use once_cell::sync::Lazy;
use std::env;
pub static ENV_MUTEX: Lazy<tokio::sync::Mutex<()>> = Lazy::new(|| tokio::sync::Mutex::new(()));
pub struct EnvVarGuard {
vars: Vec<(String, Option<String>)>,
}
impl EnvVarGuard {
pub fn new() -> Self {
Self { vars: Vec::new() }
}
pub fn set(&mut self, key: &str, value: &str) {
let original = env::var(key).ok();
self.vars.push((key.to_string(), original));
unsafe {
env::set_var(key, value);
}
}
#[allow(dead_code)]
pub fn remove(&mut self, key: &str) {
let original = env::var(key).ok();
self.vars.push((key.to_string(), original));
unsafe {
env::remove_var(key);
}
}
}
impl Drop for EnvVarGuard {
fn drop(&mut self) {
for (key, value) in self.vars.iter().rev() {
unsafe {
match value {
Some(v) => env::set_var(key, v),
None => env::remove_var(key),
}
}
}
}
}
impl Default for EnvVarGuard {
fn default() -> Self {
Self::new()
}
}