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
22impl Drop for ScopedEnvVar {
23 fn drop(&mut self) {
24 if let Some(value) = &self.previous {
25 std::env::set_var(self.key, value);
26 } else {
27 std::env::remove_var(self.key);
28 }
29 }
30}