Skip to main content

isothrum_machine/host/
tool_path.rs

1//! The folders a process searches for the tools machine setup and a run start, worked out as a
2//! value its caller puts on its own `PATH`: the crate never sets a variable.
3//!
4//! An app opened from macOS's Finder (and from some Linux desktops) starts with a minimal `PATH`
5//! (`/usr/bin:/bin:/usr/sbin:/sbin`), not the user's shell's, so the folders the tools are
6//! installed in (Homebrew's, Docker's, Vagrant's, the tools inside app bundles: Docker's CLI,
7//! `utmctl`, Fusion's OVF Tool) are appended ([`augmented`]). The entries already there keep
8//! priority. The folders of tools the caller places itself (a managed OVF Tool) come last, and
9//! before they exist: a tool placed while the process runs is then found without a restart.
10//!
11//! On Windows the `PATH` is complete at start, but goes stale: an installer (winget, Docker
12//! Desktop, VirtualBox) writes the new one to the registry, which a running process never reads
13//! again. [`refreshed`] reads it back (`reg query`, machine then user, its `%VAR%`s expanded
14//! with the caller's variables) and merges it in, with the tool folders that exist now.
15
16use std::ffi::{OsStr, OsString};
17use std::path::{Path, PathBuf};
18use std::time::Duration;
19
20use isothrum_runner::ProcessSpec;
21
22use super::HostOs;
23use crate::context::Context;
24
25/// How long one `reg query` of the registry's `Path` may take.
26const REG_TIMEOUT: Duration = Duration::from_secs(10);
27
28/// The registry keys whose `Path` value a refresh reads, machine then user.
29const REGISTRY_PATHS: [&str; 2] = [r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment", r"HKCU\Environment"];
30
31/// What the tool path is worked out from: the process's `PATH`, the user's home folder and the
32/// variables it reads (Program Files, the system drive, VirtualBox's install folder, and any a
33/// registry `PATH` names), as values, so a test hands its own.
34#[derive(Debug, Clone, Default, PartialEq, Eq)]
35pub struct Env {
36    /// The `PATH`'s folders, in order.
37    pub path: Vec<PathBuf>,
38    /// The user's home folder.
39    pub home: Option<PathBuf>,
40    /// The variables, by name.
41    pub vars: Vec<(String, OsString)>,
42}
43
44impl Env {
45    /// This process's: its `PATH` split as this OS splits it, its home (`HOME`, else
46    /// `USERPROFILE`) and its variables (those with a UTF-8 name).
47    #[must_use]
48    pub fn here() -> Env {
49        let path = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();
50        let home = std::env::var_os("HOME")
51            .or_else(|| std::env::var_os("USERPROFILE"))
52            .filter(|h| !h.is_empty())
53            .map(PathBuf::from);
54        let vars = std::env::vars_os().filter_map(|(k, v)| k.into_string().ok().map(|k| (k, v))).collect();
55        Env { path, home, vars }
56    }
57
58    /// The value of variable `name`: its name compared regardless of case, as Windows does (the
59    /// names read here are never two variables that differ in case alone).
60    #[must_use]
61    pub fn var(&self, name: &str) -> Option<&OsStr> {
62        self.vars
63            .iter()
64            .rev()
65            .find(|(k, _)| k.eq_ignore_ascii_case(name))
66            .map(|(_, v)| v.as_os_str())
67            .filter(|v| !v.is_empty())
68    }
69}
70
71/// The folders the tools are installed in on `os`, whether they exist or not ([`augmented`]
72/// adds those that do).
73#[must_use]
74pub fn tool_dirs(os: HostOs, env: &Env) -> Vec<PathBuf> {
75    let mut dirs: Vec<PathBuf> = Vec::new();
76    if os != HostOs::Windows {
77        dirs.extend(["/usr/local/bin", "/usr/local/sbin", "/opt/homebrew/bin", "/opt/homebrew/sbin"].map(PathBuf::from));
78        if let Some(home) = &env.home {
79            // Docker Desktop's per-user CLI install, and user-level installs.
80            dirs.push(home.join(".docker/bin"));
81            dirs.push(home.join(".local/bin"));
82        }
83    }
84    match os {
85        HostOs::Macos => dirs.extend(mac_bundle_dirs(env.home.as_deref())),
86        HostOs::Windows => dirs.extend(windows_dirs(env)),
87        HostOs::Linux => {}
88    }
89    dirs
90}
91
92/// The macOS tools that live inside app bundles: Docker's CLI, `utmctl` (in UTM, in
93/// `/Applications` or the user's own `~/Applications`), and Fusion's OVF Tool.
94fn mac_bundle_dirs(home: Option<&Path>) -> Vec<PathBuf> {
95    let mut dirs = vec![
96        PathBuf::from("/Applications/Docker.app/Contents/Resources/bin"),
97        PathBuf::from("/Applications/UTM.app/Contents/MacOS"),
98    ];
99    dirs.extend(home.map(|h| h.join("Applications/UTM.app/Contents/MacOS")));
100    dirs.push(PathBuf::from("/Applications/VMware Fusion.app/Contents/Library/VMware OVF Tool"));
101    dirs.push(PathBuf::from("/Applications/VMware Fusion.app/Contents/Library"));
102    dirs
103}
104
105/// The Windows tool folders. None of these installers adds itself to `PATH`: VirtualBox says
106/// where it went in `VBOX_MSI_INSTALL_PATH` (first: a VirtualBox moved elsewhere wins), VMware
107/// Workstation puts `vmrun` under the 32-bit Program Files and its OVF Tool in a folder of its
108/// own, and QEMU's installer adds nothing either.
109fn windows_dirs(env: &Env) -> Vec<PathBuf> {
110    let mut dirs: Vec<PathBuf> = Vec::new();
111    dirs.extend(env.var("VBOX_MSI_INSTALL_PATH").map(PathBuf::from));
112    if let Some(pf) = env.var("ProgramFiles").map(PathBuf::from) {
113        dirs.push(pf.join("Oracle").join("VirtualBox"));
114        dirs.push(pf.join("VMware").join("VMware OVF Tool"));
115        dirs.push(pf.join("Vagrant").join("bin"));
116        dirs.push(pf.join("Docker").join("Docker").join("resources").join("bin"));
117        dirs.push(pf.join("qemu"));
118    }
119    if let Some(pf86) = env.var("ProgramFiles(x86)").map(PathBuf::from) {
120        dirs.push(pf86.join("VMware").join("VMware Workstation"));
121    }
122    for pf in ["ProgramFiles(x86)", "ProgramFiles"].into_iter().filter_map(|v| env.var(v)) {
123        dirs.push(crate::tools::ovftool::workstation_dir(Path::new(pf)));
124    }
125    dirs
126}
127
128/// The folders added even before they exist, so a tool installed there while the process runs
129/// is found without a restart: on Linux the per-user Google Cloud SDK earlier installs made, on
130/// Windows Vagrant's folder under the system drive (where its installer puts it), on macOS
131/// `/usr/local/bin` and Homebrew's: a Mac with Apple silicon has no `/usr/local/bin` until an
132/// installer makes it for its link (Vagrant's, the AWS CLI's), nor Homebrew's folder until
133/// Homebrew is installed.
134#[must_use]
135pub fn future_dirs(os: HostOs, env: &Env) -> Vec<PathBuf> {
136    match os {
137        HostOs::Linux => env.home.iter().map(|h| h.join("google-cloud-sdk/bin")).collect(),
138        HostOs::Windows => {
139            let drive = env.var("SystemDrive").map_or_else(|| "C:".to_owned(), |d| d.to_string_lossy().into_owned());
140            vec![PathBuf::from(format!("{drive}\\HashiCorp\\Vagrant\\bin"))]
141        }
142        HostOs::Macos => ["/usr/local/bin", "/opt/homebrew/bin"].map(PathBuf::from).to_vec(),
143    }
144}
145
146/// Whether two `PATH` entries on `os` name the same folder: on Windows regardless of case and of
147/// a trailing separator (`C:\Tools\` and `c:\tools` are one entry).
148fn same_dir(os: HostOs, a: &Path, b: &Path) -> bool {
149    if os == HostOs::Windows {
150        let norm = |p: &Path| p.to_string_lossy().trim_end_matches(['\\', '/']).to_lowercase();
151        norm(a) == norm(b)
152    } else {
153        a == b
154    }
155}
156
157/// `current` with each of `dirs` appended that it doesn't hold yet (an empty one never); None
158/// when nothing was added. The entries already there keep their order, so they keep priority.
159#[must_use]
160pub fn appended(os: HostOs, current: &[PathBuf], dirs: impl IntoIterator<Item = PathBuf>) -> Option<Vec<PathBuf>> {
161    let mut paths = current.to_vec();
162    for dir in dirs {
163        if !dir.as_os_str().is_empty() && !paths.iter().any(|p| same_dir(os, p, &dir)) {
164            paths.push(dir);
165        }
166    }
167    (paths.len() > current.len()).then_some(paths)
168}
169
170/// The `PATH` an app opened from Finder (or a desktop's launcher) needs: `env`'s, then each
171/// [`tool_dirs`] folder that exists, each [`future_dirs`] one, then `own`, the folders of the
172/// tools the caller places itself (which may not exist yet): a hypervisor's own copy of a tool
173/// comes before the caller's. None when nothing is added. The caller joins it
174/// (`std::env::join_paths`) and sets it.
175#[must_use]
176pub fn augmented(os: HostOs, env: &Env, own: &[PathBuf]) -> Option<Vec<PathBuf>> {
177    augmented_where(os, env, own, Path::is_dir)
178}
179
180/// [`augmented`], `is_dir` saying which folders exist.
181pub(crate) fn augmented_where(os: HostOs, env: &Env, own: &[PathBuf], is_dir: impl Fn(&Path) -> bool) -> Option<Vec<PathBuf>> {
182    let existing = tool_dirs(os, env).into_iter().filter(|d| is_dir(d));
183    appended(os, &env.path, existing.chain(future_dirs(os, env)).chain(own.iter().cloned()))
184}
185
186/// On Windows, `env`'s `PATH` with the one installers have since written to the registry
187/// (machine, then user, expanded) and the tool folders that exist now merged in: each folder
188/// that exists and isn't there yet, appended. None when nothing is added, and on every other OS
189/// (no installer there changes a running process's `PATH`). Two `reg query` runs: cheap enough
190/// before each machine check. A registry value `reg` can't read is left out.
191pub async fn refreshed(cx: &Context, env: &Env) -> Option<Vec<PathBuf>> {
192    refreshed_where(cx, env, Path::is_dir).await
193}
194
195/// [`refreshed`], `is_dir` saying which folders exist.
196pub(crate) async fn refreshed_where(cx: &Context, env: &Env, is_dir: impl Fn(&Path) -> bool) -> Option<Vec<PathBuf>> {
197    if cx.host.os != HostOs::Windows {
198        return None;
199    }
200    let mut registry: Vec<PathBuf> = Vec::new();
201    for key in REGISTRY_PATHS {
202        let spec = ProcessSpec::new("reg", ["query", key, "/v", "Path"]);
203        let Ok(captured) = cx.probe_within(REG_TIMEOUT, &spec).await else { continue };
204        if !captured.success() {
205            continue;
206        }
207        if let Some(value) = registry_value(&captured.stdout.join("\n")) {
208            registry.extend(expanded(&value, env).split(';').map(str::trim).filter(|d| !d.is_empty()).map(PathBuf::from));
209        }
210    }
211    let dirs: Vec<PathBuf> = registry.into_iter().chain(tool_dirs(HostOs::Windows, env)).filter(|d| is_dir(d)).collect();
212    appended(HostOs::Windows, &env.path, dirs)
213}
214
215/// [`refreshed`] as a `PATH` value a Windows program is started with (`;` between its folders,
216/// whatever this crate was built for): what a step runs with ([`crate::install::run_step`]), so
217/// it finds a tool installed since this process started. None when nothing is added, and on
218/// every other OS.
219pub async fn refreshed_value(cx: &Context, env: &Env) -> Option<String> {
220    refreshed_value_where(cx, env, Path::is_dir).await
221}
222
223/// [`refreshed_value`], `is_dir` saying which folders exist.
224pub(crate) async fn refreshed_value_where(cx: &Context, env: &Env, is_dir: impl Fn(&Path) -> bool) -> Option<String> {
225    let dirs = refreshed_where(cx, env, is_dir).await?;
226    Some(dirs.iter().map(|d| d.to_string_lossy()).collect::<Vec<_>>().join(";"))
227}
228
229/// The value `reg query <key> /v Path` printed: the text after its type (`REG_EXPAND_SZ` or
230/// `REG_SZ`) on the value's line, which may hold spaces.
231fn registry_value(out: &str) -> Option<String> {
232    out.lines().find_map(|line| {
233        let mut words = line.split_whitespace();
234        if !words.next()?.eq_ignore_ascii_case("path") {
235            return None;
236        }
237        let kind = words.next()?;
238        if kind != "REG_EXPAND_SZ" && kind != "REG_SZ" {
239            return None;
240        }
241        let (_, rest) = line.split_once(kind)?;
242        Some(rest.trim().to_owned())
243    })
244}
245
246/// `value` with each `%NAME%` replaced by `env`'s variable `NAME`, as Windows expands a
247/// `REG_EXPAND_SZ`; one with no such variable, and a lone `%`, stay as written.
248fn expanded(value: &str, env: &Env) -> String {
249    let mut out = String::with_capacity(value.len());
250    let mut rest = value;
251    while let Some(start) = rest.find('%') {
252        let (before, from) = rest.split_at(start);
253        out.push_str(before);
254        let after = from.get(1..).unwrap_or_default();
255        let Some(end) = after.find('%') else {
256            out.push_str(from);
257            return out;
258        };
259        let name = after.get(..end).unwrap_or_default();
260        if let Some(v) = env.var(name).filter(|_| !name.is_empty()) {
261            out.push_str(&v.to_string_lossy());
262        } else {
263            out.push('%');
264            out.push_str(name);
265            out.push('%');
266        }
267        rest = after.get(end + 1..).unwrap_or_default();
268    }
269    out.push_str(rest);
270    out
271}
272
273#[cfg(test)]
274mod tests;