isothrum_machine/host/
tool_path.rs1use 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
25const REG_TIMEOUT: Duration = Duration::from_secs(10);
27
28const REGISTRY_PATHS: [&str; 2] = [r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment", r"HKCU\Environment"];
30
31#[derive(Debug, Clone, Default, PartialEq, Eq)]
35pub struct Env {
36 pub path: Vec<PathBuf>,
38 pub home: Option<PathBuf>,
40 pub vars: Vec<(String, OsString)>,
42}
43
44impl Env {
45 #[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 #[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#[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 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
92fn 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
105fn 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#[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
146fn 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#[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#[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
180pub(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
186pub async fn refreshed(cx: &Context, env: &Env) -> Option<Vec<PathBuf>> {
192 refreshed_where(cx, env, Path::is_dir).await
193}
194
195pub(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
215pub async fn refreshed_value(cx: &Context, env: &Env) -> Option<String> {
220 refreshed_value_where(cx, env, Path::is_dir).await
221}
222
223pub(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
229fn 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
246fn 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;