Skip to content

Commit ecff5dc

Browse files
committed
Cleanup
1 parent 7c0409e commit ecff5dc

File tree

7 files changed

+64
-100
lines changed

7 files changed

+64
-100
lines changed

Cargo.lock

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

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_toolchain::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/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_toolchain::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_toolchain::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
@@ -3,12 +3,13 @@
33
use std::{
44
env, ops,
55
path::{Path, PathBuf},
6-
process::{Command, Output},
6+
process::Command,
77
};
88

9-
use anyhow::{bail, Context, Result};
9+
use anyhow::{bail, Result};
1010
use ra_arena::{Arena, Idx};
11-
use ra_toolchain::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!(

crates/ra_toolchain/Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,4 @@ 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: 32 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,26 @@
11
//! This crate contains a single public function
22
//! [`get_path_for_executable`](fn.get_path_for_executable.html).
33
//! See docs there for more information.
4-
use std::{
5-
env,
6-
path::{Path, PathBuf},
7-
process::Command,
8-
};
4+
use std::{env, iter, path::PathBuf};
95

10-
use anyhow::{bail, Result};
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+
}
1117

1218
/// Return a `PathBuf` to use for the given executable.
1319
///
1420
/// E.g., `get_path_for_executable("cargo")` may return just `cargo` if that
1521
/// gives a valid Cargo executable; or it may return a full path to a valid
1622
/// Cargo.
17-
pub fn get_path_for_executable(executable_name: &'static str) -> Result<PathBuf> {
18-
assert!(executable_name == "rustc" || executable_name == "cargo");
23+
fn get_path_for_executable(executable_name: &'static str) -> PathBuf {
1924
// The current implementation checks three places for an executable to use:
2025
// 1) Appropriate environment variable (erroring if this is set but not a usable executable)
2126
// example: for cargo, this checks $CARGO environment variable; for rustc, $RUSTC; etc
@@ -25,45 +30,35 @@ pub fn get_path_for_executable(executable_name: &'static str) -> Result<PathBuf>
2530
// example: for cargo, this tries ~/.cargo/bin/cargo
2631
// It seems that this is a reasonable place to try for cargo, rustc, and rustup
2732
let env_var = executable_name.to_ascii_uppercase();
28-
if let Ok(path) = env::var(&env_var) {
29-
return if is_valid_executable(&path) {
30-
Ok(path.into())
31-
} else {
32-
bail!(
33-
"`{}` environment variable points to something that's not a valid executable",
34-
env_var
35-
)
36-
};
33+
if let Some(path) = env::var_os(&env_var) {
34+
return path.into();
3735
}
3836

39-
if is_valid_executable(executable_name) {
40-
return Ok(executable_name.into());
37+
if lookup_in_path(executable_name) {
38+
return executable_name.into();
4139
}
4240

4341
if let Some(mut path) = home::home_dir() {
4442
path.push(".cargo");
4543
path.push("bin");
4644
path.push(executable_name);
47-
if is_valid_executable(&path) {
48-
return Ok(path);
45+
if path.is_file() {
46+
return path;
4947
}
5048
}
51-
// This error message may also be caused by $PATH or $CARGO/$RUSTC/etc not being set correctly
52-
// for VSCode, even if they are set correctly in a terminal.
53-
// On macOS in particular, launching VSCode from terminal with `code <dirname>` causes VSCode
54-
// to inherit environment variables including $PATH, $CARGO, $RUSTC, etc from that terminal;
55-
// but launching VSCode from Dock does not inherit environment variables from a terminal.
56-
// For more discussion, see #3118.
57-
bail!(
58-
"Failed to find `{}` executable. Make sure `{}` is in `$PATH`, or set `${}` to point to a valid executable.",
59-
executable_name, executable_name, env_var
60-
)
49+
executable_name.into()
6150
}
6251

63-
/// Does the given `Path` point to a usable executable?
64-
///
65-
/// (assumes the executable takes a `--version` switch and writes to stdout,
66-
/// which is true for `cargo`, `rustc`, and `rustup`)
67-
fn is_valid_executable(p: &'static str) -> bool {
68-
Command::new(p).arg("--version").output().is_ok()
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())
6964
}

0 commit comments

Comments
 (0)