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]
132pub fn future_dirs(os: HostOs, env: &Env) -> Vec<PathBuf> {
133 match os {
134 HostOs::Linux => env.home.iter().map(|h| h.join("google-cloud-sdk/bin")).collect(),
135 HostOs::Windows => {
136 let drive = env.var("SystemDrive").map_or_else(|| "C:".to_owned(), |d| d.to_string_lossy().into_owned());
137 vec![PathBuf::from(format!("{drive}\\HashiCorp\\Vagrant\\bin"))]
138 }
139 HostOs::Macos => Vec::new(),
140 }
141}
142
143fn same_dir(os: HostOs, a: &Path, b: &Path) -> bool {
146 if os == HostOs::Windows {
147 let norm = |p: &Path| p.to_string_lossy().trim_end_matches(['\\', '/']).to_lowercase();
148 norm(a) == norm(b)
149 } else {
150 a == b
151 }
152}
153
154#[must_use]
157pub fn appended(os: HostOs, current: &[PathBuf], dirs: impl IntoIterator<Item = PathBuf>) -> Option<Vec<PathBuf>> {
158 let mut paths = current.to_vec();
159 for dir in dirs {
160 if !dir.as_os_str().is_empty() && !paths.iter().any(|p| same_dir(os, p, &dir)) {
161 paths.push(dir);
162 }
163 }
164 (paths.len() > current.len()).then_some(paths)
165}
166
167#[must_use]
173pub fn augmented(os: HostOs, env: &Env, own: &[PathBuf]) -> Option<Vec<PathBuf>> {
174 augmented_where(os, env, own, Path::is_dir)
175}
176
177pub(crate) fn augmented_where(os: HostOs, env: &Env, own: &[PathBuf], is_dir: impl Fn(&Path) -> bool) -> Option<Vec<PathBuf>> {
179 let existing = tool_dirs(os, env).into_iter().filter(|d| is_dir(d));
180 appended(os, &env.path, existing.chain(future_dirs(os, env)).chain(own.iter().cloned()))
181}
182
183pub async fn refreshed(cx: &Context, env: &Env) -> Option<Vec<PathBuf>> {
189 refreshed_where(cx, env, Path::is_dir).await
190}
191
192pub(crate) async fn refreshed_where(cx: &Context, env: &Env, is_dir: impl Fn(&Path) -> bool) -> Option<Vec<PathBuf>> {
194 if cx.host.os != HostOs::Windows {
195 return None;
196 }
197 let mut registry: Vec<PathBuf> = Vec::new();
198 for key in REGISTRY_PATHS {
199 let spec = ProcessSpec::new("reg", ["query", key, "/v", "Path"]);
200 let Ok(captured) = cx.probe_within(REG_TIMEOUT, &spec).await else { continue };
201 if !captured.success() {
202 continue;
203 }
204 if let Some(value) = registry_value(&captured.stdout.join("\n")) {
205 registry.extend(expanded(&value, env).split(';').map(str::trim).filter(|d| !d.is_empty()).map(PathBuf::from));
206 }
207 }
208 let dirs: Vec<PathBuf> = registry.into_iter().chain(tool_dirs(HostOs::Windows, env)).filter(|d| is_dir(d)).collect();
209 appended(HostOs::Windows, &env.path, dirs)
210}
211
212pub async fn refreshed_value(cx: &Context, env: &Env) -> Option<String> {
217 refreshed_value_where(cx, env, Path::is_dir).await
218}
219
220pub(crate) async fn refreshed_value_where(cx: &Context, env: &Env, is_dir: impl Fn(&Path) -> bool) -> Option<String> {
222 let dirs = refreshed_where(cx, env, is_dir).await?;
223 Some(dirs.iter().map(|d| d.to_string_lossy()).collect::<Vec<_>>().join(";"))
224}
225
226fn registry_value(out: &str) -> Option<String> {
229 out.lines().find_map(|line| {
230 let mut words = line.split_whitespace();
231 if !words.next()?.eq_ignore_ascii_case("path") {
232 return None;
233 }
234 let kind = words.next()?;
235 if kind != "REG_EXPAND_SZ" && kind != "REG_SZ" {
236 return None;
237 }
238 let (_, rest) = line.split_once(kind)?;
239 Some(rest.trim().to_owned())
240 })
241}
242
243fn expanded(value: &str, env: &Env) -> String {
246 let mut out = String::with_capacity(value.len());
247 let mut rest = value;
248 while let Some(start) = rest.find('%') {
249 let (before, from) = rest.split_at(start);
250 out.push_str(before);
251 let after = from.get(1..).unwrap_or_default();
252 let Some(end) = after.find('%') else {
253 out.push_str(from);
254 return out;
255 };
256 let name = after.get(..end).unwrap_or_default();
257 if let Some(v) = env.var(name).filter(|_| !name.is_empty()) {
258 out.push_str(&v.to_string_lossy());
259 } else {
260 out.push('%');
261 out.push_str(name);
262 out.push('%');
263 }
264 rest = after.get(end + 1..).unwrap_or_default();
265 }
266 out.push_str(rest);
267 out
268}
269
270#[cfg(test)]
271mod tests;