Skip to main content

pacsea/index/
query.rs

1use crate::state::{PackageItem, Source};
2
3use super::idx;
4
5/// What: Search the official index for packages whose names match `query`.
6///
7/// Inputs:
8/// - `query`: Raw query string
9/// - `fuzzy`: When `true`, uses fuzzy matching (fzf-style); when `false`, uses substring matching
10///
11/// Output:
12/// - Vector of `PackageItem`s populated from the index; enrichment is not performed here.
13///   An empty or whitespace-only query returns an empty list.
14///   When fuzzy mode is enabled, items are returned with scores for sorting.
15///
16/// Details:
17/// - When `fuzzy` is `false`, performs a case-insensitive substring match on package names.
18/// - When `fuzzy` is `true`, uses fuzzy matching and returns items with match scores.
19#[must_use]
20pub fn search_official(query: &str, fuzzy: bool) -> Vec<(PackageItem, Option<i64>)> {
21    let ql = query.trim();
22    if ql.is_empty() {
23        return Vec::new();
24    }
25    if !fuzzy {
26        return idx().read().map_or_else(
27            |_| Vec::new(),
28            |index| crate::integrations::arch_toolkit::index::search(&index, ql),
29        );
30    }
31    let mut items = Vec::new();
32    if let Ok(g) = idx().read() {
33        // Create matcher once per search query for better performance
34        let fuzzy_matcher = if fuzzy {
35            Some(fuzzy_matcher::skim::SkimMatcherV2::default())
36        } else {
37            None
38        };
39        for p in &g.pkgs {
40            let match_score = if fuzzy {
41                fuzzy_matcher
42                    .as_ref()
43                    .and_then(|m| crate::util::fuzzy_match_rank_with_matcher(&p.name, ql, m))
44            } else {
45                let nl = p.name.to_lowercase();
46                let ql_lower = ql.to_lowercase();
47                if nl.contains(&ql_lower) {
48                    Some(0) // Use 0 as placeholder score for substring matches
49                } else {
50                    None
51                }
52            };
53            if let Some(score) = match_score {
54                items.push((
55                    PackageItem {
56                        name: p.name.clone(),
57                        version: p.version.clone(),
58                        description: p.description.clone(),
59                        source: Source::Official {
60                            repo: p.repo.clone(),
61                            arch: p.arch.clone(),
62                        },
63                        popularity: None,
64                        out_of_date: None,
65                        orphaned: false,
66                    },
67                    Some(score),
68                ));
69            }
70        }
71    }
72    items
73}
74
75/// What: Return the entire official index as a list of `PackageItem`s.
76///
77/// Inputs:
78/// - None
79///
80/// Output:
81/// - Vector of all official items mapped to `PackageItem`.
82///
83/// Details:
84/// - Clones data from the shared index under a read lock and omits popularity data.
85#[must_use]
86pub fn all_official() -> Vec<PackageItem> {
87    let mut items = Vec::new();
88    if let Ok(g) = idx().read() {
89        items.reserve(g.pkgs.len());
90        for p in &g.pkgs {
91            items.push(PackageItem {
92                name: p.name.clone(),
93                version: p.version.clone(),
94                description: p.description.clone(),
95                source: Source::Official {
96                    repo: p.repo.clone(),
97                    arch: p.arch.clone(),
98                },
99                popularity: None,
100                out_of_date: None,
101                orphaned: false,
102            });
103        }
104    }
105    items
106}
107
108/// What: Return the entire official list; if empty, try to populate from disk and return it.
109///
110/// Inputs:
111/// - `path`: Path to on-disk JSON index to load as a fallback
112///
113/// Output:
114/// - Vector of `PackageItem`s representing the current in-memory (or loaded) index.
115///
116/// Details:
117/// - Loads from disk only when the in-memory list is empty to avoid redundant IO.
118#[must_use]
119pub fn all_official_or_fetch(path: &std::path::Path) -> Vec<PackageItem> {
120    let items = all_official();
121    if !items.is_empty() {
122        return items;
123    }
124    super::persist::load_from_disk(path);
125    all_official()
126}
127
128#[cfg(test)]
129mod tests {
130    #[test]
131    /// What: Return empty vector when the query is blank.
132    ///
133    /// Inputs:
134    /// - Seed index with an entry and call `search_official` using whitespace-only query.
135    ///
136    /// Output:
137    /// - Empty result set.
138    ///
139    /// Details:
140    /// - Confirms whitespace trimming logic works.
141    fn search_official_empty_query_returns_empty() {
142        if let Ok(mut g) = super::idx().write() {
143            g.pkgs = vec![crate::index::OfficialPkg {
144                name: "example".to_string(),
145                repo: "core".to_string(),
146                arch: "x86_64".to_string(),
147                version: "1.0".to_string(),
148                description: "desc".to_string(),
149            }];
150        }
151        let res = super::search_official("   ", false);
152        assert!(res.is_empty());
153    }
154
155    #[test]
156    /// What: Perform case-insensitive matching and field mapping.
157    ///
158    /// Inputs:
159    /// - Seed index with uppercase/lowercase packages and query with lowercase substring.
160    ///
161    /// Output:
162    /// - Single result matching expected fields.
163    ///
164    /// Details:
165    /// - Verifies `Source::Official` metadata is preserved in mapped items.
166    fn search_official_is_case_insensitive_and_maps_fields() {
167        if let Ok(mut g) = super::idx().write() {
168            g.pkgs = vec![
169                crate::index::OfficialPkg {
170                    name: "PacSea".to_string(),
171                    repo: "core".to_string(),
172                    arch: "x86_64".to_string(),
173                    version: "1.2.3".to_string(),
174                    description: "awesome".to_string(),
175                },
176                crate::index::OfficialPkg {
177                    name: "other".to_string(),
178                    repo: "extra".to_string(),
179                    arch: "any".to_string(),
180                    version: "0.1".to_string(),
181                    description: "meh".to_string(),
182                },
183            ];
184        }
185        let res = super::search_official("pac", false);
186        assert_eq!(res.len(), 1);
187        let (item, _) = &res[0];
188        assert_eq!(item.name, "PacSea");
189        assert_eq!(item.version, "1.2.3");
190        assert_eq!(item.description, "awesome");
191        match &item.source {
192            crate::state::Source::Official { repo, arch } => {
193                assert_eq!(repo, "core");
194                assert_eq!(arch, "x86_64");
195            }
196            crate::state::Source::Aur => panic!("expected Source::Official"),
197        }
198    }
199
200    #[test]
201    /// What: Populate all official packages regardless of query.
202    ///
203    /// Inputs:
204    /// - Seed index with two packages and call `all_official`.
205    ///
206    /// Output:
207    /// - Vector containing both packages.
208    ///
209    /// Details:
210    /// - Checks ordering is not enforced but the returned names set matches expectation.
211    fn all_official_returns_all_items() {
212        if let Ok(mut g) = super::idx().write() {
213            g.pkgs = vec![
214                crate::index::OfficialPkg {
215                    name: "aa".to_string(),
216                    repo: "core".to_string(),
217                    arch: "x86_64".to_string(),
218                    version: "1".to_string(),
219                    description: "A".to_string(),
220                },
221                crate::index::OfficialPkg {
222                    name: "zz".to_string(),
223                    repo: "extra".to_string(),
224                    arch: "any".to_string(),
225                    version: "2".to_string(),
226                    description: "Z".to_string(),
227                },
228            ];
229        }
230        let items = super::all_official();
231        assert_eq!(items.len(), 2);
232        let mut names: Vec<String> = items.into_iter().map(|p| p.name).collect();
233        names.sort();
234        assert_eq!(names, vec!["aa", "zz"]);
235    }
236
237    #[tokio::test]
238    /// What: Load packages from disk when the in-memory index is empty.
239    ///
240    /// Inputs:
241    /// - Clear the index and provide a temp JSON file with one package.
242    ///
243    /// Output:
244    /// - Vector containing the package from disk.
245    ///
246    /// Details:
247    /// - Ensures fallback to `persist::load_from_disk` is exercised.
248    async fn all_official_or_fetch_reads_from_disk_when_empty() {
249        use std::path::PathBuf;
250        if let Ok(mut g) = super::idx().write() {
251            g.pkgs.clear();
252        }
253        let mut path: PathBuf = std::env::temp_dir();
254        path.push(format!(
255            "pacsea_idx_query_fetch_{}_{}.json",
256            std::process::id(),
257            std::time::SystemTime::now()
258                .duration_since(std::time::UNIX_EPOCH)
259                .expect("System time is before UNIX epoch")
260                .as_nanos()
261        ));
262        let idx_json = serde_json::json!({
263            "pkgs": [
264                {"name": "foo", "repo": "core", "arch": "x86_64", "version": "1", "description": ""}
265            ]
266        });
267        std::fs::write(
268            &path,
269            serde_json::to_string(&idx_json).expect("failed to serialize index JSON"),
270        )
271        .expect("failed to write index JSON file");
272        let items = super::all_official_or_fetch(&path);
273        assert_eq!(items.len(), 1);
274        assert_eq!(items[0].name, "foo");
275        let _ = std::fs::remove_file(&path);
276    }
277
278    #[test]
279    /// What: Verify fuzzy search finds non-substring matches and normal search still works.
280    ///
281    /// Inputs:
282    /// - Seed index with packages and test both fuzzy and normal search modes.
283    ///
284    /// Output:
285    /// - Fuzzy mode finds "ripgrep" with query "rg", normal mode does not.
286    /// - Normal mode finds substring matches as before.
287    ///
288    /// Details:
289    /// - Tests that fuzzy matching enables finding packages by character sequence matching.
290    fn search_official_fuzzy_vs_normal() {
291        if let Ok(mut g) = super::idx().write() {
292            g.pkgs = vec![
293                crate::index::OfficialPkg {
294                    name: "ripgrep".to_string(),
295                    repo: "core".to_string(),
296                    arch: "x86_64".to_string(),
297                    version: "1.0".to_string(),
298                    description: "fast grep".to_string(),
299                },
300                crate::index::OfficialPkg {
301                    name: "other".to_string(),
302                    repo: "extra".to_string(),
303                    arch: "any".to_string(),
304                    version: "0.1".to_string(),
305                    description: "meh".to_string(),
306                },
307            ];
308        }
309
310        // Normal mode: "rg" should not match "ripgrep" (not a substring)
311        let res_normal = super::search_official("rg", false);
312        assert_eq!(res_normal.len(), 0);
313
314        // Fuzzy mode: "rg" should match "ripgrep" (fuzzy match)
315        let res_fuzzy = super::search_official("rg", true);
316        assert_eq!(res_fuzzy.len(), 1);
317        let (item, score) = &res_fuzzy[0];
318        assert_eq!(item.name, "ripgrep");
319        assert!(score.is_some());
320
321        // Both modes should find "rip" (substring match)
322        let res_normal2 = super::search_official("rip", false);
323        assert_eq!(res_normal2.len(), 1);
324        let res_fuzzy2 = super::search_official("rip", true);
325        assert_eq!(res_fuzzy2.len(), 1);
326    }
327}