corundum_framework_package/
cli_path.rs1use 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#[derive(Clone, Copy, Debug)]
21pub struct CliSpec {
22 pub command: &'static str,
25}
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum CliStatus {
30 Installed,
32 Missing,
34 Broken,
36 Taken,
40 Unsupported,
42}
43
44pub fn status(spec: &CliSpec) -> CliStatus {
46 #[cfg(windows)]
47 return windows::status(spec);
48 #[cfg(unix)]
49 return unix::status(spec);
50}
51
52pub fn install(spec: &CliSpec) -> Result<(), Error> {
55 #[cfg(windows)]
56 return windows::install(spec);
57 #[cfg(unix)]
58 return unix::install(spec);
59}
60
61pub fn uninstall(spec: &CliSpec) -> Result<(), Error> {
63 #[cfg(windows)]
64 return windows::uninstall(spec);
65 #[cfg(unix)]
66 return unix::uninstall(spec);
67}
68
69pub fn on_path(dir: &Path) -> bool {
72 on_path_in(dir, &std::env::var_os("PATH").unwrap_or_default())
73}
74
75#[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#[cfg(unix)]
89pub const LOGIN_PATH_WAIT: std::time::Duration = std::time::Duration::from_secs(20);
90
91#[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#[cfg(unix)]
129const LOGIN_PATH_MARKER: &str = "corundum-login-path:";
130
131#[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
145pub(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
153fn clean(path: &Path) -> PathBuf {
156 path.canonicalize()
157 .unwrap_or_else(|_| path.components().collect())
158}
159
160#[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#[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
189fn 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 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}