Skip to content

Commit 51e4b92

Browse files
bors[bot]matklad
andauthored
Merge #4375
4375: Cleanup toolchain handling r=matklad a=matklad bors r+ 🤖 Co-authored-by: Aleksey Kladov <[email protected]>
2 parents 8295a93 + ecff5dc commit 51e4b92

File tree

10 files changed

+108
-141
lines changed

10 files changed

+108
-141
lines changed

Cargo.lock

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

crates/ra_env/src/lib.rs

Lines changed: 0 additions & 66 deletions
This file was deleted.

crates/ra_flycheck/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +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" }
17+
ra_toolchain = { path = "../ra_toolchain" }
1818

1919
[dev-dependencies]
2020
insta = "0.16.0"

crates/ra_flycheck/src/lib.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ use lsp_types::{
1616
CodeAction, CodeActionOrCommand, Diagnostic, Url, WorkDoneProgress, WorkDoneProgressBegin,
1717
WorkDoneProgressEnd, WorkDoneProgressReport,
1818
};
19-
use ra_env::get_path_for_executable;
2019

2120
use crate::conv::{map_rust_diagnostic_to_lsp, MappedRustDiagnostic};
2221

@@ -216,10 +215,10 @@ impl FlycheckThread {
216215

217216
let mut cmd = match &self.config {
218217
FlycheckConfig::CargoCommand { command, all_targets, all_features, extra_args } => {
219-
let mut cmd = Command::new(get_path_for_executable("cargo").unwrap());
218+
let mut cmd = Command::new(ra_toolchain::cargo());
220219
cmd.arg(command);
221-
cmd.args(&["--workspace", "--message-format=json", "--manifest-path"]);
222-
cmd.arg(self.workspace_root.join("Cargo.toml"));
220+
cmd.args(&["--workspace", "--message-format=json", "--manifest-path"])
221+
.arg(self.workspace_root.join("Cargo.toml"));
223222
if *all_targets {
224223
cmd.arg("--all-targets");
225224
}

crates/ra_project_model/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ cargo_metadata = "0.9.1"
1616
ra_arena = { path = "../ra_arena" }
1717
ra_cfg = { path = "../ra_cfg" }
1818
ra_db = { path = "../ra_db" }
19-
ra_env = { path = "../ra_env" }
19+
ra_toolchain = { path = "../ra_toolchain" }
2020
ra_proc_macro = { path = "../ra_proc_macro" }
2121

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

crates/ra_project_model/src/cargo_workspace.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ use anyhow::{Context, Result};
1111
use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId};
1212
use ra_arena::{Arena, Idx};
1313
use ra_db::Edition;
14-
use ra_env::get_path_for_executable;
1514
use rustc_hash::FxHashMap;
1615

1716
/// `CargoWorkspace` represents the logical structure of, well, a Cargo
@@ -147,7 +146,7 @@ impl CargoWorkspace {
147146
cargo_features: &CargoConfig,
148147
) -> Result<CargoWorkspace> {
149148
let mut meta = MetadataCommand::new();
150-
meta.cargo_path(get_path_for_executable("cargo")?);
149+
meta.cargo_path(ra_toolchain::cargo());
151150
meta.manifest_path(cargo_toml);
152151
if cargo_features.all_features {
153152
meta.features(CargoOpt::AllFeatures);
@@ -289,7 +288,7 @@ pub fn load_extern_resources(
289288
cargo_toml: &Path,
290289
cargo_features: &CargoConfig,
291290
) -> Result<ExternResources> {
292-
let mut cmd = Command::new(get_path_for_executable("cargo")?);
291+
let mut cmd = Command::new(ra_toolchain::cargo());
293292
cmd.args(&["check", "--message-format=json", "--manifest-path"]).arg(cargo_toml);
294293
if cargo_features.all_features {
295294
cmd.arg("--all-features");

crates/ra_project_model/src/lib.rs

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,12 @@ use std::{
88
fs::{read_dir, File, ReadDir},
99
io::{self, BufReader},
1010
path::{Path, PathBuf},
11-
process::Command,
11+
process::{Command, Output},
1212
};
1313

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;
1817
use rustc_hash::FxHashMap;
1918
use serde_json::from_reader;
2019

@@ -568,25 +567,18 @@ pub fn get_rustc_cfg_options(target: Option<&String>) -> CfgOptions {
568567
}
569568
}
570569

571-
match (|| -> Result<String> {
570+
let rustc_cfgs = || -> Result<String> {
572571
// `cfg(test)` and `cfg(debug_assertion)` are handled outside, so we suppress them here.
573-
let mut cmd = Command::new(get_path_for_executable("rustc")?);
572+
let mut cmd = Command::new(ra_toolchain::rustc());
574573
cmd.args(&["--print", "cfg", "-O"]);
575574
if let Some(target) = target {
576575
cmd.args(&["--target", target.as_str()]);
577576
}
578-
let output = cmd.output().context("Failed to get output from rustc --print cfg -O")?;
579-
if !output.status.success() {
580-
bail!(
581-
"rustc --print cfg -O exited with exit code ({})",
582-
output
583-
.status
584-
.code()
585-
.map_or(String::from("no exit code"), |code| format!("{}", code))
586-
);
587-
}
577+
let output = output(cmd)?;
588578
Ok(String::from_utf8(output.stdout)?)
589-
})() {
579+
}();
580+
581+
match rustc_cfgs {
590582
Ok(rustc_cfgs) => {
591583
for line in rustc_cfgs.lines() {
592584
match line.find('=') {
@@ -599,8 +591,16 @@ pub fn get_rustc_cfg_options(target: Option<&String>) -> CfgOptions {
599591
}
600592
}
601593
}
602-
Err(e) => log::error!("failed to get rustc cfgs: {}", e),
594+
Err(e) => log::error!("failed to get rustc cfgs: {:#}", e),
603595
}
604596

605597
cfg_options
606598
}
599+
600+
fn output(mut cmd: Command) -> Result<Output> {
601+
let output = cmd.output().with_context(|| format!("{:?} failed", cmd))?;
602+
if !output.status.success() {
603+
bail!("{:?} failed, {}", cmd, output.status)
604+
}
605+
Ok(output)
606+
}

crates/ra_project_model/src/sysroot.rs

Lines changed: 11 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
//! FIXME: write short doc here
22
3-
use anyhow::{bail, Context, Result};
43
use std::{
54
env, ops,
65
path::{Path, PathBuf},
7-
process::{Command, Output},
6+
process::Command,
87
};
98

9+
use anyhow::{bail, Result};
1010
use ra_arena::{Arena, Idx};
11-
use ra_env::get_path_for_executable;
11+
12+
use crate::output;
1213

1314
#[derive(Default, Debug, Clone)]
1415
pub struct Sysroot {
@@ -85,50 +86,22 @@ impl Sysroot {
8586
}
8687
}
8788

88-
fn create_command_text(program: &str, args: &[&str]) -> String {
89-
format!("{} {}", program, args.join(" "))
90-
}
91-
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");
98-
let output = Command::new(program)
99-
.current_dir(cargo_toml.as_ref().parent().unwrap())
100-
.args(args)
101-
.output()
102-
.context(format!("{} failed", create_command_text(program, args)))?;
103-
if !output.status.success() {
104-
match output.status.code() {
105-
Some(code) => bail!(
106-
"failed to run the command: '{}' exited with code {}",
107-
create_command_text(program, args),
108-
code
109-
),
110-
None => bail!(
111-
"failed to run the command: '{}' terminated by signal",
112-
create_command_text(program, args)
113-
),
114-
};
115-
}
116-
Ok(output)
117-
}
118-
11989
fn get_or_install_rust_src(cargo_toml: &Path) -> Result<PathBuf> {
12090
if let Ok(path) = env::var("RUST_SRC_PATH") {
12191
return Ok(path.into());
12292
}
123-
let rustc = get_path_for_executable("rustc")?;
124-
let rustc_output = run_command_in_cargo_dir(cargo_toml, &rustc, &["--print", "sysroot"])?;
93+
let current_dir = cargo_toml.parent().unwrap();
94+
let mut rustc = Command::new(ra_toolchain::rustc());
95+
rustc.current_dir(current_dir).args(&["--print", "sysroot"]);
96+
let rustc_output = output(rustc)?;
12597
let stdout = String::from_utf8(rustc_output.stdout)?;
12698
let sysroot_path = Path::new(stdout.trim());
12799
let src_path = sysroot_path.join("lib/rustlib/src/rust/src");
128100

129101
if !src_path.exists() {
130-
let rustup = get_path_for_executable("rustup")?;
131-
run_command_in_cargo_dir(cargo_toml, &rustup, &["component", "add", "rust-src"])?;
102+
let mut rustup = Command::new(ra_toolchain::rustup());
103+
rustup.current_dir(current_dir).args(&["component", "add", "rust-src"]);
104+
let _output = output(rustup)?;
132105
}
133106
if !src_path.exists() {
134107
bail!(
Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
[package]
22
edition = "2018"
3-
name = "ra_env"
3+
name = "ra_toolchain"
44
version = "0.1.0"
55
authors = ["rust-analyzer developers"]
66

77
[dependencies]
8-
anyhow = "1.0.26"
98
home = "0.5.3"

crates/ra_toolchain/src/lib.rs

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
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+
use std::{env, iter, path::PathBuf};
5+
6+
pub fn cargo() -> PathBuf {
7+
get_path_for_executable("cargo")
8+
}
9+
10+
pub fn rustc() -> PathBuf {
11+
get_path_for_executable("rustc")
12+
}
13+
14+
pub fn rustup() -> PathBuf {
15+
get_path_for_executable("rustup")
16+
}
17+
18+
/// Return a `PathBuf` to use for the given executable.
19+
///
20+
/// E.g., `get_path_for_executable("cargo")` may return just `cargo` if that
21+
/// gives a valid Cargo executable; or it may return a full path to a valid
22+
/// Cargo.
23+
fn get_path_for_executable(executable_name: &'static str) -> PathBuf {
24+
// The current implementation checks three places for an executable to use:
25+
// 1) Appropriate environment variable (erroring if this is set but not a usable executable)
26+
// example: for cargo, this checks $CARGO environment variable; for rustc, $RUSTC; etc
27+
// 2) `<executable_name>`
28+
// example: for cargo, this tries just `cargo`, which will succeed if `cargo` is on the $PATH
29+
// 3) `~/.cargo/bin/<executable_name>`
30+
// example: for cargo, this tries ~/.cargo/bin/cargo
31+
// It seems that this is a reasonable place to try for cargo, rustc, and rustup
32+
let env_var = executable_name.to_ascii_uppercase();
33+
if let Some(path) = env::var_os(&env_var) {
34+
return path.into();
35+
}
36+
37+
if lookup_in_path(executable_name) {
38+
return executable_name.into();
39+
}
40+
41+
if let Some(mut path) = home::home_dir() {
42+
path.push(".cargo");
43+
path.push("bin");
44+
path.push(executable_name);
45+
if path.is_file() {
46+
return path;
47+
}
48+
}
49+
executable_name.into()
50+
}
51+
52+
fn lookup_in_path(exec: &str) -> bool {
53+
let paths = env::var_os("PATH").unwrap_or_default();
54+
let mut candidates = env::split_paths(&paths).flat_map(|path| {
55+
let candidate = path.join(&exec);
56+
let with_exe = if env::consts::EXE_EXTENSION == "" {
57+
None
58+
} else {
59+
Some(candidate.with_extension(env::consts::EXE_EXTENSION))
60+
};
61+
iter::once(candidate).chain(with_exe)
62+
});
63+
candidates.any(|it| it.is_file())
64+
}

0 commit comments

Comments
 (0)