Skip to content

Commit 0d5c3e4

Browse files
unhappychoiceclaude
andcommitted
refactor(config): replace HOME env mutation in TempHome with injected override
CodeRabbit flagged the previous `TempHome` implementation in `config.rs` and `main.rs` as unsafe under multi-threaded test execution. Both copies mutated process-global `HOME`/`USERPROFILE` and only serialized themselves through a shared `test_home_env_lock()` mutex, which does not protect any other test module that happens to read `$HOME`. Replace the env mutation with a `pub(crate) test_home::Guard` type in `config.rs` that: - Acquires a single serializer mutex so only one test can install an override at a time. - Stores the override path in an `RwLock<Option<PathBuf>>` so a wrapper `home_dir()` can transparently consult it before falling back to `dirs::home_dir()`. - Clears the override on `Drop`, so production calls outside test scopes always see the real home directory. `Config::config_path` and `Config::themes_dir` now go through the new `home_dir()` helper, and the per-module `TempHome` structs in `config.rs` and `main.rs` are thin wrappers around the shared guard. No `env::set_var` or `env::remove_var` calls remain in the test code. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent 2f50404 commit 0d5c3e4

2 files changed

Lines changed: 66 additions & 67 deletions

File tree

‎src/config.rs‎

Lines changed: 63 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,59 @@ fn default_ignore_patterns() -> Vec<String> {
4545
Vec::new()
4646
}
4747

48+
fn home_dir() -> Option<PathBuf> {
49+
#[cfg(test)]
50+
if let Some(path) = test_home::current() {
51+
return Some(path);
52+
}
53+
dirs::home_dir()
54+
}
55+
4856
#[cfg(test)]
49-
pub(crate) fn test_home_env_lock() -> &'static std::sync::Mutex<()> {
50-
static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
51-
LOCK.get_or_init(|| std::sync::Mutex::new(()))
57+
pub(crate) mod test_home {
58+
use std::path::{Path, PathBuf};
59+
use std::sync::{Mutex, MutexGuard, OnceLock, RwLock};
60+
61+
fn serializer() -> &'static Mutex<()> {
62+
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
63+
LOCK.get_or_init(|| Mutex::new(()))
64+
}
65+
66+
fn override_state() -> &'static RwLock<Option<PathBuf>> {
67+
static STATE: OnceLock<RwLock<Option<PathBuf>>> = OnceLock::new();
68+
STATE.get_or_init(|| RwLock::new(None))
69+
}
70+
71+
pub(crate) fn current() -> Option<PathBuf> {
72+
override_state().read().ok().and_then(|g| g.clone())
73+
}
74+
75+
pub(crate) struct Guard {
76+
_lock: MutexGuard<'static, ()>,
77+
}
78+
79+
impl Guard {
80+
pub(crate) fn new(path: &Path) -> Self {
81+
Self::with_override(Some(path.to_path_buf()))
82+
}
83+
84+
#[cfg(test)]
85+
pub(crate) fn no_override() -> Self {
86+
Self::with_override(None)
87+
}
88+
89+
fn with_override(path: Option<PathBuf>) -> Self {
90+
let lock = serializer().lock().expect("serializer poisoned");
91+
*override_state().write().expect("override poisoned") = path;
92+
Self { _lock: lock }
93+
}
94+
}
95+
96+
impl Drop for Guard {
97+
fn drop(&mut self) {
98+
*override_state().write().expect("override poisoned") = None;
99+
}
100+
}
52101
}
53102

54103
impl Default for Config {
@@ -181,7 +230,7 @@ impl Config {
181230
}
182231

183232
pub fn config_path() -> Result<PathBuf> {
184-
let config_dir = dirs::home_dir()
233+
let config_dir = home_dir()
185234
.context("Failed to determine home directory")?
186235
.join(".config")
187236
.join("gitlogue");
@@ -198,7 +247,7 @@ impl Config {
198247

199248
#[allow(dead_code)]
200249
pub fn themes_dir() -> Result<PathBuf> {
201-
let config_dir = dirs::home_dir()
250+
let config_dir = home_dir()
202251
.context("Failed to determine home directory")?
203252
.join(".config")
204253
.join("gitlogue")
@@ -219,23 +268,15 @@ impl Config {
219268
mod tests {
220269
use super::*;
221270
use std::env;
222-
use std::ffi::OsString;
223-
use std::sync::MutexGuard;
224271
use std::time::{SystemTime, UNIX_EPOCH};
225272

226-
const HOME_VARS: [&str; 4] = ["HOME", "USERPROFILE", "HOMEDRIVE", "HOMEPATH"];
227-
228273
struct TempHome {
229-
_lock: MutexGuard<'static, ()>,
274+
_override: super::test_home::Guard,
230275
path: PathBuf,
231-
original_vars: Vec<(&'static str, Option<OsString>)>,
232276
}
233277

234278
impl TempHome {
235279
fn new() -> Result<Self> {
236-
let lock = test_home_env_lock()
237-
.lock()
238-
.unwrap_or_else(|poisoned| poisoned.into_inner());
239280
let path = env::temp_dir().join(format!(
240281
"gitlogue-config-tests-{}-{}",
241282
std::process::id(),
@@ -244,37 +285,23 @@ mod tests {
244285

245286
fs::create_dir_all(&path)?;
246287

247-
let original_vars = HOME_VARS
248-
.iter()
249-
.map(|name| (*name, env::var_os(name)))
250-
.collect();
251-
252-
env::set_var("HOME", &path);
253-
env::set_var("USERPROFILE", &path);
254-
env::remove_var("HOMEDRIVE");
255-
env::remove_var("HOMEPATH");
256-
257-
Ok(Self {
258-
_lock: lock,
259-
path,
260-
original_vars,
261-
})
288+
let _override = super::test_home::Guard::new(&path);
289+
Ok(Self { _override, path })
262290
}
263291
}
264292

265293
impl Drop for TempHome {
266294
fn drop(&mut self) {
267-
self.original_vars
268-
.iter()
269-
.for_each(|(name, value)| match value {
270-
Some(value) => env::set_var(name, value),
271-
None => env::remove_var(name),
272-
});
273-
274295
let _ = fs::remove_dir_all(&self.path);
275296
}
276297
}
277298

299+
#[test]
300+
fn home_dir_falls_back_to_dirs_home_dir_when_override_is_unset() {
301+
let _guard = super::test_home::Guard::no_override();
302+
assert_eq!(super::home_dir(), dirs::home_dir());
303+
}
304+
278305
fn sample_config() -> Config {
279306
Config {
280307
theme: "nord".to_string(),

‎src/main.rs‎

Lines changed: 3 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -631,23 +631,18 @@ mod tests {
631631
use git2::{Repository, Signature, Time};
632632
use ratatui::style::Color;
633633
use std::env;
634-
use std::ffi::OsString;
635634
use std::fs;
636635
use std::sync::atomic::{AtomicU64, Ordering as CounterOrdering};
637-
use std::sync::MutexGuard;
638636
use std::time::{SystemTime, UNIX_EPOCH};
639637

640-
const HOME_VARS: [&str; 4] = ["HOME", "USERPROFILE", "HOMEDRIVE", "HOMEPATH"];
641-
642638
struct TestRepo {
643639
path: PathBuf,
644640
repo: Repository,
645641
}
646642

647643
struct TempHome {
648-
_lock: MutexGuard<'static, ()>,
644+
_override: config::test_home::Guard,
649645
path: PathBuf,
650-
original_vars: Vec<(&'static str, Option<OsString>)>,
651646
}
652647

653648
impl TestRepo {
@@ -743,9 +738,6 @@ mod tests {
743738

744739
impl TempHome {
745740
fn new() -> Result<Self> {
746-
let lock = config::test_home_env_lock()
747-
.lock()
748-
.unwrap_or_else(|poisoned| poisoned.into_inner());
749741
let path = env::temp_dir().join(format!(
750742
"gitlogue-main-home-{}-{}",
751743
std::process::id(),
@@ -754,21 +746,8 @@ mod tests {
754746

755747
fs::create_dir_all(&path)?;
756748

757-
let original_vars = HOME_VARS
758-
.iter()
759-
.map(|name| (*name, env::var_os(name)))
760-
.collect();
761-
762-
env::set_var("HOME", &path);
763-
env::set_var("USERPROFILE", &path);
764-
env::remove_var("HOMEDRIVE");
765-
env::remove_var("HOMEPATH");
766-
767-
Ok(Self {
768-
_lock: lock,
769-
path,
770-
original_vars,
771-
})
749+
let _override = config::test_home::Guard::new(&path);
750+
Ok(Self { _override, path })
772751
}
773752
}
774753

@@ -780,13 +759,6 @@ mod tests {
780759

781760
impl Drop for TempHome {
782761
fn drop(&mut self) {
783-
self.original_vars
784-
.iter()
785-
.for_each(|(name, value)| match value {
786-
Some(value) => env::set_var(name, value),
787-
None => env::remove_var(name),
788-
});
789-
790762
let _ = fs::remove_dir_all(&self.path);
791763
}
792764
}

0 commit comments

Comments
 (0)