Skip to content

Commit 0492b04

Browse files
committed
refactor(self-update): extract with_saved_global_state()
1 parent 7d497e1 commit 0492b04

File tree

2 files changed

+23
-15
lines changed

2 files changed

+23
-15
lines changed

src/cli/self_update/test.rs

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,28 @@ use winreg::{
88
RegKey, RegValue,
99
};
1010

11+
/// Support testing of code that mutates global state
12+
pub fn with_saved_global_state<S>(
13+
getter: impl Fn() -> io::Result<S>,
14+
setter: impl Fn(S),
15+
f: &mut dyn FnMut(),
16+
) {
17+
// Lock protects concurrent mutation of registry
18+
static LOCK: Mutex<()> = Mutex::new(());
19+
let _g = LOCK.lock();
20+
21+
// Save and restore the global state here to keep from trashing things.
22+
let saved_state =
23+
getter().expect("Error getting global state: Better abort to avoid trashing it");
24+
let _g = scopeguard::guard(saved_state, setter);
25+
26+
f();
27+
}
28+
29+
pub fn with_saved_path(f: &mut dyn FnMut()) {
30+
with_saved_global_state(get_path, restore_path, f)
31+
}
32+
1133
#[cfg(windows)]
1234
pub fn get_path() -> io::Result<Option<RegValue>> {
1335
let root = RegKey::predef(HKEY_CURRENT_USER);
@@ -34,20 +56,6 @@ fn restore_path(p: Option<RegValue>) {
3456
}
3557
}
3658

37-
/// Support testing of code that mutates global path state
38-
pub fn with_saved_path(f: &mut dyn FnMut()) {
39-
// Lock protects concurrent mutation of registry
40-
static LOCK: Mutex<()> = Mutex::new(());
41-
let _g = LOCK.lock();
42-
43-
// On windows these tests mess with the user's PATH. Save
44-
// and restore them here to keep from trashing things.
45-
let saved_path = get_path().expect("Error getting PATH: Better abort to avoid trashing it.");
46-
let _g = scopeguard::guard(saved_path, restore_path);
47-
48-
f();
49-
}
50-
5159
#[cfg(unix)]
5260
pub fn get_path() -> io::Result<Option<()>> {
5361
Ok(None)

src/test.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use std::process::Command;
1515
#[cfg(test)]
1616
use anyhow::Result;
1717

18-
pub use crate::cli::self_update::test::{get_path, with_saved_path};
18+
pub use crate::cli::self_update::test::{get_path, with_saved_global_state, with_saved_path};
1919
use crate::currentprocess;
2020
use crate::dist::dist::TargetTriple;
2121

0 commit comments

Comments
 (0)