Skip to content

Commit 8295a93

Browse files
bors[bot]cdisselkoenVeetaha
authored
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.) https://github.com/rust-analyzer/rust-analyzer/blob/a4778ddb7a00f552a8e653bbf56ae9fd69cfe1d3/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 <[email protected]> Co-authored-by: veetaha <[email protected]>
2 parents 363c1f2 + 3077eae commit 8295a93

File tree

13 files changed

+183
-63
lines changed

13 files changed

+183
-63
lines changed

Cargo.lock

Lines changed: 19 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

crates/ra_env/Cargo.toml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
[package]
2+
edition = "2018"
3+
name = "ra_env"
4+
version = "0.1.0"
5+
authors = ["rust-analyzer developers"]
6+
7+
[dependencies]
8+
anyhow = "1.0.26"
9+
home = "0.5.3"

crates/ra_env/src/lib.rs

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
//! This crate contains a single public function
2+
//! [`get_path_for_executable`](fn.get_path_for_executable.html).
3+
//! See docs there for more information.
4+
5+
use anyhow::{bail, Result};
6+
use std::env;
7+
use std::path::{Path, PathBuf};
8+
use std::process::Command;
9+
10+
/// Return a `PathBuf` to use for the given executable.
11+
///
12+
/// E.g., `get_path_for_executable("cargo")` may return just `cargo` if that
13+
/// gives a valid Cargo executable; or it may return a full path to a valid
14+
/// Cargo.
15+
pub fn get_path_for_executable(executable_name: impl AsRef<str>) -> Result<PathBuf> {
16+
// The current implementation checks three places for an executable to use:
17+
// 1) Appropriate environment variable (erroring if this is set but not a usable executable)
18+
// example: for cargo, this checks $CARGO environment variable; for rustc, $RUSTC; etc
19+
// 2) `<executable_name>`
20+
// example: for cargo, this tries just `cargo`, which will succeed if `cargo` is on the $PATH
21+
// 3) `~/.cargo/bin/<executable_name>`
22+
// example: for cargo, this tries ~/.cargo/bin/cargo
23+
// It seems that this is a reasonable place to try for cargo, rustc, and rustup
24+
let executable_name = executable_name.as_ref();
25+
let env_var = executable_name.to_ascii_uppercase();
26+
if let Ok(path) = env::var(&env_var) {
27+
if is_valid_executable(&path) {
28+
Ok(path.into())
29+
} else {
30+
bail!(
31+
"`{}` environment variable points to something that's not a valid executable",
32+
env_var
33+
)
34+
}
35+
} else {
36+
if is_valid_executable(executable_name) {
37+
return Ok(executable_name.into());
38+
}
39+
if let Some(mut path) = ::home::home_dir() {
40+
path.push(".cargo");
41+
path.push("bin");
42+
path.push(executable_name);
43+
if is_valid_executable(&path) {
44+
return Ok(path);
45+
}
46+
}
47+
// This error message may also be caused by $PATH or $CARGO/$RUSTC/etc not being set correctly
48+
// for VSCode, even if they are set correctly in a terminal.
49+
// On macOS in particular, launching VSCode from terminal with `code <dirname>` causes VSCode
50+
// to inherit environment variables including $PATH, $CARGO, $RUSTC, etc from that terminal;
51+
// but launching VSCode from Dock does not inherit environment variables from a terminal.
52+
// For more discussion, see #3118.
53+
bail!(
54+
"Failed to find `{}` executable. Make sure `{}` is in `$PATH`, or set `${}` to point to a valid executable.",
55+
executable_name, executable_name, env_var
56+
)
57+
}
58+
}
59+
60+
/// Does the given `Path` point to a usable executable?
61+
///
62+
/// (assumes the executable takes a `--version` switch and writes to stdout,
63+
/// which is true for `cargo`, `rustc`, and `rustup`)
64+
fn is_valid_executable(p: impl AsRef<Path>) -> bool {
65+
Command::new(p.as_ref()).arg("--version").output().is_ok()
66+
}

crates/ra_flycheck/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ log = "0.4.8"
1414
cargo_metadata = "0.9.1"
1515
serde_json = "1.0.48"
1616
jod-thread = "0.1.1"
17+
ra_env = { path = "../ra_env" }
1718

1819
[dev-dependencies]
1920
insta = "0.16.0"

crates/ra_flycheck/src/lib.rs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
mod conv;
55

66
use std::{
7-
env,
87
io::{self, BufRead, BufReader},
98
path::PathBuf,
109
process::{Command, Stdio},
@@ -17,6 +16,7 @@ use lsp_types::{
1716
CodeAction, CodeActionOrCommand, Diagnostic, Url, WorkDoneProgress, WorkDoneProgressBegin,
1817
WorkDoneProgressEnd, WorkDoneProgressReport,
1918
};
19+
use ra_env::get_path_for_executable;
2020

2121
use crate::conv::{map_rust_diagnostic_to_lsp, MappedRustDiagnostic};
2222

@@ -216,7 +216,7 @@ impl FlycheckThread {
216216

217217
let mut cmd = match &self.config {
218218
FlycheckConfig::CargoCommand { command, all_targets, all_features, extra_args } => {
219-
let mut cmd = Command::new(cargo_binary());
219+
let mut cmd = Command::new(get_path_for_executable("cargo").unwrap());
220220
cmd.arg(command);
221221
cmd.args(&["--workspace", "--message-format=json", "--manifest-path"]);
222222
cmd.arg(self.workspace_root.join("Cargo.toml"));
@@ -337,7 +337,3 @@ fn run_cargo(
337337

338338
Ok(())
339339
}
340-
341-
fn cargo_binary() -> String {
342-
env::var("CARGO").unwrap_or_else(|_| "cargo".to_string())
343-
}

crates/ra_project_model/Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,9 @@ rustc-hash = "1.1.0"
1414
cargo_metadata = "0.9.1"
1515

1616
ra_arena = { path = "../ra_arena" }
17-
ra_db = { path = "../ra_db" }
1817
ra_cfg = { path = "../ra_cfg" }
18+
ra_db = { path = "../ra_db" }
19+
ra_env = { path = "../ra_env" }
1920
ra_proc_macro = { path = "../ra_proc_macro" }
2021

2122
serde = { version = "1.0.106", features = ["derive"] }

crates/ra_project_model/src/cargo_workspace.rs

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
//! FIXME: write short doc here
22
33
use std::{
4-
env,
54
ffi::OsStr,
65
ops,
76
path::{Path, PathBuf},
@@ -12,6 +11,7 @@ use anyhow::{Context, Result};
1211
use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId};
1312
use ra_arena::{Arena, Idx};
1413
use ra_db::Edition;
14+
use ra_env::get_path_for_executable;
1515
use rustc_hash::FxHashMap;
1616

1717
/// `CargoWorkspace` represents the logical structure of, well, a Cargo
@@ -146,12 +146,8 @@ impl CargoWorkspace {
146146
cargo_toml: &Path,
147147
cargo_features: &CargoConfig,
148148
) -> Result<CargoWorkspace> {
149-
let _ = Command::new(cargo_binary())
150-
.arg("--version")
151-
.output()
152-
.context("failed to run `cargo --version`, is `cargo` in PATH?")?;
153-
154149
let mut meta = MetadataCommand::new();
150+
meta.cargo_path(get_path_for_executable("cargo")?);
155151
meta.manifest_path(cargo_toml);
156152
if cargo_features.all_features {
157153
meta.features(CargoOpt::AllFeatures);
@@ -293,7 +289,7 @@ pub fn load_extern_resources(
293289
cargo_toml: &Path,
294290
cargo_features: &CargoConfig,
295291
) -> Result<ExternResources> {
296-
let mut cmd = Command::new(cargo_binary());
292+
let mut cmd = Command::new(get_path_for_executable("cargo")?);
297293
cmd.args(&["check", "--message-format=json", "--manifest-path"]).arg(cargo_toml);
298294
if cargo_features.all_features {
299295
cmd.arg("--all-features");
@@ -347,7 +343,3 @@ fn is_dylib(path: &Path) -> bool {
347343
Some(ext) => matches!(ext.as_str(), "dll" | "dylib" | "so"),
348344
}
349345
}
350-
351-
fn cargo_binary() -> String {
352-
env::var("CARGO").unwrap_or_else(|_| "cargo".to_string())
353-
}

crates/ra_project_model/src/lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use std::{
1414
use anyhow::{bail, Context, Result};
1515
use ra_cfg::CfgOptions;
1616
use ra_db::{CrateGraph, CrateName, Edition, Env, ExternSource, ExternSourceId, FileId};
17+
use ra_env::get_path_for_executable;
1718
use rustc_hash::FxHashMap;
1819
use serde_json::from_reader;
1920

@@ -569,7 +570,7 @@ pub fn get_rustc_cfg_options(target: Option<&String>) -> CfgOptions {
569570

570571
match (|| -> Result<String> {
571572
// `cfg(test)` and `cfg(debug_assertion)` are handled outside, so we suppress them here.
572-
let mut cmd = Command::new("rustc");
573+
let mut cmd = Command::new(get_path_for_executable("rustc")?);
573574
cmd.args(&["--print", "cfg", "-O"]);
574575
if let Some(target) = target {
575576
cmd.args(&["--target", target.as_str()]);

crates/ra_project_model/src/sysroot.rs

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use std::{
88
};
99

1010
use ra_arena::{Arena, Idx};
11+
use ra_env::get_path_for_executable;
1112

1213
#[derive(Default, Debug, Clone)]
1314
pub struct Sysroot {
@@ -88,9 +89,14 @@ fn create_command_text(program: &str, args: &[&str]) -> String {
8889
format!("{} {}", program, args.join(" "))
8990
}
9091

91-
fn run_command_in_cargo_dir(cargo_toml: &Path, program: &str, args: &[&str]) -> Result<Output> {
92+
fn run_command_in_cargo_dir(
93+
cargo_toml: impl AsRef<Path>,
94+
program: impl AsRef<Path>,
95+
args: &[&str],
96+
) -> Result<Output> {
97+
let program = program.as_ref().as_os_str().to_str().expect("Invalid Unicode in path");
9298
let output = Command::new(program)
93-
.current_dir(cargo_toml.parent().unwrap())
99+
.current_dir(cargo_toml.as_ref().parent().unwrap())
94100
.args(args)
95101
.output()
96102
.context(format!("{} failed", create_command_text(program, args)))?;
@@ -114,13 +120,15 @@ fn get_or_install_rust_src(cargo_toml: &Path) -> Result<PathBuf> {
114120
if let Ok(path) = env::var("RUST_SRC_PATH") {
115121
return Ok(path.into());
116122
}
117-
let rustc_output = run_command_in_cargo_dir(cargo_toml, "rustc", &["--print", "sysroot"])?;
123+
let rustc = get_path_for_executable("rustc")?;
124+
let rustc_output = run_command_in_cargo_dir(cargo_toml, &rustc, &["--print", "sysroot"])?;
118125
let stdout = String::from_utf8(rustc_output.stdout)?;
119126
let sysroot_path = Path::new(stdout.trim());
120127
let src_path = sysroot_path.join("lib/rustlib/src/rust/src");
121128

122129
if !src_path.exists() {
123-
run_command_in_cargo_dir(cargo_toml, "rustup", &["component", "add", "rust-src"])?;
130+
let rustup = get_path_for_executable("rustup")?;
131+
run_command_in_cargo_dir(cargo_toml, &rustup, &["component", "add", "rust-src"])?;
124132
}
125133
if !src_path.exists() {
126134
bail!(

0 commit comments

Comments
 (0)