Skip to main content

harn_cli/
env_guard.rs

1pub struct ScopedEnvVar {
2    key: &'static str,
3    previous: Option<String>,
4}
5
6impl ScopedEnvVar {
7    pub fn set(key: &'static str, value: &str) -> Self {
8        let previous = std::env::var(key).ok();
9        std::env::set_var(key, value);
10        Self { key, previous }
11    }
12
13    pub fn set_if_unset(key: &'static str, value: &str) -> Option<Self> {
14        if std::env::var(key).is_ok() {
15            None
16        } else {
17            Some(Self::set(key, value))
18        }
19    }
20
21    pub fn unset(key: &'static str) -> Self {
22        let previous = std::env::var(key).ok();
23        std::env::remove_var(key);
24        Self { key, previous }
25    }
26}
27
28impl Drop for ScopedEnvVar {
29    fn drop(&mut self) {
30        if let Some(value) = &self.previous {
31            std::env::set_var(self.key, value);
32        } else {
33            std::env::remove_var(self.key);
34        }
35    }
36}