]> git.proxmox.com Git - rustc.git/blame - src/tools/rust-analyzer/crates/toolchain/src/lib.rs
New upstream version 1.68.2+dfsg1
[rustc.git] / src / tools / rust-analyzer / crates / toolchain / src / lib.rs
CommitLineData
064997fb
FG
1//! Discovery of `cargo` & `rustc` executables.
2
3#![warn(rust_2018_idioms, unused_lifetimes, semicolon_in_expressions_from_macros)]
4
5use std::{env, iter, path::PathBuf};
6
7pub fn cargo() -> PathBuf {
8 get_path_for_executable("cargo")
9}
10
11pub fn rustc() -> PathBuf {
12 get_path_for_executable("rustc")
13}
14
15pub fn rustup() -> PathBuf {
16 get_path_for_executable("rustup")
17}
18
19pub fn rustfmt() -> PathBuf {
20 get_path_for_executable("rustfmt")
21}
22
23/// Return a `PathBuf` to use for the given executable.
24///
25/// E.g., `get_path_for_executable("cargo")` may return just `cargo` if that
26/// gives a valid Cargo executable; or it may return a full path to a valid
27/// Cargo.
28fn get_path_for_executable(executable_name: &'static str) -> PathBuf {
29 // The current implementation checks three places for an executable to use:
30 // 1) Appropriate environment variable (erroring if this is set but not a usable executable)
31 // example: for cargo, this checks $CARGO environment variable; for rustc, $RUSTC; etc
32 // 2) `<executable_name>`
33 // example: for cargo, this tries just `cargo`, which will succeed if `cargo` is on the $PATH
34 // 3) `~/.cargo/bin/<executable_name>`
35 // example: for cargo, this tries ~/.cargo/bin/cargo
36 // It seems that this is a reasonable place to try for cargo, rustc, and rustup
37 let env_var = executable_name.to_ascii_uppercase();
f25598a0 38 if let Some(path) = env::var_os(env_var) {
064997fb
FG
39 return path.into();
40 }
41
42 if lookup_in_path(executable_name) {
43 return executable_name.into();
44 }
45
46 if let Some(mut path) = home::home_dir() {
47 path.push(".cargo");
48 path.push("bin");
49 path.push(executable_name);
50 if let Some(path) = probe(path) {
51 return path;
52 }
53 }
54
55 executable_name.into()
56}
57
58fn lookup_in_path(exec: &str) -> bool {
59 let paths = env::var_os("PATH").unwrap_or_default();
60 env::split_paths(&paths).map(|path| path.join(exec)).find_map(probe).is_some()
61}
62
63fn probe(path: PathBuf) -> Option<PathBuf> {
64 let with_extension = match env::consts::EXE_EXTENSION {
65 "" => None,
66 it => Some(path.with_extension(it)),
67 };
68 iter::once(path).chain(with_extension).find(|it| it.is_file())
69}