From 27d238112f769c5e7ecef7db835b483eabff4e27 Mon Sep 17 00:00:00 2001 From: Amin Yahyaabadi Date: Wed, 21 Jul 2021 11:42:05 -0500 Subject: [PATCH 1/5] fix: run eslint-fix (use const, optimize regex, etc) --- lib/dist-fetch.js | 37 +++++++++++++------- lib/index.js | 75 ++++++++++++++++++++++++++--------------- lib/rust-project.js | 34 ++++++++++++------- snippets/.eslintrc.json | 6 ++++ 4 files changed, 99 insertions(+), 53 deletions(-) create mode 100644 snippets/.eslintrc.json diff --git a/lib/dist-fetch.js b/lib/dist-fetch.js index a9b5237..88052d3 100644 --- a/lib/dist-fetch.js +++ b/lib/dist-fetch.js @@ -21,7 +21,7 @@ async function checkDatedDistHasRls(date, channel = "nightly") { const dateString = _.isString(date) ? date : date.toISOString().split("T")[0] const cacheKey = `${channel}-${dateString}` - let fetch = + const fetch = datedNightlyHasRlsCache.get(cacheKey) || new Promise((resolve, reject) => { https @@ -33,7 +33,9 @@ async function checkDatedDistHasRls(date, channel = "nightly") { let body = "" res.on("data", (data) => { body += data - if (manifest_includes_rls(body)) resolve(cacheKey) + if (manifest_includes_rls(body)) { + resolve(cacheKey) + } }) res.on("end", () => reject(new Error("no 'rls-preview'"))) }) @@ -60,11 +62,16 @@ async function fetchLatestDatedDistWithRls(channel) { const check = (day) => { return checkDatedDistHasRls(day, channel).catch((e) => { - if (e && e.code === "ENOTFOUND") throw e + if (e && e.code === "ENOTFOUND") { + throw e + } const yesterday = new Date(day - aDayMillis) - if (yesterday >= minDate) return check(yesterday) - else throw new Error("No nightly with 'rls-preview'") + if (yesterday >= minDate) { + return check(yesterday) + } else { + throw new Error("No nightly with 'rls-preview'") + } }) } @@ -89,9 +96,11 @@ async function fetchLatestDist({ toolchain, currentVersion = "none" }) { res.on("data", (data) => (body += data)) res.on("end", () => { // use a subsection as toml is slow to parse fully - let rustcInfo = body.match(/(\[pkg\.rustc\][^[]*)/m) - if (!rustcInfo) return reject(new Error("could not split channel toml output")) - let rustcVersion = require("toml").parse(rustcInfo[1]).pkg.rustc.version.trim() + const rustcInfo = body.match(/(\[pkg\.rustc][^[]*)/m) + if (!rustcInfo) { + return reject(new Error("could not split channel toml output")) + } + const rustcVersion = require("toml").parse(rustcInfo[1]).pkg.rustc.version.trim() resolve( !currentVersion.trim().endsWith(rustcVersion) && manifest_includes_rls(body) && `rustc ${rustcVersion}` ) @@ -111,14 +120,14 @@ async function fetchLatestDist({ toolchain, currentVersion = "none" }) { * @returns {Promise} */ async function checkHasRls(toolchain) { - let dated = toolchain.match(DATED_REGEX) + const dated = toolchain.match(DATED_REGEX) if (dated) { return checkDatedDistHasRls(dated[2], dated[1]) .then(() => true) .catch(() => false) } return fetchLatestDist({ toolchain }) - .then((v) => !!v) + .then((v) => Boolean(v)) .catch(() => false) } @@ -127,10 +136,12 @@ async function checkHasRls(toolchain) { * @returns {Promise} Latest channel dated version with rls-preview or the channel itself if ok */ async function suggestChannelOrDated(channel) { - let latestDatedPromise = fetchLatestDatedDistWithRls(channel) + const latestDatedPromise = fetchLatestDatedDistWithRls(channel) try { - let latestIsOk = await fetchLatestDist({ toolchain: channel }) - if (latestIsOk) return channel + const latestIsOk = await fetchLatestDist({ toolchain: channel }) + if (latestIsOk) { + return channel + } } catch (e) { console.warn(e) } diff --git a/lib/index.js b/lib/index.js index fcb59c2..01eba60 100644 --- a/lib/index.js +++ b/lib/index.js @@ -26,7 +26,7 @@ async function exec(command, { cwd } = {}) { } function logErr(e, logFn = console.warn) { - e && logFn("" + e) + e && logFn(`${e}`) } function clearIdeRustNotifications(prefix = "ide-rust") { @@ -78,7 +78,7 @@ function rustupRun(toolchain, command, opts = {}) { function notifyLanguageServerCommandFailed(languageServerCmd) { clearIdeRustNotifications("ide-rust.langServerCommand") - let description = + const description = "Make sure the **rust-analyzer** binary is installed and in `$PATH`." + "\n\nSee https://rust-analyzer.github.io/manual.html#rust-analyzer-language-server-binary." @@ -92,7 +92,7 @@ function notifyLanguageServerCommandFailed(languageServerCmd) { async function rustupDefaultToolchain() { // linux: "stable-x86_64-unknown-linux-gnu (default)" // mac: "stable (default)" - let { stdout } = await exec("rustup default") + const { stdout } = await exec("rustup default") return stdout.split("-")[0].trim().split(" ")[0] } @@ -107,12 +107,12 @@ async function hasCommand(rustCommand) { /** @returns {{ path: string; toolchain: String }[]} */ async function rustupOverrides() { - let { stdout } = await exec("rustup override list") + const { stdout } = await exec("rustup override list") return stdout - .split(/[\r\n]+/g) + .split(/[\n\r]+/g) .map((line) => { // line.trimEnd is not a function ? - let lastSpace = line.trimEnd().lastIndexOf(" ") + const lastSpace = line.trimEnd().lastIndexOf(" ") return { path: line.slice(0, lastSpace).trim(), toolchain: line.slice(lastSpace).trim(), @@ -150,7 +150,9 @@ function shouldIgnoreProjectPath(projectPath) { let envPath = () => { // Make sure the cargo directory is in PATH let envPath = process.env.PATH || "" - if (!envPath.includes(".cargo/bin")) envPath += `:${path.join(os.homedir(), ".cargo/bin")}` + if (!envPath.includes(".cargo/bin")) { + envPath += `:${path.join(os.homedir(), ".cargo/bin")}` + } return envPath } @@ -236,23 +238,31 @@ class RustLanguageClient extends AutoLanguageClient { this.activeOverrides = new Set(overrides) if (this.activeOverrides.size > oldActive.size) { const confToolchain = configToolchain() || (await rustupDefaultToolchain()) - if (confToolchain) oldActive.add(confToolchain) + if (confToolchain) { + oldActive.add(confToolchain) + } this._promptToUpdateToolchain({ ignore: oldActive }) } } catch (e) { - if (await hasCommand("rustup")) logErr(e) + if (await hasCommand("rustup")) { + logErr(e) + } } } /** @param {string | null} reason Reason for the restart shown in the notification */ async _restartLanguageServers(reason) { await this.restartAllServers() - if (reason) atom.notifications.addSuccess(reason, { _src: "ide-rust" }) + if (reason) { + atom.notifications.addSuccess(reason, { _src: "ide-rust" }) + } } // check for toolchain updates if installed & not dated async _promptToUpdateToolchain({ ignore } = {}) { - if (!atom.config.get("ide-rust.checkForToolchainUpdates")) return + if (!atom.config.get("ide-rust.checkForToolchainUpdates")) { + return + } if (!(await hasCommand("rustup"))) { atom.config.set("ide-rust.checkForToolchainUpdates", false) @@ -263,7 +273,9 @@ class RustLanguageClient extends AutoLanguageClient { const toolchains = new Set(this.activeOverrides) const confToolchain = configToolchain() || (await rustupDefaultToolchain()) - if (confToolchain) toolchains.add(confToolchain) + if (confToolchain) { + toolchains.add(confToolchain) + } Array.from(toolchains) .filter((toolchain) => !ignore || !ignore.has(toolchain)) @@ -274,9 +286,11 @@ class RustLanguageClient extends AutoLanguageClient { toolchain = toolchain.split("-")[0] } - let { stdout: currentVersion } = await rustupRun(confToolchain, "rustc --version") - let newVersion = await fetchLatestDist({ toolchain, currentVersion }).catch(() => false) - if (!newVersion) return + const { stdout: currentVersion } = await rustupRun(confToolchain, "rustc --version") + const newVersion = await fetchLatestDist({ toolchain, currentVersion }).catch(() => false) + if (!newVersion) { + return + } atom.notifications.addInfo(`Rust \`${toolchain}\` toolchain update available`, { description: newVersion, @@ -339,7 +353,7 @@ class RustLanguageClient extends AutoLanguageClient { if (!(await exec("rustup --version").catch(() => false))) { this._handleMissingRustup() } else { - let clicked = await atomPrompt( + const clicked = await atomPrompt( `\`rustup\` missing ${toolchain} toolchain`, { detail: `rustup toolchain install ${toolchain}`, @@ -355,7 +369,7 @@ class RustLanguageClient extends AutoLanguageClient { .catch((e) => { console.warn(e) clearIdeRustNotifications() - let err = (e + "").split("\n") + let err = `${e}`.split("\n") err = (err.length && err[0]) || `Error installing rust \`${toolchain}\`` atom.notifications.addError(err, { detail: "Check the toolchain is valid & connection is available", @@ -374,10 +388,11 @@ class RustLanguageClient extends AutoLanguageClient { async _handleMissingRustup() { try { let description = "Installs from https://www.rustup.rs" - if (process.platform === "linux") + if (process.platform === "linux") { description += ", alternatively install rustup with _`apt install rustup`_ or similar and restart." + } - let clicked = await atomPrompt( + const clicked = await atomPrompt( "`rustup` is not available", { description, @@ -388,7 +403,7 @@ class RustLanguageClient extends AutoLanguageClient { if (clicked === "Install") { // Install rustup and try again - let installRustupPromise = installRustup() + const installRustupPromise = installRustup() if (this.busySignalService) { this.busySignalService.reportBusyWhile(`Installing rustup`, () => installRustupPromise) } @@ -424,7 +439,9 @@ class RustLanguageClient extends AutoLanguageClient { // watch config toolchain updates -> check for updates if enabling this.disposables.add( atom.config.onDidChange("ide-rust.checkForToolchainUpdates", ({ newValue: enabled }) => { - if (enabled) this._promptToUpdateToolchain().catch(logErr) + if (enabled) { + this._promptToUpdateToolchain().catch(logErr) + } }) ) @@ -455,7 +472,7 @@ class RustLanguageClient extends AutoLanguageClient { postInitialization(server) { // track the server so we can keep its config updated - let project = new RustProject(server, () => this.busySignalService) + const project = new RustProject(server, () => this.busySignalService) this.projects[server.projectPath] = project server.process.on("exit", () => { @@ -545,11 +562,11 @@ class RustLanguageClient extends AutoLanguageClient { // only used for local variables by the language server. This makes the // outline view cleaner and more useful. provideOutlines() { - let provide = super.provideOutlines() - let superOutline = provide.getOutline + const provide = super.provideOutlines() + const superOutline = provide.getOutline provide.getOutline = async (...args) => { - let outline = await superOutline.apply(this, args) + const outline = await superOutline.apply(this, args) outline.outlineTrees = outline.outlineTrees.filter((o) => o.icon !== "type-variable") return outline } @@ -584,7 +601,7 @@ class RustLanguageClient extends AutoLanguageClient { * @returns {Promise} */ async getDatatip(editor, ...args) { - let datatip = await super.getDatatip(editor, ...args) + const datatip = await super.getDatatip(editor, ...args) try { if (datatip) { datatip.markedStrings = datatip.markedStrings @@ -613,7 +630,7 @@ class RustLanguageClient extends AutoLanguageClient { */ function convertMarkdownToSnippets(value) { // even indices are text, odds are rust snippets - return value.split(/\s*```rust\s*((?:.|\s)+?)\s*```/).map((bit, index) => { + return value.split(/\s*```rust\s*([\s.]+?)\s*```/).map((bit, index) => { if (index % 2 == 0) { return { type: "markdown", @@ -647,7 +664,9 @@ if (process.platform === "win32") { envPath = () => { // Make sure the cargo directory is in PATH let envPath = process.env.PATH || "" - if (!envPath.includes(".cargo\\bin")) envPath += `;${path.join(os.homedir(), ".cargo", "bin")}` + if (!envPath.includes(".cargo\\bin")) { + envPath += `;${path.join(os.homedir(), ".cargo", "bin")}` + } return envPath } diff --git a/lib/rust-project.js b/lib/rust-project.js index c6f6f01..2ef43b0 100644 --- a/lib/rust-project.js +++ b/lib/rust-project.js @@ -43,7 +43,9 @@ class RustProject { // Handle r.a progress messages onProgress({ token, value }) { const busySignal = this.getBusySignalService() - if (!busySignal) return + if (!busySignal) { + return + } let { kind, title, message, percentage } = value @@ -52,7 +54,9 @@ class RustProject { let busyMessage = this._progress.get(token) if (done) { - if (busyMessage) busyMessage.dispose() + if (busyMessage) { + busyMessage.dispose() + } this._progress.delete(token) } else { if (busyMessage) { @@ -62,8 +66,12 @@ class RustProject { title = title || busyMessage.lastProgressTitle } let busyText = `${path.basename(this.server.projectPath)} ${title || "r.a"}` - if (percentage) busyText += ` ${percentage.toFixed()}%` - if (message) busyText += `: ${message}` + if (percentage) { + busyText += ` ${percentage.toFixed()}%` + } + if (message) { + busyText += `: ${message}` + } if (busyMessage) { busyMessage.setTitle(busyText) @@ -80,10 +88,10 @@ class RustProject { // Send rls.toml as `workspace/didChangeConfiguration` message (or default if no rls.toml) sendRlsTomlConfig() { - let rlsTomlPath = path.join(this.server.projectPath, "rls.toml") + const rlsTomlPath = path.join(this.server.projectPath, "rls.toml") fs.readFile(rlsTomlPath, (err, data) => { - let config = this.defaultConfig() + const config = this.defaultConfig() if (!err) { try { Object.assign(config, toml.parse(data)) @@ -92,7 +100,9 @@ class RustProject { } } - if (_.isEqual(config, this._lastSentConfig)) return + if (_.isEqual(config, this._lastSentConfig)) { + return + } this.server.connection.didChangeConfiguration({ settings: { @@ -149,7 +159,7 @@ async function handleMultiCrateProjectErrors(projectPath, errorNote) { (errorNote.getMessage() || "").startsWith("could not find `Cargo.toml`") && detail.endsWith(projectPath) ) { - let root_manifest = await asyncLstat(path.join(projectPath, "Cargo.toml")).catch(() => false) + const root_manifest = await asyncLstat(path.join(projectPath, "Cargo.toml")).catch(() => false) if (root_manifest) { return } @@ -158,10 +168,10 @@ async function handleMultiCrateProjectErrors(projectPath, errorNote) { const ls = await callbackAsync(fs.readdir)(projectPath) const childProjects = [] for (const f of ls) { - let file = path.join(projectPath, f) - let stat = await asyncLstat(file) + const file = path.join(projectPath, f) + const stat = await asyncLstat(file) if (stat.isDirectory()) { - let has_manifest = await asyncLstat(path.join(file, "Cargo.toml")).catch(() => false) + const has_manifest = await asyncLstat(path.join(file, "Cargo.toml")).catch(() => false) if (has_manifest) { childProjects.push(f) } @@ -172,7 +182,7 @@ async function handleMultiCrateProjectErrors(projectPath, errorNote) { let newNote const projects = childProjects.map((p) => `"${p}"`).join(", ") const workspaceManifest = `[workspace]\nmembers = [${projects}]` - let options = { + const options = { _src: "ide-rust", dismissable: true, description: `Child projects without a root (or higher) workspace are not supported. A root manifest at _${path.join( diff --git a/snippets/.eslintrc.json b/snippets/.eslintrc.json new file mode 100644 index 0000000..2ef1976 --- /dev/null +++ b/snippets/.eslintrc.json @@ -0,0 +1,6 @@ +{ + "extends": "../.eslintrc", + "rules": { + "no-template-curly-in-string": "off" + } +} From 720d53e8ae0117a54f709b3d19fdcfef6dabf497 Mon Sep 17 00:00:00 2001 From: Amin Yahyaabadi Date: Wed, 21 Jul 2021 11:44:27 -0500 Subject: [PATCH 2/5] fix: remove excess async from the functions that return a Promise --- lib/dist-fetch.js | 8 ++++---- lib/index.js | 2 +- lib/rust-project.js | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/dist-fetch.js b/lib/dist-fetch.js index 88052d3..4c37cc4 100644 --- a/lib/dist-fetch.js +++ b/lib/dist-fetch.js @@ -17,7 +17,7 @@ function manifest_includes_rls(manifest) { * @param {string} [channel] Defaults to `nightly` * @returns {Promise} Toolchain name */ -async function checkDatedDistHasRls(date, channel = "nightly") { +function checkDatedDistHasRls(date, channel = "nightly") { const dateString = _.isString(date) ? date : date.toISOString().split("T")[0] const cacheKey = `${channel}-${dateString}` @@ -56,7 +56,7 @@ async function checkDatedDistHasRls(date, channel = "nightly") { * @param {string} [channel] Defaults to `nightly` * @returns {Promise} Latest channel dated version with rls-preview */ -async function fetchLatestDatedDistWithRls(channel) { +function fetchLatestDatedDistWithRls(channel) { const aDayMillis = 24 * 60 * 60 * 1000 const minDate = new Date(Date.now() - 30 * aDayMillis) @@ -83,7 +83,7 @@ async function fetchLatestDatedDistWithRls(channel) { * @param {string} [arg.currentVersion] Current installed rustc version * @returns {Promise} New version of update available (falsy otherwise) */ -async function fetchLatestDist({ toolchain, currentVersion = "none" }) { +function fetchLatestDist({ toolchain, currentVersion = "none" }) { return new Promise((resolve, reject) => { https .get(`https://static.rust-lang.org/dist/channel-rust-${toolchain}.toml`, (res) => { @@ -119,7 +119,7 @@ async function fetchLatestDist({ toolchain, currentVersion = "none" }) { * @param {string} toolchain * @returns {Promise} */ -async function checkHasRls(toolchain) { +function checkHasRls(toolchain) { const dated = toolchain.match(DATED_REGEX) if (dated) { return checkDatedDistHasRls(dated[2], dated[1]) diff --git a/lib/index.js b/lib/index.js index 01eba60..fa34de5 100644 --- a/lib/index.js +++ b/lib/index.js @@ -10,7 +10,7 @@ const { showConflictingPackageWarnings } = require("./competition.js") /** @type {number} interval Between toolchain update checks, milliseconds */ const PERIODIC_UPDATE_CHECK_MILLIS = 6 * 60 * 60 * 1000 -async function exec(command, { cwd } = {}) { +function exec(command, { cwd } = {}) { return new Promise((resolve, reject) => { const env = process.env env.PATH = envPath() diff --git a/lib/rust-project.js b/lib/rust-project.js index 2ef43b0..b761f36 100644 --- a/lib/rust-project.js +++ b/lib/rust-project.js @@ -126,7 +126,7 @@ class RustProject { * @returns {function} Async function */ function callbackAsync(functionWithCallback) { - return async (...args) => { + return (...args) => { return new Promise((resolve, reject) => { functionWithCallback(...args, (err, ...out) => { if (err) { From fad513bbe1ab3f3f78ed257b55b537042fe1678b Mon Sep 17 00:00:00 2001 From: Amin Yahyaabadi Date: Wed, 21 Jul 2021 11:45:51 -0500 Subject: [PATCH 3/5] fix: use === --- lib/competition.js | 2 +- lib/index.js | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/competition.js b/lib/competition.js index f8855ff..38e6a26 100644 --- a/lib/competition.js +++ b/lib/competition.js @@ -19,7 +19,7 @@ const CONFLICTING_PACKAGES = [ * @returns {boolean} */ function alreadyNotifying(pkg) { - return atom.notifications.getNotifications().some((note) => note.getOptions()._src == `ide-rust-conflict-${pkg}`) + return atom.notifications.getNotifications().some((note) => note.getOptions()._src === `ide-rust-conflict-${pkg}`) } /** Scans current active packages and shows notifications to help handle conflicts */ diff --git a/lib/index.js b/lib/index.js index fa34de5..e278c47 100644 --- a/lib/index.js +++ b/lib/index.js @@ -15,7 +15,7 @@ function exec(command, { cwd } = {}) { const env = process.env env.PATH = envPath() cp.exec(command, { env, cwd }, (err, stdout, stderr) => { - if (err != null) { + if (err !== null) { reject(err) return } @@ -631,7 +631,7 @@ class RustLanguageClient extends AutoLanguageClient { function convertMarkdownToSnippets(value) { // even indices are text, odds are rust snippets return value.split(/\s*```rust\s*([\s.]+?)\s*```/).map((bit, index) => { - if (index % 2 == 0) { + if (index % 2 === 0) { return { type: "markdown", value: bit, From a84d542fc5acb38c61bef42efcdf4b10ada052e6 Mon Sep 17 00:00:00 2001 From: Amin Yahyaabadi Date: Wed, 21 Jul 2021 11:49:20 -0500 Subject: [PATCH 4/5] chore: ignore class-methods-use-this --- lib/index.js | 3 +++ lib/rust-project.js | 1 + 2 files changed, 4 insertions(+) diff --git a/lib/index.js b/lib/index.js index e278c47..e3dc31f 100644 --- a/lib/index.js +++ b/lib/index.js @@ -485,6 +485,7 @@ class RustLanguageClient extends AutoLanguageClient { this._refreshActiveOverrides() } + /* eslint-disable class-methods-use-this */ getGrammarScopes() { return ["source.rust", "rust"] } @@ -506,6 +507,7 @@ class RustLanguageClient extends AutoLanguageClient { !filePath.includes("/target/release/") ) } + /* eslint-enable class-methods-use-this */ // Kill servers fast (#196) shutdownGracefully = false @@ -580,6 +582,7 @@ class RustLanguageClient extends AutoLanguageClient { * @param {(ls.Command | ls.CodeAction)[]} actions * @returns {(ls.Command | ls.CodeAction)[]} Filtered actions */ + /* eslint-disable-next-line class-methods-use-this */ filterCodeActions(actions) { return actions.filter((a) => !a.command || a.command.command !== "rust-analyzer.applySourceChange") } diff --git a/lib/rust-project.js b/lib/rust-project.js index b761f36..2e3b741 100644 --- a/lib/rust-project.js +++ b/lib/rust-project.js @@ -114,6 +114,7 @@ class RustProject { } // Default Rls config according to package settings & Rls defaults + /* eslint-disable-next-line class-methods-use-this */ defaultConfig() { return {} } From 28c1d532ae772e940ba7a55c53812a781ea7cc64 Mon Sep 17 00:00:00 2001 From: Amin Yahyaabadi Date: Wed, 21 Jul 2021 11:51:33 -0500 Subject: [PATCH 5/5] fix: use if --- lib/index.js | 9 ++++++--- lib/rust-project.js | 4 +++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/lib/index.js b/lib/index.js index e3dc31f..2b4607f 100644 --- a/lib/index.js +++ b/lib/index.js @@ -26,7 +26,9 @@ function exec(command, { cwd } = {}) { } function logErr(e, logFn = console.warn) { - e && logFn(`${e}`) + if (e) { + logFn(`${e}`) + } } function clearIdeRustNotifications(prefix = "ide-rust") { @@ -307,11 +309,12 @@ class RustLanguageClient extends AutoLanguageClient { .then(() => this._restartLanguageServers(`Updated rust toolchain`)) .catch((e) => { logErr(e) - e && + if (e) { atom.notifications.addError(`\`rustup update ${toolchain}\` failed`, { detail: e, dismissable: true, }) + } }) if (this.busySignalService) { @@ -413,7 +416,7 @@ class RustLanguageClient extends AutoLanguageClient { .catch(logErr) } } catch (e) { - e && console.warn(e) + console.warn(e) } } diff --git a/lib/rust-project.js b/lib/rust-project.js index 2e3b741..fc3dce5 100644 --- a/lib/rust-project.js +++ b/lib/rust-project.js @@ -36,7 +36,9 @@ class RustProject { this.server.process.on("exit", () => { this._progress.forEach((msg) => msg.dispose()) this._progress.clear() - this._rustDocBusyMessage && this._rustDocBusyMessage.dispose() + if (this._rustDocBusyMessage) { + this._rustDocBusyMessage.dispose() + } }) }