#![cfg(test)]
use std::sync::{Mutex, OnceLock};
static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
pub(crate) fn with_env<T>(vars: &[(&str, Option<&str>)], f: impl FnOnce() -> T) -> T {
let _guard = ENV_LOCK
.get_or_init(|| Mutex::new(()))
.lock()
.unwrap_or_else(|e| e.into_inner());
let saved: Vec<(String, Option<String>)> = vars
.iter()
.map(|(k, _)| ((*k).to_string(), std::env::var(k).ok()))
.collect();
struct Restore(Vec<(String, Option<String>)>);
impl Drop for Restore {
fn drop(&mut self) {
for (k, v) in &self.0 {
match v {
Some(v) => unsafe { std::env::set_var(k, v) },
None => unsafe { std::env::remove_var(k) },
}
}
}
}
let _restore = Restore(saved);
for (k, v) in vars {
match v {
Some(v) => unsafe { std::env::set_var(k, v) },
None => unsafe { std::env::remove_var(k) },
}
}
f()
}
pub(crate) fn with_isolated_registry<T>(tag: &str, f: impl FnOnce() -> T) -> T {
let dir = std::env::temp_dir().join(format!("dextui-test-registry-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
with_env(&[("XDG_CONFIG_HOME", Some(dir.to_str().unwrap()))], f)
}