aboutsummaryrefslogtreecommitdiff
path: root/crates/toolchain
diff options
context:
space:
mode:
Diffstat (limited to 'crates/toolchain')
-rw-r--r--crates/toolchain/Cargo.toml12
-rw-r--r--crates/toolchain/src/lib.rs66
2 files changed, 78 insertions, 0 deletions
diff --git a/crates/toolchain/Cargo.toml b/crates/toolchain/Cargo.toml
new file mode 100644
index 000000000..4856668f8
--- /dev/null
+++ b/crates/toolchain/Cargo.toml
@@ -0,0 +1,12 @@
1[package]
2name = "toolchain"
3version = "0.0.0"
4license = "MIT OR Apache-2.0"
5authors = ["rust-analyzer developers"]
6edition = "2018"
7
8[lib]
9doctest = false
10
11[dependencies]
12home = "0.5.3"
diff --git a/crates/toolchain/src/lib.rs b/crates/toolchain/src/lib.rs
new file mode 100644
index 000000000..3b6886f5b
--- /dev/null
+++ b/crates/toolchain/src/lib.rs
@@ -0,0 +1,66 @@
1//! Discovery of `cargo` & `rustc` executables.
2use std::{env, iter, path::PathBuf};
3
4pub fn cargo() -> PathBuf {
5 get_path_for_executable("cargo")
6}
7
8pub fn rustc() -> PathBuf {
9 get_path_for_executable("rustc")
10}
11
12pub fn rustup() -> PathBuf {
13 get_path_for_executable("rustup")
14}
15
16pub fn rustfmt() -> PathBuf {
17 get_path_for_executable("rustfmt")
18}
19
20/// Return a `PathBuf` to use for the given executable.
21///
22/// E.g., `get_path_for_executable("cargo")` may return just `cargo` if that
23/// gives a valid Cargo executable; or it may return a full path to a valid
24/// Cargo.
25fn get_path_for_executable(executable_name: &'static str) -> PathBuf {
26 // The current implementation checks three places for an executable to use:
27 // 1) Appropriate environment variable (erroring if this is set but not a usable executable)
28 // example: for cargo, this checks $CARGO environment variable; for rustc, $RUSTC; etc
29 // 2) `<executable_name>`
30 // example: for cargo, this tries just `cargo`, which will succeed if `cargo` is on the $PATH
31 // 3) `~/.cargo/bin/<executable_name>`
32 // example: for cargo, this tries ~/.cargo/bin/cargo
33 // It seems that this is a reasonable place to try for cargo, rustc, and rustup
34 let env_var = executable_name.to_ascii_uppercase();
35 if let Some(path) = env::var_os(&env_var) {
36 return path.into();
37 }
38
39 if lookup_in_path(executable_name) {
40 return executable_name.into();
41 }
42
43 if let Some(mut path) = home::home_dir() {
44 path.push(".cargo");
45 path.push("bin");
46 path.push(executable_name);
47 if let Some(path) = probe(path) {
48 return path;
49 }
50 }
51
52 executable_name.into()
53}
54
55fn lookup_in_path(exec: &str) -> bool {
56 let paths = env::var_os("PATH").unwrap_or_default();
57 env::split_paths(&paths).map(|path| path.join(exec)).find_map(probe).is_some()
58}
59
60fn probe(path: PathBuf) -> Option<PathBuf> {
61 let with_extension = match env::consts::EXE_EXTENSION {
62 "" => None,
63 it => Some(path.with_extension(it)),
64 };
65 iter::once(path).chain(with_extension).find(|it| it.is_file())
66}