diff options
author | bors[bot] <26634292+bors[bot]@users.noreply.github.com> | 2020-05-08 13:55:55 +0100 |
---|---|---|
committer | GitHub <[email protected]> | 2020-05-08 13:55:55 +0100 |
commit | 51e4b92c1eee25cb6bf1b5ec8e7633dfc5f67a45 (patch) | |
tree | 871ebe102579fd2c8a35d2d5df4ed18b27219fd6 | |
parent | 8295a9340c1fbda805497035054ead0b10c0d88e (diff) | |
parent | ecff5dc141046c5b9e40639657247a05fb9b0344 (diff) |
Merge #4375
4375: Cleanup toolchain handling r=matklad a=matklad
bors r+
🤖
Co-authored-by: Aleksey Kladov <[email protected]>
-rw-r--r-- | Cargo.lock | 19 | ||||
-rw-r--r-- | crates/ra_env/src/lib.rs | 66 | ||||
-rw-r--r-- | crates/ra_flycheck/Cargo.toml | 2 | ||||
-rw-r--r-- | crates/ra_flycheck/src/lib.rs | 7 | ||||
-rw-r--r-- | crates/ra_project_model/Cargo.toml | 2 | ||||
-rw-r--r-- | crates/ra_project_model/src/cargo_workspace.rs | 5 | ||||
-rw-r--r-- | crates/ra_project_model/src/lib.rs | 32 | ||||
-rw-r--r-- | crates/ra_project_model/src/sysroot.rs | 49 | ||||
-rw-r--r-- | crates/ra_toolchain/Cargo.toml (renamed from crates/ra_env/Cargo.toml) | 3 | ||||
-rw-r--r-- | crates/ra_toolchain/src/lib.rs | 64 |
10 files changed, 108 insertions, 141 deletions
diff --git a/Cargo.lock b/Cargo.lock index 36cff6402..41855f22e 100644 --- a/Cargo.lock +++ b/Cargo.lock | |||
@@ -958,14 +958,6 @@ dependencies = [ | |||
958 | ] | 958 | ] |
959 | 959 | ||
960 | [[package]] | 960 | [[package]] |
961 | name = "ra_env" | ||
962 | version = "0.1.0" | ||
963 | dependencies = [ | ||
964 | "anyhow", | ||
965 | "home", | ||
966 | ] | ||
967 | |||
968 | [[package]] | ||
969 | name = "ra_flycheck" | 961 | name = "ra_flycheck" |
970 | version = "0.1.0" | 962 | version = "0.1.0" |
971 | dependencies = [ | 963 | dependencies = [ |
@@ -975,7 +967,7 @@ dependencies = [ | |||
975 | "jod-thread", | 967 | "jod-thread", |
976 | "log", | 968 | "log", |
977 | "lsp-types", | 969 | "lsp-types", |
978 | "ra_env", | 970 | "ra_toolchain", |
979 | "serde_json", | 971 | "serde_json", |
980 | ] | 972 | ] |
981 | 973 | ||
@@ -1180,8 +1172,8 @@ dependencies = [ | |||
1180 | "ra_arena", | 1172 | "ra_arena", |
1181 | "ra_cfg", | 1173 | "ra_cfg", |
1182 | "ra_db", | 1174 | "ra_db", |
1183 | "ra_env", | ||
1184 | "ra_proc_macro", | 1175 | "ra_proc_macro", |
1176 | "ra_toolchain", | ||
1185 | "rustc-hash", | 1177 | "rustc-hash", |
1186 | "serde", | 1178 | "serde", |
1187 | "serde_json", | 1179 | "serde_json", |
@@ -1214,6 +1206,13 @@ dependencies = [ | |||
1214 | ] | 1206 | ] |
1215 | 1207 | ||
1216 | [[package]] | 1208 | [[package]] |
1209 | name = "ra_toolchain" | ||
1210 | version = "0.1.0" | ||
1211 | dependencies = [ | ||
1212 | "home", | ||
1213 | ] | ||
1214 | |||
1215 | [[package]] | ||
1217 | name = "ra_tt" | 1216 | name = "ra_tt" |
1218 | version = "0.1.0" | 1217 | version = "0.1.0" |
1219 | dependencies = [ | 1218 | dependencies = [ |
diff --git a/crates/ra_env/src/lib.rs b/crates/ra_env/src/lib.rs deleted file mode 100644 index 413da1982..000000000 --- a/crates/ra_env/src/lib.rs +++ /dev/null | |||
@@ -1,66 +0,0 @@ | |||
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 | } | ||
diff --git a/crates/ra_flycheck/Cargo.toml b/crates/ra_flycheck/Cargo.toml index d0f7fb2dc..03e557148 100644 --- a/crates/ra_flycheck/Cargo.toml +++ b/crates/ra_flycheck/Cargo.toml | |||
@@ -14,7 +14,7 @@ log = "0.4.8" | |||
14 | cargo_metadata = "0.9.1" | 14 | cargo_metadata = "0.9.1" |
15 | serde_json = "1.0.48" | 15 | serde_json = "1.0.48" |
16 | jod-thread = "0.1.1" | 16 | jod-thread = "0.1.1" |
17 | ra_env = { path = "../ra_env" } | 17 | ra_toolchain = { path = "../ra_toolchain" } |
18 | 18 | ||
19 | [dev-dependencies] | 19 | [dev-dependencies] |
20 | insta = "0.16.0" | 20 | insta = "0.16.0" |
diff --git a/crates/ra_flycheck/src/lib.rs b/crates/ra_flycheck/src/lib.rs index d8b727b0e..68dcee285 100644 --- a/crates/ra_flycheck/src/lib.rs +++ b/crates/ra_flycheck/src/lib.rs | |||
@@ -16,7 +16,6 @@ use lsp_types::{ | |||
16 | CodeAction, CodeActionOrCommand, Diagnostic, Url, WorkDoneProgress, WorkDoneProgressBegin, | 16 | CodeAction, CodeActionOrCommand, Diagnostic, Url, WorkDoneProgress, WorkDoneProgressBegin, |
17 | WorkDoneProgressEnd, WorkDoneProgressReport, | 17 | WorkDoneProgressEnd, WorkDoneProgressReport, |
18 | }; | 18 | }; |
19 | use ra_env::get_path_for_executable; | ||
20 | 19 | ||
21 | use crate::conv::{map_rust_diagnostic_to_lsp, MappedRustDiagnostic}; | 20 | use crate::conv::{map_rust_diagnostic_to_lsp, MappedRustDiagnostic}; |
22 | 21 | ||
@@ -216,10 +215,10 @@ impl FlycheckThread { | |||
216 | 215 | ||
217 | let mut cmd = match &self.config { | 216 | let mut cmd = match &self.config { |
218 | FlycheckConfig::CargoCommand { command, all_targets, all_features, extra_args } => { | 217 | 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()); |
220 | cmd.arg(command); | 219 | cmd.arg(command); |
221 | cmd.args(&["--workspace", "--message-format=json", "--manifest-path"]); | 220 | cmd.args(&["--workspace", "--message-format=json", "--manifest-path"]) |
222 | cmd.arg(self.workspace_root.join("Cargo.toml")); | 221 | .arg(self.workspace_root.join("Cargo.toml")); |
223 | if *all_targets { | 222 | if *all_targets { |
224 | cmd.arg("--all-targets"); | 223 | cmd.arg("--all-targets"); |
225 | } | 224 | } |
diff --git a/crates/ra_project_model/Cargo.toml b/crates/ra_project_model/Cargo.toml index 626478468..a32a5daab 100644 --- a/crates/ra_project_model/Cargo.toml +++ b/crates/ra_project_model/Cargo.toml | |||
@@ -16,7 +16,7 @@ cargo_metadata = "0.9.1" | |||
16 | ra_arena = { path = "../ra_arena" } | 16 | ra_arena = { path = "../ra_arena" } |
17 | ra_cfg = { path = "../ra_cfg" } | 17 | ra_cfg = { path = "../ra_cfg" } |
18 | ra_db = { path = "../ra_db" } | 18 | ra_db = { path = "../ra_db" } |
19 | ra_env = { path = "../ra_env" } | 19 | ra_toolchain = { path = "../ra_toolchain" } |
20 | ra_proc_macro = { path = "../ra_proc_macro" } | 20 | ra_proc_macro = { path = "../ra_proc_macro" } |
21 | 21 | ||
22 | serde = { version = "1.0.106", features = ["derive"] } | 22 | serde = { version = "1.0.106", features = ["derive"] } |
diff --git a/crates/ra_project_model/src/cargo_workspace.rs b/crates/ra_project_model/src/cargo_workspace.rs index eb9f33ee8..082af4f96 100644 --- a/crates/ra_project_model/src/cargo_workspace.rs +++ b/crates/ra_project_model/src/cargo_workspace.rs | |||
@@ -11,7 +11,6 @@ use anyhow::{Context, Result}; | |||
11 | use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId}; | 11 | use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId}; |
12 | use ra_arena::{Arena, Idx}; | 12 | use ra_arena::{Arena, Idx}; |
13 | use ra_db::Edition; | 13 | use ra_db::Edition; |
14 | use ra_env::get_path_for_executable; | ||
15 | use rustc_hash::FxHashMap; | 14 | use rustc_hash::FxHashMap; |
16 | 15 | ||
17 | /// `CargoWorkspace` represents the logical structure of, well, a Cargo | 16 | /// `CargoWorkspace` represents the logical structure of, well, a Cargo |
@@ -147,7 +146,7 @@ impl CargoWorkspace { | |||
147 | cargo_features: &CargoConfig, | 146 | cargo_features: &CargoConfig, |
148 | ) -> Result<CargoWorkspace> { | 147 | ) -> Result<CargoWorkspace> { |
149 | let mut meta = MetadataCommand::new(); | 148 | let mut meta = MetadataCommand::new(); |
150 | meta.cargo_path(get_path_for_executable("cargo")?); | 149 | meta.cargo_path(ra_toolchain::cargo()); |
151 | meta.manifest_path(cargo_toml); | 150 | meta.manifest_path(cargo_toml); |
152 | if cargo_features.all_features { | 151 | if cargo_features.all_features { |
153 | meta.features(CargoOpt::AllFeatures); | 152 | meta.features(CargoOpt::AllFeatures); |
@@ -289,7 +288,7 @@ pub fn load_extern_resources( | |||
289 | cargo_toml: &Path, | 288 | cargo_toml: &Path, |
290 | cargo_features: &CargoConfig, | 289 | cargo_features: &CargoConfig, |
291 | ) -> Result<ExternResources> { | 290 | ) -> Result<ExternResources> { |
292 | let mut cmd = Command::new(get_path_for_executable("cargo")?); | 291 | let mut cmd = Command::new(ra_toolchain::cargo()); |
293 | cmd.args(&["check", "--message-format=json", "--manifest-path"]).arg(cargo_toml); | 292 | cmd.args(&["check", "--message-format=json", "--manifest-path"]).arg(cargo_toml); |
294 | if cargo_features.all_features { | 293 | if cargo_features.all_features { |
295 | cmd.arg("--all-features"); | 294 | cmd.arg("--all-features"); |
diff --git a/crates/ra_project_model/src/lib.rs b/crates/ra_project_model/src/lib.rs index 88a6ffb2a..5a0a87ed7 100644 --- a/crates/ra_project_model/src/lib.rs +++ b/crates/ra_project_model/src/lib.rs | |||
@@ -8,13 +8,12 @@ use std::{ | |||
8 | fs::{read_dir, File, ReadDir}, | 8 | fs::{read_dir, File, ReadDir}, |
9 | io::{self, BufReader}, | 9 | io::{self, BufReader}, |
10 | path::{Path, PathBuf}, | 10 | path::{Path, PathBuf}, |
11 | process::Command, | 11 | process::{Command, Output}, |
12 | }; | 12 | }; |
13 | 13 | ||
14 | use anyhow::{bail, Context, Result}; | 14 | use anyhow::{bail, Context, Result}; |
15 | use ra_cfg::CfgOptions; | 15 | use ra_cfg::CfgOptions; |
16 | use ra_db::{CrateGraph, CrateName, Edition, Env, ExternSource, ExternSourceId, FileId}; | 16 | use ra_db::{CrateGraph, CrateName, Edition, Env, ExternSource, ExternSourceId, FileId}; |
17 | use ra_env::get_path_for_executable; | ||
18 | use rustc_hash::FxHashMap; | 17 | use rustc_hash::FxHashMap; |
19 | use serde_json::from_reader; | 18 | use serde_json::from_reader; |
20 | 19 | ||
@@ -568,25 +567,18 @@ pub fn get_rustc_cfg_options(target: Option<&String>) -> CfgOptions { | |||
568 | } | 567 | } |
569 | } | 568 | } |
570 | 569 | ||
571 | match (|| -> Result<String> { | 570 | let rustc_cfgs = || -> Result<String> { |
572 | // `cfg(test)` and `cfg(debug_assertion)` are handled outside, so we suppress them here. | 571 | // `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()); |
574 | cmd.args(&["--print", "cfg", "-O"]); | 573 | cmd.args(&["--print", "cfg", "-O"]); |
575 | if let Some(target) = target { | 574 | if let Some(target) = target { |
576 | cmd.args(&["--target", target.as_str()]); | 575 | cmd.args(&["--target", target.as_str()]); |
577 | } | 576 | } |
578 | let output = cmd.output().context("Failed to get output from rustc --print cfg -O")?; | 577 | let output = output(cmd)?; |
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 | } | ||
588 | Ok(String::from_utf8(output.stdout)?) | 578 | Ok(String::from_utf8(output.stdout)?) |
589 | })() { | 579 | }(); |
580 | |||
581 | match rustc_cfgs { | ||
590 | Ok(rustc_cfgs) => { | 582 | Ok(rustc_cfgs) => { |
591 | for line in rustc_cfgs.lines() { | 583 | for line in rustc_cfgs.lines() { |
592 | match line.find('=') { | 584 | match line.find('=') { |
@@ -599,8 +591,16 @@ pub fn get_rustc_cfg_options(target: Option<&String>) -> CfgOptions { | |||
599 | } | 591 | } |
600 | } | 592 | } |
601 | } | 593 | } |
602 | Err(e) => log::error!("failed to get rustc cfgs: {}", e), | 594 | Err(e) => log::error!("failed to get rustc cfgs: {:#}", e), |
603 | } | 595 | } |
604 | 596 | ||
605 | cfg_options | 597 | cfg_options |
606 | } | 598 | } |
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 | } | ||
diff --git a/crates/ra_project_model/src/sysroot.rs b/crates/ra_project_model/src/sysroot.rs index 11c26ad89..a8a196e64 100644 --- a/crates/ra_project_model/src/sysroot.rs +++ b/crates/ra_project_model/src/sysroot.rs | |||
@@ -1,14 +1,15 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! FIXME: write short doc here |
2 | 2 | ||
3 | use anyhow::{bail, Context, Result}; | ||
4 | use std::{ | 3 | use std::{ |
5 | env, ops, | 4 | env, ops, |
6 | path::{Path, PathBuf}, | 5 | path::{Path, PathBuf}, |
7 | process::{Command, Output}, | 6 | process::Command, |
8 | }; | 7 | }; |
9 | 8 | ||
9 | use anyhow::{bail, Result}; | ||
10 | use ra_arena::{Arena, Idx}; | 10 | use ra_arena::{Arena, Idx}; |
11 | use ra_env::get_path_for_executable; | 11 | |
12 | use crate::output; | ||
12 | 13 | ||
13 | #[derive(Default, Debug, Clone)] | 14 | #[derive(Default, Debug, Clone)] |
14 | pub struct Sysroot { | 15 | pub struct Sysroot { |
@@ -85,50 +86,22 @@ impl Sysroot { | |||
85 | } | 86 | } |
86 | } | 87 | } |
87 | 88 | ||
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 | |||
119 | fn get_or_install_rust_src(cargo_toml: &Path) -> Result<PathBuf> { | 89 | fn get_or_install_rust_src(cargo_toml: &Path) -> Result<PathBuf> { |
120 | if let Ok(path) = env::var("RUST_SRC_PATH") { | 90 | if let Ok(path) = env::var("RUST_SRC_PATH") { |
121 | return Ok(path.into()); | 91 | return Ok(path.into()); |
122 | } | 92 | } |
123 | let rustc = get_path_for_executable("rustc")?; | 93 | let current_dir = cargo_toml.parent().unwrap(); |
124 | let rustc_output = run_command_in_cargo_dir(cargo_toml, &rustc, &["--print", "sysroot"])?; | 94 | let mut rustc = Command::new(ra_toolchain::rustc()); |
95 | rustc.current_dir(current_dir).args(&["--print", "sysroot"]); | ||
96 | let rustc_output = output(rustc)?; | ||
125 | let stdout = String::from_utf8(rustc_output.stdout)?; | 97 | let stdout = String::from_utf8(rustc_output.stdout)?; |
126 | let sysroot_path = Path::new(stdout.trim()); | 98 | let sysroot_path = Path::new(stdout.trim()); |
127 | let src_path = sysroot_path.join("lib/rustlib/src/rust/src"); | 99 | let src_path = sysroot_path.join("lib/rustlib/src/rust/src"); |
128 | 100 | ||
129 | if !src_path.exists() { | 101 | if !src_path.exists() { |
130 | let rustup = get_path_for_executable("rustup")?; | 102 | let mut rustup = Command::new(ra_toolchain::rustup()); |
131 | run_command_in_cargo_dir(cargo_toml, &rustup, &["component", "add", "rust-src"])?; | 103 | rustup.current_dir(current_dir).args(&["component", "add", "rust-src"]); |
104 | let _output = output(rustup)?; | ||
132 | } | 105 | } |
133 | if !src_path.exists() { | 106 | if !src_path.exists() { |
134 | bail!( | 107 | bail!( |
diff --git a/crates/ra_env/Cargo.toml b/crates/ra_toolchain/Cargo.toml index f0a401be5..1873fbe16 100644 --- a/crates/ra_env/Cargo.toml +++ b/crates/ra_toolchain/Cargo.toml | |||
@@ -1,9 +1,8 @@ | |||
1 | [package] | 1 | [package] |
2 | edition = "2018" | 2 | edition = "2018" |
3 | name = "ra_env" | 3 | name = "ra_toolchain" |
4 | version = "0.1.0" | 4 | version = "0.1.0" |
5 | authors = ["rust-analyzer developers"] | 5 | authors = ["rust-analyzer developers"] |
6 | 6 | ||
7 | [dependencies] | 7 | [dependencies] |
8 | anyhow = "1.0.26" | ||
9 | home = "0.5.3" | 8 | home = "0.5.3" |
diff --git a/crates/ra_toolchain/src/lib.rs b/crates/ra_toolchain/src/lib.rs new file mode 100644 index 000000000..3c307a0ea --- /dev/null +++ b/crates/ra_toolchain/src/lib.rs | |||
@@ -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 | } | ||