use std::io;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::time::UNIX_EPOCH;
const DELETED: &str = " (deleted)";
pub fn devsandbox() -> io::Result<PathBuf> {
Ok(strip_deleted(std::env::current_exe()?, |p| p.exists()))
}
fn strip_deleted(path: PathBuf, exists: impl Fn(&Path) -> bool) -> PathBuf {
let stripped = path.to_str().and_then(|s| s.strip_suffix(DELETED)).map(PathBuf::from);
match stripped {
Some(stripped) if exists(&stripped) => stripped,
_ => path,
}
}
pub fn own_build_stamp() -> Option<u64> {
static STAMP: OnceLock<Option<u64>> = OnceLock::new();
*STAMP.get_or_init(|| {
#[cfg(target_os = "linux")]
let path = PathBuf::from("/proc/self/exe");
#[cfg(not(target_os = "linux"))]
let path = std::env::current_exe().ok()?;
let modified = std::fs::metadata(path).ok()?.modified().ok()?;
Some(modified.duration_since(UNIX_EPOCH).ok()?.as_secs())
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strips_deleted_only_when_the_replacement_exists() {
let deleted = PathBuf::from("/usr/bin/devsandbox (deleted)");
let replaced = PathBuf::from("/usr/bin/devsandbox");
assert_eq!(strip_deleted(deleted.clone(), |p| p == replaced), replaced);
assert_eq!(strip_deleted(deleted.clone(), |_| false), deleted);
}
#[test]
fn leaves_other_paths_alone() {
let plain = PathBuf::from("/usr/bin/devsandbox");
assert_eq!(strip_deleted(plain.clone(), |_| true), plain);
let inside = PathBuf::from("/tmp/x (deleted)/devsandbox");
assert_eq!(strip_deleted(inside.clone(), |_| true), inside);
}
#[test]
fn devsandbox_resolves_to_an_existing_binary() {
assert!(devsandbox().unwrap().exists());
}
#[test]
fn build_stamp_is_stable() {
let first = own_build_stamp();
assert!(first.is_some());
assert_eq!(own_build_stamp(), first);
}
}