Merge #4329
4329: Look for `cargo`, `rustc`, and `rustup` in standard installation path r=matklad a=cdisselkoen
Discussed in #3118. This is approximately a 90% fix for the issue described there.
This PR creates a new crate `ra_env` with a function `get_path_for_executable()`; see docs there. `get_path_for_executable()` improves and generalizes the function `cargo_binary()` which was previously duplicated in the `ra_project_model` and `ra_flycheck` crates. (Both of those crates now depend on the new `ra_env` crate.) The new function checks (e.g.) `$CARGO` and `$PATH`, but also falls back on `~/.cargo/bin` manually before erroring out. This should allow most users to not have to worry about setting the `$CARGO` or `$PATH` variables for VSCode, which can be difficult e.g. on macOS as discussed in #3118.
I've attempted to replace all calls to `cargo`, `rustc`, and `rustup` in rust-analyzer with appropriate invocations of `get_path_for_executable()`; I don't think I've missed any in Rust code, but there is at least one invocation in TypeScript code which I haven't fixed. (I'm not sure whether it's affected by the same problem or not.) a4778ddb7a/editors/code/src/cargo.ts (L79)
I'm sure this PR could be improved a bunch, so I'm happy to take feedback/suggestions on how to solve this problem better, or just bikeshedding variable/function/crate names etc.
cc @Veetaha
Fixes #3118.
Co-authored-by: Craig Disselkoen <craigdissel@gmail.com>
Co-authored-by: veetaha <veetaha2@gmail.com>
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
import * as cp from 'child_process';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import * as readline from 'readline';
|
||||
import { OutputChannel } from 'vscode';
|
||||
import { isValidExecutable } from './util';
|
||||
|
||||
interface CompilationArtifact {
|
||||
fileName: string;
|
||||
@@ -10,17 +13,9 @@ interface CompilationArtifact {
|
||||
}
|
||||
|
||||
export class Cargo {
|
||||
rootFolder: string;
|
||||
env?: Record<string, string>;
|
||||
output: OutputChannel;
|
||||
constructor(readonly rootFolder: string, readonly output: OutputChannel) { }
|
||||
|
||||
public constructor(cargoTomlFolder: string, output: OutputChannel, env: Record<string, string> | undefined = undefined) {
|
||||
this.rootFolder = cargoTomlFolder;
|
||||
this.output = output;
|
||||
this.env = env;
|
||||
}
|
||||
|
||||
public async artifactsFromArgs(cargoArgs: string[]): Promise<CompilationArtifact[]> {
|
||||
private async artifactsFromArgs(cargoArgs: string[]): Promise<CompilationArtifact[]> {
|
||||
const artifacts: CompilationArtifact[] = [];
|
||||
|
||||
try {
|
||||
@@ -37,17 +32,13 @@ export class Cargo {
|
||||
isTest: message.profile.test
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (message.reason === 'compiler-message') {
|
||||
} else if (message.reason === 'compiler-message') {
|
||||
this.output.append(message.message.rendered);
|
||||
}
|
||||
},
|
||||
stderr => {
|
||||
this.output.append(stderr);
|
||||
}
|
||||
stderr => this.output.append(stderr),
|
||||
);
|
||||
}
|
||||
catch (err) {
|
||||
} catch (err) {
|
||||
this.output.show(true);
|
||||
throw new Error(`Cargo invocation has failed: ${err}`);
|
||||
}
|
||||
@@ -55,9 +46,8 @@ export class Cargo {
|
||||
return artifacts;
|
||||
}
|
||||
|
||||
public async executableFromArgs(args: string[]): Promise<string> {
|
||||
const cargoArgs = [...args]; // to remain args unchanged
|
||||
cargoArgs.push("--message-format=json");
|
||||
async executableFromArgs(args: readonly string[]): Promise<string> {
|
||||
const cargoArgs = [...args, "--message-format=json"];
|
||||
|
||||
const artifacts = await this.artifactsFromArgs(cargoArgs);
|
||||
|
||||
@@ -70,24 +60,27 @@ export class Cargo {
|
||||
return artifacts[0].fileName;
|
||||
}
|
||||
|
||||
runCargo(
|
||||
private runCargo(
|
||||
cargoArgs: string[],
|
||||
onStdoutJson: (obj: any) => void,
|
||||
onStderrString: (data: string) => void
|
||||
): Promise<number> {
|
||||
return new Promise<number>((resolve, reject) => {
|
||||
const cargo = cp.spawn('cargo', cargoArgs, {
|
||||
return new Promise((resolve, reject) => {
|
||||
let cargoPath;
|
||||
try {
|
||||
cargoPath = getCargoPathOrFail();
|
||||
} catch (err) {
|
||||
return reject(err);
|
||||
}
|
||||
|
||||
const cargo = cp.spawn(cargoPath, cargoArgs, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
cwd: this.rootFolder,
|
||||
env: this.env,
|
||||
cwd: this.rootFolder
|
||||
});
|
||||
|
||||
cargo.on('error', err => {
|
||||
reject(new Error(`could not launch cargo: ${err}`));
|
||||
});
|
||||
cargo.stderr.on('data', chunk => {
|
||||
onStderrString(chunk.toString());
|
||||
});
|
||||
cargo.on('error', err => reject(new Error(`could not launch cargo: ${err}`)));
|
||||
|
||||
cargo.stderr.on('data', chunk => onStderrString(chunk.toString()));
|
||||
|
||||
const rl = readline.createInterface({ input: cargo.stdout });
|
||||
rl.on('line', line => {
|
||||
@@ -103,4 +96,28 @@ export class Cargo {
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mirrors `ra_env::get_path_for_executable` implementation
|
||||
function getCargoPathOrFail(): string {
|
||||
const envVar = process.env.CARGO;
|
||||
const executableName = "cargo";
|
||||
|
||||
if (envVar) {
|
||||
if (isValidExecutable(envVar)) return envVar;
|
||||
|
||||
throw new Error(`\`${envVar}\` environment variable points to something that's not a valid executable`);
|
||||
}
|
||||
|
||||
if (isValidExecutable(executableName)) return executableName;
|
||||
|
||||
const standardLocation = path.join(os.homedir(), '.cargo', 'bin', executableName);
|
||||
|
||||
if (isValidExecutable(standardLocation)) return standardLocation;
|
||||
|
||||
throw new Error(
|
||||
`Failed to find \`${executableName}\` executable. ` +
|
||||
`Make sure \`${executableName}\` is in \`$PATH\`, ` +
|
||||
`or set \`${envVar}\` to point to a valid executable.`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -119,8 +119,11 @@ export function debugSingle(ctx: Ctx): Cmd {
|
||||
}
|
||||
|
||||
if (!debugEngine) {
|
||||
vscode.window.showErrorMessage(`Install [CodeLLDB](https://marketplace.visualstudio.com/items?itemName=${lldbId})`
|
||||
+ ` or [MS C++ tools](https://marketplace.visualstudio.com/items?itemName=${cpptoolsId}) extension for debugging.`);
|
||||
vscode.window.showErrorMessage(
|
||||
`Install [CodeLLDB](https://marketplace.visualstudio.com/items?itemName=${lldbId}) ` +
|
||||
`or [MS C++ tools](https://marketplace.visualstudio.com/items?itemName=${cpptoolsId}) ` +
|
||||
`extension for debugging.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,10 +8,9 @@ import { activateInlayHints } from './inlay_hints';
|
||||
import { activateStatusDisplay } from './status_display';
|
||||
import { Ctx } from './ctx';
|
||||
import { Config, NIGHTLY_TAG } from './config';
|
||||
import { log, assert } from './util';
|
||||
import { log, assert, isValidExecutable } from './util';
|
||||
import { PersistentState } from './persistent_state';
|
||||
import { fetchRelease, download } from './net';
|
||||
import { spawnSync } from 'child_process';
|
||||
import { activateTaskProvider } from './tasks';
|
||||
|
||||
let ctx: Ctx | undefined;
|
||||
@@ -179,10 +178,7 @@ async function bootstrapServer(config: Config, state: PersistentState): Promise<
|
||||
|
||||
log.debug("Using server binary at", path);
|
||||
|
||||
const res = spawnSync(path, ["--version"], { encoding: 'utf8' });
|
||||
log.debug("Checked binary availability via --version", res);
|
||||
log.debug(res, "--version output:", res.output);
|
||||
if (res.status !== 0) {
|
||||
if (!isValidExecutable(path)) {
|
||||
throw new Error(`Failed to execute ${path} --version`);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as lc from "vscode-languageclient";
|
||||
import * as vscode from "vscode";
|
||||
import { strict as nativeAssert } from "assert";
|
||||
import { spawnSync } from "child_process";
|
||||
|
||||
export function assert(condition: boolean, explanation: string): asserts condition {
|
||||
try {
|
||||
@@ -82,3 +83,13 @@ export function isRustDocument(document: vscode.TextDocument): document is RustD
|
||||
export function isRustEditor(editor: vscode.TextEditor): editor is RustEditor {
|
||||
return isRustDocument(editor.document);
|
||||
}
|
||||
|
||||
export function isValidExecutable(path: string): boolean {
|
||||
log.debug("Checking availability of a binary at", path);
|
||||
|
||||
const res = spawnSync(path, ["--version"], { encoding: 'utf8' });
|
||||
|
||||
log.debug(res, "--version output:", res.output);
|
||||
|
||||
return res.status === 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user