Skip to main content

pacsea/index/
installed.rs

1use super::installed_lock;
2
3/// What: Refresh the process-wide cache of installed package names using `pacman -Qq`.
4///
5/// Inputs:
6/// - None (spawns a blocking task to run pacman)
7///
8/// Output:
9/// - Updates the global installed-name set; ignores errors.
10///
11/// Details:
12/// - Parses command stdout into a `HashSet` and swaps it into the shared cache under a write lock.
13pub async fn refresh_installed_cache() {
14    if let Ok(Ok(body)) =
15        tokio::task::spawn_blocking(|| crate::util::pacman::run_pacman(&["-Qq"])).await
16    {
17        let set: std::collections::HashSet<String> =
18            body.lines().map(|s| s.trim().to_string()).collect();
19        if let Ok(mut g) = installed_lock().write() {
20            *g = set;
21        }
22    }
23}
24
25/// What: Query whether `name` appears in the cached set of installed packages.
26///
27/// Inputs:
28/// - `name`: Package name
29///
30/// Output:
31/// - `true` if `name` is present; `false` when absent or if the cache is unavailable.
32///
33/// Details:
34/// - Acquires a read lock and defers to `HashSet::contains`, returning false on lock poisoning.
35#[must_use]
36pub fn is_installed(name: &str) -> bool {
37    installed_lock().read().is_ok_and(|s| s.contains(name))
38}
39
40#[cfg(test)]
41mod tests {
42    /// What: Return false when the cache is empty or the package is missing.
43    ///
44    /// Inputs:
45    /// - Clear `INSTALLED_SET` and query an unknown package name.
46    ///
47    /// Output:
48    /// - Boolean `false` result.
49    ///
50    /// Details:
51    /// - Confirms empty cache behaves as expected without panicking.
52    #[test]
53    fn is_installed_returns_false_when_uninitialized_or_missing() {
54        let _guard = crate::global_test_mutex()
55            .lock()
56            .unwrap_or_else(std::sync::PoisonError::into_inner);
57        if let Ok(mut g) = super::installed_lock().write() {
58            g.clear();
59        }
60        assert!(!super::is_installed("foo"));
61    }
62
63    /// What: Verify membership lookups return true only for cached names.
64    ///
65    /// Inputs:
66    /// - Insert `bar` into `INSTALLED_SET` before querying.
67    ///
68    /// Output:
69    /// - `true` for `bar` and `false` for `baz`.
70    ///
71    /// Details:
72    /// - Exercises both positive and negative membership checks.
73    #[test]
74    fn is_installed_checks_membership_in_cached_set() {
75        let _guard = crate::global_test_mutex()
76            .lock()
77            .unwrap_or_else(std::sync::PoisonError::into_inner);
78        if let Ok(mut g) = super::installed_lock().write() {
79            g.clear();
80            g.insert("bar".to_string());
81        }
82        assert!(super::is_installed("bar"));
83        assert!(!super::is_installed("baz"));
84    }
85
86    #[cfg(not(target_os = "windows"))]
87    #[allow(clippy::await_holding_lock)]
88    #[tokio::test]
89    /// What: Populate the installed cache from pacman output.
90    ///
91    /// Inputs:
92    /// - Override PATH with a fake pacman that emits installed package names before invoking the refresh.
93    ///
94    /// Output:
95    /// - Cache lookup succeeds for the emitted names after `refresh_installed_cache` completes.
96    ///
97    /// Details:
98    /// - Exercises the async refresh path, ensures PATH is restored, and verifies cache contents via helper accessors.
99    async fn refresh_installed_cache_populates_cache_from_pacman_output() {
100        struct PathGuard {
101            original: String,
102        }
103        impl Drop for PathGuard {
104            fn drop(&mut self) {
105                unsafe {
106                    std::env::set_var("PATH", &self.original);
107                }
108            }
109        }
110        let _guard = crate::global_test_mutex_lock();
111
112        if let Ok(mut g) = super::installed_lock().write() {
113            g.clear();
114        }
115
116        let original_path = std::env::var("PATH").unwrap_or_default();
117        let _path_guard = PathGuard {
118            original: original_path.clone(),
119        };
120
121        let mut root = std::env::temp_dir();
122        root.push(format!(
123            "pacsea_fake_pacman_qq_{}_{}",
124            std::process::id(),
125            std::time::SystemTime::now()
126                .duration_since(std::time::UNIX_EPOCH)
127                .expect("System time is before UNIX epoch")
128                .as_nanos()
129        ));
130        std::fs::create_dir_all(&root).expect("failed to create test root directory");
131        let mut bin = root.clone();
132        bin.push("bin");
133        std::fs::create_dir_all(&bin).expect("failed to create test bin directory");
134        let mut script = bin.clone();
135        script.push("pacman");
136        let body = r#"#!/usr/bin/env bash
137set -e
138if [[ "$1" == "-Qq" ]]; then
139  echo "alpha"
140  echo "beta"
141  exit 0
142fi
143exit 1
144"#;
145        std::fs::write(&script, body).expect("failed to write test pacman script");
146        #[cfg(unix)]
147        {
148            use std::os::unix::fs::PermissionsExt;
149            let mut perm = std::fs::metadata(&script)
150                .expect("failed to read test pacman script metadata")
151                .permissions();
152            perm.set_mode(0o755);
153            std::fs::set_permissions(&script, perm)
154                .expect("failed to set test pacman script permissions");
155        }
156        let new_path = format!("{}:{original_path}", bin.to_string_lossy());
157        unsafe {
158            std::env::set_var("PATH", &new_path);
159        }
160
161        super::refresh_installed_cache().await;
162
163        let _ = std::fs::remove_dir_all(&root);
164
165        assert!(super::is_installed("alpha"));
166        assert!(super::is_installed("beta"));
167        assert!(!super::is_installed("gamma"));
168    }
169}