use std::ffi::OsStr;
use std::path::Path;
use std::sync::Mutex;
use std::time::{Duration, Instant};
pub const INSTALL_TTL: Duration = Duration::from_secs(60);
pub fn on_path(bin: &str, path: Option<&OsStr>) -> bool {
if bin.contains('/') {
return executable(Path::new(bin));
}
let Some(path) = path else { return false };
std::env::split_paths(path).filter(|d| !d.as_os_str().is_empty()).any(|dir| {
let candidate = dir.join(bin);
executable(&candidate) || (cfg!(windows) && executable(&candidate.with_extension("exe")))
})
}
fn executable(path: &Path) -> bool {
let Ok(meta) = std::fs::metadata(path) else { return false };
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
meta.is_file() && meta.permissions().mode() & 0o111 != 0
}
#[cfg(not(unix))]
{
meta.is_file()
}
}
#[derive(Debug, Default)]
pub struct InstallCache {
last: Option<(Instant, bool)>,
}
impl InstallCache {
pub fn get(&mut self, now: Instant, probe: impl FnOnce() -> bool) -> bool {
match self.last {
Some((at, answer)) if now < at + INSTALL_TTL => answer,
_ => {
let answer = probe();
self.last = Some((now, answer));
answer
}
}
}
}
pub fn installed() -> bool {
static CACHE: Mutex<InstallCache> = Mutex::new(InstallCache { last: None });
let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
cache.get(Instant::now(), || on_path(super::backend().bin(), std::env::var_os("PATH").as_deref()))
}
pub fn missing_note() -> String {
format!("`{}` isn't on PATH", super::backend().bin())
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(unix)]
#[test]
fn the_binary_is_looked_up_on_path() {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!("devsandbox-installed-{}", std::process::id()));
let (bin, other) = (dir.join("bin"), dir.join("other"));
std::fs::create_dir_all(&bin).unwrap();
std::fs::create_dir_all(&other).unwrap();
let docker = bin.join("docker");
std::fs::write(&docker, "#!/bin/sh\n").unwrap();
std::fs::set_permissions(&docker, std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::write(other.join("podman"), "").unwrap();
let path = std::env::join_paths([&other, &bin]).unwrap();
assert!(on_path("docker", Some(&path)));
assert!(!on_path("podman", Some(&path)), "not executable");
assert!(!on_path("container", Some(&path)));
assert!(!on_path("docker", Some(OsStr::new("/nonexistent"))));
assert!(!on_path("docker", Some(OsStr::new(""))));
assert!(!on_path("docker", None));
assert!(on_path(docker.to_str().unwrap(), None));
assert!(!on_path("/nonexistent/docker", Some(&path)));
std::fs::create_dir_all(other.join("container")).unwrap();
assert!(!on_path("container", Some(&path)));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_answer_is_asked_again_every_ttl() {
let mut cache = InstallCache::default();
let t0 = Instant::now();
assert!(!cache.get(t0, || false));
let never = || -> bool { panic!("asked within the ttl") };
assert!(!cache.get(t0 + INSTALL_TTL - Duration::from_millis(1), never));
assert!(cache.get(t0 + INSTALL_TTL, || true));
assert!(cache.get(t0 + INSTALL_TTL + Duration::from_secs(1), never));
}
}