Skip to main content

tilo_process/
tools.rs

1//! Where a person's command-line tools live.
2//!
3//! A desktop session often hands its apps a narrower PATH than the person's terminal: a
4//! tool installed the usual way must still be found, so [`ToolDirs::current`] looks in
5//! the process's own PATH, the per-user install folders, and the PATH the login shell
6//! sets up. The page has no programs to run.
7
8use std::ffi::{OsStr, OsString};
9use std::path::{Path, PathBuf};
10use std::sync::OnceLock;
11
12static LOGIN_PATH: OnceLock<Option<OsString>> = OnceLock::new();
13
14#[derive(Clone, Debug, Default, PartialEq, Eq)]
15pub struct ToolDirs {
16    dirs: Vec<PathBuf>,
17}
18
19impl ToolDirs {
20    #[must_use]
21    pub fn of(path: Option<&OsStr>, home: Option<&Path>, login_path: Option<&OsStr>) -> Self {
22        let mut dirs: Vec<PathBuf> = path
23            .map(|path| std::env::split_paths(path).collect())
24            .unwrap_or_default();
25        if let Some(home) = home {
26            dirs.push(home.join(".cargo").join("bin"));
27            dirs.push(home.join(".local").join("bin"));
28        }
29        if let Some(login) = login_path {
30            dirs.extend(std::env::split_paths(login));
31        }
32        let mut seen = std::collections::HashSet::new();
33        dirs.retain(|dir| dir.is_absolute() && seen.insert(dir.clone()));
34        Self { dirs }
35    }
36
37    #[must_use]
38    pub fn current() -> Self {
39        backend::current()
40    }
41
42    #[must_use]
43    pub fn find(&self, name: &str) -> Option<PathBuf> {
44        self.dirs
45            .iter()
46            .find_map(|dir| backend::program(&dir.join(name)))
47    }
48}
49
50#[must_use]
51pub fn runs(program: &str) -> bool {
52    if program.contains('/') {
53        return backend::program(Path::new(program)).is_some();
54    }
55    ToolDirs::current().find(program).is_some()
56}
57
58#[must_use]
59pub fn login_path_read() -> bool {
60    LOGIN_PATH.get().is_some()
61}
62
63pub fn read_login_path() {
64    if login_path_read() {
65        return;
66    }
67    let spawned = std::thread::Builder::new()
68        .name("login-path".into())
69        .spawn(|| {
70            let _ = LOGIN_PATH.set(backend::login_shell_path());
71        });
72    if spawned.is_err() {
73        let _ = LOGIN_PATH.set(None);
74    }
75}
76
77#[cfg(unix)]
78mod backend {
79    use std::ffi::OsString;
80    use std::os::unix::ffi::OsStringExt;
81    use std::os::unix::fs::PermissionsExt;
82    use std::path::{Path, PathBuf};
83
84    // A profile that waits on something must not hold a thread and a shell forever.
85    const PROFILE_BOUND: std::time::Duration = std::time::Duration::from_secs(10);
86    const PATH_LIMIT: usize = 64 * 1024;
87
88    pub(super) fn current() -> super::ToolDirs {
89        let home = std::env::var_os("HOME").map(PathBuf::from);
90        let login = super::LOGIN_PATH.get().and_then(Option::as_deref);
91        super::ToolDirs::of(std::env::var_os("PATH").as_deref(), home.as_deref(), login)
92    }
93
94    pub(super) fn login_shell_path() -> Option<OsString> {
95        let shell = crate::login_shell::login_shell();
96        let output = bounded_command::run_os(
97            shell,
98            &["-l", "-c", "printf %s \"$PATH\""],
99            None,
100            PATH_LIMIT,
101            PROFILE_BOUND,
102        )
103        .ok()?;
104        (output.status.success() && !output.stdout.is_empty())
105            .then(|| OsString::from_vec(output.stdout))
106    }
107
108    pub(super) fn program(path: &Path) -> Option<PathBuf> {
109        std::fs::metadata(path)
110            .is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
111            .then(|| path.to_path_buf())
112    }
113}
114
115/// Windows: the process's PATH, where a program is its `.exe`.
116#[cfg(all(not(unix), not(target_family = "wasm")))]
117mod backend {
118    use std::ffi::OsString;
119    use std::path::{Path, PathBuf};
120
121    pub(super) fn current() -> super::ToolDirs {
122        super::ToolDirs::of(std::env::var_os("PATH").as_deref(), None, None)
123    }
124
125    pub(super) fn login_shell_path() -> Option<OsString> {
126        None
127    }
128
129    pub(super) fn program(path: &Path) -> Option<PathBuf> {
130        [path.with_extension("exe"), path.to_path_buf()]
131            .into_iter()
132            .find(|candidate| candidate.is_file())
133    }
134}
135
136#[cfg(target_family = "wasm")]
137mod backend {
138    use std::ffi::OsString;
139    use std::path::{Path, PathBuf};
140
141    pub(super) fn current() -> super::ToolDirs {
142        super::ToolDirs::default()
143    }
144
145    pub(super) fn login_shell_path() -> Option<OsString> {
146        None
147    }
148
149    pub(super) fn program(_: &Path) -> Option<PathBuf> {
150        None
151    }
152}
153
154#[cfg(all(test, unix))]
155mod tests {
156    use super::ToolDirs;
157    use std::os::unix::fs::PermissionsExt;
158
159    #[test]
160    fn a_tool_in_the_persons_cargo_folder_is_found_without_it_on_path() {
161        let home = tempfile::tempdir().unwrap();
162        let bin = home.path().join(".cargo/bin");
163        std::fs::create_dir_all(&bin).unwrap();
164        let tool = bin.join("rust-analyzer");
165        std::fs::write(&tool, "#!/bin/sh\n").unwrap();
166        std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
167        let empty = std::ffi::OsString::new();
168
169        let dirs = ToolDirs::of(Some(&empty), Some(home.path()), None);
170        assert_eq!(dirs.find("rust-analyzer"), Some(tool.clone()));
171        assert_eq!(
172            ToolDirs::of(Some(&empty), None, None).find("rust-analyzer"),
173            None
174        );
175
176        std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o644)).unwrap();
177        assert_eq!(
178            dirs.find("rust-analyzer"),
179            None,
180            "a file that can't run is no tool"
181        );
182    }
183}