Skip to main content

windows_headless/
cache.rs

1//! Single shared cache-root resolution for every cache group.
2//!
3//! Pre-patch behavior was six hand-rolled `match env::var(...)` blocks that
4//! silently scattered `<cwd>/.cache` dirs for installed runs. Now one helper
5//! built on `cache_manager::CacheResolver`: explicit `--dir` wins, then the
6//! per-group env var, then Cargo workspace discovery, then the OS user cache
7//! (`~/Library/Caches`, `$XDG_CACHE_HOME`, `%LOCALAPPDATA%`). No workspace +
8//! no override = `Err`, never a silent CWD cache. The winner is announced via
9//! `tracing::info!` (library-safe; the CLI installs an stderr subscriber, so
10//! it shows by default and `RUST_LOG` overrides).
11#[cfg(feature = "downloader")]
12use anyhow::{Context, Result};
13#[cfg(feature = "downloader")]
14use cache_manager::{CacheResolver, CacheRoot};
15
16/// Shared OS-cache identity for all windows-headless cache groups.
17#[cfg(feature = "downloader")]
18const OS_CACHE_QUALIFIER: &str = "com";
19#[cfg(feature = "downloader")]
20const OS_CACHE_ORGANIZATION: &str = "jzombie";
21#[cfg(feature = "downloader")]
22const OS_CACHE_APPLICATION: &str = "windows-headless";
23
24/// Resolve the cache root for one group: `explicit` (CLI `--dir`) wins, then
25/// `env_var` (e.g. `"WINDOWS_HEADLESS_QEMU_DIR"`), then workspace discovery,
26/// then the OS user cache. Announces `cache: <path> (<source>)`.
27#[cfg(feature = "downloader")]
28pub fn resolve_cache_root(
29    explicit: Option<std::path::PathBuf>,
30    env_var: &str,
31) -> Result<CacheRoot> {
32    let resolver = CacheResolver {
33        explicit,
34        env_var: Some(env_var.to_string()),
35        project_dirs: Some((
36            OS_CACHE_QUALIFIER.to_string(),
37            OS_CACHE_ORGANIZATION.to_string(),
38            OS_CACHE_APPLICATION.to_string(),
39        )),
40        ..CacheResolver::default()
41    };
42    let (root, source) = resolver.resolve().with_context(|| {
43        format!(
44            "no cache location: set ${env_var} or run from inside the project checkout \
45             (installed runs fall back to the OS user cache automatically)"
46        )
47    })?;
48    tracing::info!("cache: {} ({source:?})", root.path().display());
49    Ok(root)
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55    use std::sync::{Mutex, MutexGuard, OnceLock};
56
57    fn test_lock() -> &'static Mutex<()> {
58        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
59        LOCK.get_or_init(|| Mutex::new(()))
60    }
61
62    /// Hold the global test lock AND move CWD into a bare tmpdir (no
63    /// Cargo.toml above), restoring both on drop. Serializes these tests
64    /// against each other (env + CWD are process-global).
65    struct BareCwd {
66        previous: std::path::PathBuf,
67        _lock: MutexGuard<'static, ()>,
68    }
69
70    impl BareCwd {
71        fn enter() -> Self {
72            let lock = test_lock().lock().expect("acquire test lock");
73            let previous = std::env::current_dir().expect("current dir");
74            let tmp = tempfile::tempdir().expect("tempdir");
75            // Leak the TempDir path intentionally: the dir must survive for
76            // the whole test while CWD points inside it.
77            let bare = tmp.path().join("bare");
78            std::fs::create_dir_all(&bare).expect("create bare");
79            std::env::set_current_dir(&bare).expect("set cwd");
80            // Forget the TempDir so the dir survives for the whole test while
81            // CWD points inside it (removed when the process exits; tests only).
82            std::mem::forget(tmp);
83            Self {
84                previous,
85                _lock: lock,
86            }
87        }
88    }
89
90    impl Drop for BareCwd {
91        fn drop(&mut self) {
92            let _ = std::env::set_current_dir(&self.previous);
93        }
94    }
95
96    /// RAII guard for a process-global env var: captures the prior value on
97    /// creation and restores it in `Drop`, so a panicking assertion can never
98    /// poison the environment for later tests. Bind as `_env_guard` and keep
99    /// it alive for the whole test.
100    struct EnvGuard {
101        name: String,
102        prior: Option<String>,
103    }
104
105    impl EnvGuard {
106        fn take(name: &str) -> Self {
107            Self {
108                name: name.to_string(),
109                prior: std::env::var(name).ok(),
110            }
111        }
112    }
113
114    impl Drop for EnvGuard {
115        fn drop(&mut self) {
116            // SAFETY: every test touching env holds the shared test lock via
117            // `BareCwd`, so no two tests can race, and this exact var is
118            // restored to its prior value (no other thread observes these
119            // test-scoped names).
120            unsafe {
121                match &self.prior {
122                    Some(v) => std::env::set_var(&self.name, v),
123                    None => std::env::remove_var(&self.name),
124                }
125            }
126        }
127    }
128
129    #[test]
130    fn explicit_path_wins() {
131        let _bare = BareCwd::enter();
132        let dir = std::env::current_dir().unwrap().join("explicit-root");
133        let root = resolve_cache_root(Some(dir.clone()), "WINDOWS_HEADLESS_CACHE_TEST_EXPLICIT")
134            .expect("resolve");
135        assert_eq!(root.path(), dir.as_path());
136    }
137
138    #[test]
139    fn env_var_wins_over_os_cache() {
140        let _bare = BareCwd::enter();
141        let name = "WINDOWS_HEADLESS_CACHE_TEST_ENV";
142        let _env_guard = EnvGuard::take(name);
143        let want = std::env::current_dir().unwrap().join("env-root");
144        // SAFETY: serialized by the test lock; test-scoped name, guard restores.
145        unsafe { std::env::set_var(name, &want) };
146        let root = resolve_cache_root(None, name).expect("resolve");
147        assert_eq!(root.path(), want.as_path());
148    }
149
150    #[test]
151    fn bare_cwd_falls_back_to_os_cache_never_cwd() {
152        let _bare = BareCwd::enter();
153        let name = "WINDOWS_HEADLESS_CACHE_TEST_OS";
154        let _env_guard = EnvGuard::take(name);
155        // SAFETY: serialized by the test lock; test-scoped name, guard restores.
156        unsafe { std::env::remove_var(name) };
157        let root = resolve_cache_root(None, name).expect("resolve");
158        // Must NOT be <cwd>/.cache (the old silent scatter).
159        assert!(
160            !root.path().starts_with(std::env::current_dir().unwrap()),
161            "scattered into CWD: {}",
162            root.path().display()
163        );
164        assert!(
165            root.path().to_string_lossy().contains("windows-headless"),
166            "expected OS user cache path, got {}",
167            root.path().display()
168        );
169    }
170}