Skip to main content

corundum_framework_package/
cli_path.rs

1//! The app's command line on `PATH`.
2//!
3//! Windows puts the package's `current` directory on the user `Path` from the install hook
4//! and takes it off from the uninstall hook. macOS links `/usr/local/bin/<command>` to the
5//! binary in the `.app`, with administrator rights asked through `osascript`; Linux links
6//! `~/.local/bin/<command>` to the AppImage. Both are made and removed when the user asks.
7//! An update keeps the binary's path, so nothing is made again after one.
8
9use std::ffi::OsStr;
10use std::path::{Path, PathBuf};
11
12use crate::error::Error;
13
14#[cfg(unix)]
15mod unix;
16#[cfg(windows)]
17mod windows;
18
19/// The command line a package puts on `PATH`.
20#[derive(Clone, Copy, Debug)]
21pub struct CliSpec {
22    /// The name typed in a terminal: `sapphire-journal`. On Windows, the console shim's
23    /// file name without `.exe`.
24    pub command: &'static str,
25}
26
27/// Whether the command line is on `PATH`.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum CliStatus {
30    /// On `PATH`, running this package.
31    Installed,
32    /// Not on `PATH`.
33    Missing,
34    /// A link whose target is gone: the `.app` or the AppImage was deleted or moved.
35    Broken,
36    /// Another program has the name, left alone: a file that is not a link (a
37    /// command-line-only install of the same app), or a link to another file (Homebrew's,
38    /// pipx's).
39    Taken,
40    /// Outside a package.
41    Unsupported,
42}
43
44/// Whether the command line is on `PATH`.
45pub fn status(spec: &CliSpec) -> CliStatus {
46    #[cfg(windows)]
47    return windows::status(spec);
48    #[cfg(unix)]
49    return unix::status(spec);
50}
51
52/// Puts the command line on `PATH`. Never replaces another program's: a file that is not a
53/// link, or a link to another file ([`CliStatus::Taken`]).
54pub fn install(spec: &CliSpec) -> Result<(), Error> {
55    #[cfg(windows)]
56    return windows::install(spec);
57    #[cfg(unix)]
58    return unix::install(spec);
59}
60
61/// Takes the command line off `PATH`. Nothing to take off is not an error.
62pub fn uninstall(spec: &CliSpec) -> Result<(), Error> {
63    #[cfg(windows)]
64    return windows::uninstall(spec);
65    #[cfg(unix)]
66    return unix::uninstall(spec);
67}
68
69/// Whether `dir` is on this process's `PATH`: Linux's `~/.local/bin` is not on every
70/// distribution's.
71pub fn on_path(dir: &Path) -> bool {
72    on_path_in(dir, &std::env::var_os("PATH").unwrap_or_default())
73}
74
75/// Whether `dir` is on the `PATH` a terminal gets: the one the user's login shell sets up,
76/// or `None` when the shell does not answer within [`LOGIN_PATH_WAIT`]. A window started from
77/// the desktop's menu often has a shorter `PATH` than a terminal, since shells add
78/// `~/.local/bin` in their own start files, so [`on_path`] would warn about a directory every
79/// terminal has; and a busy machine can take seconds to start a shell, so a missing answer
80/// is not a "no". It blocks while the shell starts: call it off the UI thread.
81#[cfg(unix)]
82pub fn on_login_path(dir: &Path) -> Option<bool> {
83    login_path().map(|path_var| on_path_in(dir, &path_var))
84}
85
86/// How long [`on_login_path`] waits for the shell: an interactive shell's start files can
87/// take several seconds on a machine busy with its disk.
88#[cfg(unix)]
89pub const LOGIN_PATH_WAIT: std::time::Duration = std::time::Duration::from_secs(20);
90
91/// What a terminal's `PATH` would be: asked of `$SHELL` as a login, interactive shell, which
92/// reads the start files a terminal does. Its output is searched for a marker, since start
93/// files may print greetings of their own.
94#[cfg(unix)]
95fn login_path() -> Option<std::ffi::OsString> {
96    use std::io::Read;
97    use std::process::{Command, Stdio};
98    use std::time::{Duration, Instant};
99
100    let shell = std::env::var_os("SHELL").unwrap_or_else(|| "/bin/sh".into());
101    let mut child = Command::new(shell)
102        .args(["-l", "-i", "-c", r#"printf '\n%s%s\n' "$1" "$PATH""#, "sh"])
103        .arg(LOGIN_PATH_MARKER)
104        .stdin(Stdio::null())
105        .stdout(Stdio::piped())
106        .stderr(Stdio::null())
107        .spawn()
108        .ok()?;
109    let deadline = Instant::now() + LOGIN_PATH_WAIT;
110    loop {
111        match child.try_wait() {
112            Ok(Some(_)) => break,
113            Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(20)),
114            _ => {
115                let _ = child.kill();
116                let _ = child.wait();
117                return None;
118            }
119        }
120    }
121    let mut out = Vec::new();
122    child.stdout.take()?.read_to_end(&mut out).ok()?;
123    parse_login_path(&out)
124}
125
126/// Put before `$PATH` in the shell's output, so a greeting from a start file is not taken
127/// for it.
128#[cfg(unix)]
129const LOGIN_PATH_MARKER: &str = "corundum-login-path:";
130
131/// The `PATH` after the last marker in a login shell's output.
132#[cfg(unix)]
133fn parse_login_path(out: &[u8]) -> Option<std::ffi::OsString> {
134    use std::os::unix::ffi::OsStringExt;
135
136    let marker = LOGIN_PATH_MARKER.as_bytes();
137    let start = out
138        .windows(marker.len())
139        .rposition(|window| window == marker)?
140        + marker.len();
141    let line = out[start..].split(|&b| b == b'\n').next()?;
142    (!line.is_empty()).then(|| std::ffi::OsString::from_vec(line.to_vec()))
143}
144
145/// [`on_path`] for a given `PATH` value.
146pub(crate) fn on_path_in(dir: &Path, path_var: &OsStr) -> bool {
147    let dir = clean(dir);
148    std::env::split_paths(path_var)
149        .filter(|entry| !entry.as_os_str().is_empty())
150        .any(|entry| clean(&entry) == dir)
151}
152
153/// `path` as it names a directory: its canonical form, or, when it does not exist, its
154/// components without `.` and a trailing separator.
155fn clean(path: &Path) -> PathBuf {
156    path.canonicalize()
157        .unwrap_or_else(|_| path.components().collect())
158}
159
160/// The user `Path` value with `dir` added at the end, or `None` when it is already there.
161/// The other entries are kept as they are, a trailing `;` too.
162#[cfg_attr(not(windows), allow(dead_code))]
163pub(crate) fn path_with(value: &str, dir: &str) -> Option<String> {
164    if value.split(';').any(|entry| same_entry(entry, dir)) {
165        return None;
166    }
167    Some(if value.is_empty() {
168        dir.to_owned()
169    } else if let Some(rest) = value.strip_suffix(';') {
170        format!("{rest};{dir};")
171    } else {
172        format!("{value};{dir}")
173    })
174}
175
176/// The user `Path` value with every entry naming `dir` removed, or `None` when there is
177/// none. The other entries are kept as they are, empty ones too.
178#[cfg_attr(not(windows), allow(dead_code))]
179pub(crate) fn path_without(value: &str, dir: &str) -> Option<String> {
180    let entries: Vec<&str> = value.split(';').collect();
181    let kept: Vec<&str> = entries
182        .iter()
183        .copied()
184        .filter(|entry| !same_entry(entry, dir))
185        .collect();
186    (kept.len() != entries.len()).then(|| kept.join(";"))
187}
188
189/// Whether a `Path` entry names `dir`: Windows paths ignore case, and an entry may be
190/// quoted or end with a `\`. An empty entry names nothing.
191fn same_entry(entry: &str, dir: &str) -> bool {
192    let norm = |s: &str| {
193        let s = s
194            .strip_prefix('"')
195            .and_then(|s| s.strip_suffix('"'))
196            .unwrap_or(s);
197        s.strip_suffix('\\').unwrap_or(s).to_lowercase()
198    };
199    !entry.is_empty() && norm(entry) == norm(dir)
200}
201
202#[cfg(test)]
203mod tests {
204    use std::ffi::OsString;
205
206    use super::*;
207
208    const DIR: &str = "C:\\x\\current";
209
210    #[cfg(unix)]
211    #[test]
212    fn the_login_path_is_read_after_the_marker() {
213        let out = b"Welcome back!\ncorundum-login-path: in a greeting\n\ncorundum-login-path:/home/u/.local/bin:/usr/bin\n";
214        assert_eq!(
215            parse_login_path(out),
216            Some(OsString::from("/home/u/.local/bin:/usr/bin"))
217        );
218        assert_eq!(parse_login_path(b"no marker here\n"), None);
219        assert_eq!(parse_login_path(b"\ncorundum-login-path:\n"), None);
220    }
221
222    #[cfg(unix)]
223    #[test]
224    fn the_login_shell_is_asked_for_its_path() {
225        // This test process's shell sees at least the directories its own `PATH` has.
226        let dir = tempfile::tempdir().unwrap();
227        assert_ne!(on_login_path(dir.path()), Some(true));
228        assert_ne!(on_login_path(Path::new("/usr/bin")), Some(false));
229    }
230
231    #[test]
232    fn a_dir_is_added_at_the_end_of_a_path_without_it() {
233        let cases: &[(&str, Option<&str>)] = &[
234            ("C:\\a;C:\\b", Some("C:\\a;C:\\b;C:\\x\\current")),
235            ("", Some("C:\\x\\current")),
236            ("C:\\a;", Some("C:\\a;C:\\x\\current;")),
237            ("C:\\a;;C:\\b", Some("C:\\a;;C:\\b;C:\\x\\current")),
238            ("C:\\a;C:\\X\\CURRENT\\", None),
239            ("\"C:\\x\\current\";C:\\b", None),
240            ("C:\\x\\current", None),
241        ];
242        for (value, want) in cases {
243            assert_eq!(path_with(value, DIR).as_deref(), *want, "{value:?}");
244        }
245    }
246
247    #[test]
248    fn a_dir_is_removed_from_a_path_keeping_the_other_entries() {
249        let cases: &[(&str, Option<&str>)] = &[
250            (
251                "%USERPROFILE%\\bin;C:\\x\\current;C:\\b",
252                Some("%USERPROFILE%\\bin;C:\\b"),
253            ),
254            ("C:\\a;C:\\x\\current;", Some("C:\\a;")),
255            ("C:\\a;;C:\\X\\Current\\;C:\\b", Some("C:\\a;;C:\\b")),
256            ("\"C:\\x\\current\"", Some("")),
257            ("C:\\x\\current;C:\\a;C:\\x\\current", Some("C:\\a")),
258            ("C:\\a;C:\\b", None),
259            ("", None),
260            ("C:\\x\\current2", None),
261        ];
262        for (value, want) in cases {
263            assert_eq!(path_without(value, DIR).as_deref(), *want, "{value:?}");
264        }
265    }
266
267    #[test]
268    fn a_dir_is_on_a_path_naming_it_with_or_without_a_trailing_separator() {
269        let tmp = tempfile::tempdir().unwrap();
270        let dir = tmp.path().join("bin");
271        std::fs::create_dir(&dir).unwrap();
272        let other = tmp.path().join("other");
273        let sep = std::path::MAIN_SEPARATOR;
274        let path_of = |entries: &[PathBuf]| -> OsString { std::env::join_paths(entries).unwrap() };
275
276        assert!(on_path_in(&dir, &path_of(&[other.clone(), dir.clone()])));
277        let trailing = PathBuf::from(format!("{}{sep}", dir.display()));
278        assert!(on_path_in(&dir, &path_of(&[trailing])));
279        let dotted = tmp.path().join(".").join("bin");
280        assert!(on_path_in(&dir, &path_of(&[dotted])));
281        assert!(!on_path_in(&dir, &path_of(&[other])));
282        assert!(!on_path_in(&dir, OsStr::new("")));
283    }
284}