use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::time::Duration;
use isothrum_runner::ProcessSpec;
use super::HostOs;
use crate::context::Context;
const REG_TIMEOUT: Duration = Duration::from_secs(10);
const REGISTRY_PATHS: [&str; 2] = [r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment", r"HKCU\Environment"];
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Env {
pub path: Vec<PathBuf>,
pub home: Option<PathBuf>,
pub vars: Vec<(String, OsString)>,
}
impl Env {
#[must_use]
pub fn here() -> Env {
let path = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();
let home = std::env::var_os("HOME")
.or_else(|| std::env::var_os("USERPROFILE"))
.filter(|h| !h.is_empty())
.map(PathBuf::from);
let vars = std::env::vars_os().filter_map(|(k, v)| k.into_string().ok().map(|k| (k, v))).collect();
Env { path, home, vars }
}
#[must_use]
pub fn var(&self, name: &str) -> Option<&OsStr> {
self.vars
.iter()
.rev()
.find(|(k, _)| k.eq_ignore_ascii_case(name))
.map(|(_, v)| v.as_os_str())
.filter(|v| !v.is_empty())
}
}
#[must_use]
pub fn tool_dirs(os: HostOs, env: &Env) -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = Vec::new();
if os != HostOs::Windows {
dirs.extend(["/usr/local/bin", "/usr/local/sbin", "/opt/homebrew/bin", "/opt/homebrew/sbin"].map(PathBuf::from));
if let Some(home) = &env.home {
dirs.push(home.join(".docker/bin"));
dirs.push(home.join(".local/bin"));
}
}
match os {
HostOs::Macos => dirs.extend(mac_bundle_dirs(env.home.as_deref())),
HostOs::Windows => dirs.extend(windows_dirs(env)),
HostOs::Linux => {}
}
dirs
}
fn mac_bundle_dirs(home: Option<&Path>) -> Vec<PathBuf> {
let mut dirs = vec![
PathBuf::from("/Applications/Docker.app/Contents/Resources/bin"),
PathBuf::from("/Applications/UTM.app/Contents/MacOS"),
];
dirs.extend(home.map(|h| h.join("Applications/UTM.app/Contents/MacOS")));
dirs.push(PathBuf::from("/Applications/VMware Fusion.app/Contents/Library/VMware OVF Tool"));
dirs.push(PathBuf::from("/Applications/VMware Fusion.app/Contents/Library"));
dirs
}
fn windows_dirs(env: &Env) -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = Vec::new();
dirs.extend(env.var("VBOX_MSI_INSTALL_PATH").map(PathBuf::from));
if let Some(pf) = env.var("ProgramFiles").map(PathBuf::from) {
dirs.push(pf.join("Oracle").join("VirtualBox"));
dirs.push(pf.join("VMware").join("VMware OVF Tool"));
dirs.push(pf.join("Vagrant").join("bin"));
dirs.push(pf.join("Docker").join("Docker").join("resources").join("bin"));
dirs.push(pf.join("qemu"));
}
if let Some(pf86) = env.var("ProgramFiles(x86)").map(PathBuf::from) {
dirs.push(pf86.join("VMware").join("VMware Workstation"));
}
for pf in ["ProgramFiles(x86)", "ProgramFiles"].into_iter().filter_map(|v| env.var(v)) {
dirs.push(crate::tools::ovftool::workstation_dir(Path::new(pf)));
}
dirs
}
#[must_use]
pub fn future_dirs(os: HostOs, env: &Env) -> Vec<PathBuf> {
match os {
HostOs::Linux => env.home.iter().map(|h| h.join("google-cloud-sdk/bin")).collect(),
HostOs::Windows => {
let drive = env.var("SystemDrive").map_or_else(|| "C:".to_owned(), |d| d.to_string_lossy().into_owned());
vec![PathBuf::from(format!("{drive}\\HashiCorp\\Vagrant\\bin"))]
}
HostOs::Macos => Vec::new(),
}
}
fn same_dir(os: HostOs, a: &Path, b: &Path) -> bool {
if os == HostOs::Windows {
let norm = |p: &Path| p.to_string_lossy().trim_end_matches(['\\', '/']).to_lowercase();
norm(a) == norm(b)
} else {
a == b
}
}
#[must_use]
pub fn appended(os: HostOs, current: &[PathBuf], dirs: impl IntoIterator<Item = PathBuf>) -> Option<Vec<PathBuf>> {
let mut paths = current.to_vec();
for dir in dirs {
if !dir.as_os_str().is_empty() && !paths.iter().any(|p| same_dir(os, p, &dir)) {
paths.push(dir);
}
}
(paths.len() > current.len()).then_some(paths)
}
#[must_use]
pub fn augmented(os: HostOs, env: &Env, own: &[PathBuf]) -> Option<Vec<PathBuf>> {
augmented_where(os, env, own, Path::is_dir)
}
pub(crate) fn augmented_where(os: HostOs, env: &Env, own: &[PathBuf], is_dir: impl Fn(&Path) -> bool) -> Option<Vec<PathBuf>> {
let existing = tool_dirs(os, env).into_iter().filter(|d| is_dir(d));
appended(os, &env.path, existing.chain(future_dirs(os, env)).chain(own.iter().cloned()))
}
pub async fn refreshed(cx: &Context, env: &Env) -> Option<Vec<PathBuf>> {
refreshed_where(cx, env, Path::is_dir).await
}
pub(crate) async fn refreshed_where(cx: &Context, env: &Env, is_dir: impl Fn(&Path) -> bool) -> Option<Vec<PathBuf>> {
if cx.host.os != HostOs::Windows {
return None;
}
let mut registry: Vec<PathBuf> = Vec::new();
for key in REGISTRY_PATHS {
let spec = ProcessSpec::new("reg", ["query", key, "/v", "Path"]);
let Ok(captured) = cx.probe_within(REG_TIMEOUT, &spec).await else { continue };
if !captured.success() {
continue;
}
if let Some(value) = registry_value(&captured.stdout.join("\n")) {
registry.extend(expanded(&value, env).split(';').map(str::trim).filter(|d| !d.is_empty()).map(PathBuf::from));
}
}
let dirs: Vec<PathBuf> = registry.into_iter().chain(tool_dirs(HostOs::Windows, env)).filter(|d| is_dir(d)).collect();
appended(HostOs::Windows, &env.path, dirs)
}
pub async fn refreshed_value(cx: &Context, env: &Env) -> Option<String> {
refreshed_value_where(cx, env, Path::is_dir).await
}
pub(crate) async fn refreshed_value_where(cx: &Context, env: &Env, is_dir: impl Fn(&Path) -> bool) -> Option<String> {
let dirs = refreshed_where(cx, env, is_dir).await?;
Some(dirs.iter().map(|d| d.to_string_lossy()).collect::<Vec<_>>().join(";"))
}
fn registry_value(out: &str) -> Option<String> {
out.lines().find_map(|line| {
let mut words = line.split_whitespace();
if !words.next()?.eq_ignore_ascii_case("path") {
return None;
}
let kind = words.next()?;
if kind != "REG_EXPAND_SZ" && kind != "REG_SZ" {
return None;
}
let (_, rest) = line.split_once(kind)?;
Some(rest.trim().to_owned())
})
}
fn expanded(value: &str, env: &Env) -> String {
let mut out = String::with_capacity(value.len());
let mut rest = value;
while let Some(start) = rest.find('%') {
let (before, from) = rest.split_at(start);
out.push_str(before);
let after = from.get(1..).unwrap_or_default();
let Some(end) = after.find('%') else {
out.push_str(from);
return out;
};
let name = after.get(..end).unwrap_or_default();
if let Some(v) = env.var(name).filter(|_| !name.is_empty()) {
out.push_str(&v.to_string_lossy());
} else {
out.push('%');
out.push_str(name);
out.push('%');
}
rest = after.get(end + 1..).unwrap_or_default();
}
out.push_str(rest);
out
}
#[cfg(test)]
mod tests;