arch-toolkit 0.3.0

Complete Rust toolkit for Arch Linux package management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! Index-related data types for official repository package operations.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

/// What: Capture the minimal metadata about an official package entry.
///
/// Inputs:
/// - Populated primarily from `pacman -Sl`/API responses with optional enrichment.
///
/// Output:
/// - Serves as the source of truth for official repository package information.
///
/// Details:
/// - Represents a package from official Arch Linux repositories.
/// - Non-name fields may be empty initially; enrichment routines fill them lazily.
/// - Serializable via Serde to allow saving and restoring across sessions.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct OfficialPackage {
    /// Package name.
    pub name: String,
    /// Repository name (e.g., "core", "extra", "community").
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub repo: String,
    /// Target architecture (e.g., `x86_64`, `any`).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub arch: String,
    /// Package version.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub version: String,
    /// Package description.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub description: String,
}

/// What: Represent the full collection of official packages maintained in memory.
///
/// Inputs:
/// - Populated by fetch and enrichment routines before being persisted or queried.
///
/// Output:
/// - Exposed through API helpers that clone or iterate the package list.
///
/// Details:
/// - Serializable via Serde to allow saving and restoring across sessions.
/// - The `name_to_idx` field is derived from `pkgs` and skipped during serialization.
/// - Provides O(1) lookup via `find_package_by_name()` when `name_to_idx` is populated.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct OfficialIndex {
    /// All known official packages in the index.
    pub pkgs: Vec<OfficialPackage>,
    /// Index mapping lowercase package names to their position in `pkgs` for O(1) lookups.
    /// Skipped during serialization; rebuilt after deserialization via `rebuild_name_index()`.
    #[serde(skip)]
    pub name_to_idx: HashMap<String, usize>,
}

impl OfficialIndex {
    /// What: Rebuild the `name_to_idx` `HashMap` from the current `pkgs` Vec.
    ///
    /// Inputs:
    /// - None (operates on `self.pkgs`)
    ///
    /// Output:
    /// - Populates `self.name_to_idx` with lowercase package names mapped to indices.
    ///
    /// Details:
    /// - Should be called after deserialization or when `pkgs` is modified.
    /// - Uses lowercase names for case-insensitive lookups.
    /// - Clears existing index before rebuilding to ensure consistency.
    pub fn rebuild_name_index(&mut self) {
        self.name_to_idx.clear();
        self.name_to_idx.reserve(self.pkgs.len());
        for (i, pkg) in self.pkgs.iter().enumerate() {
            self.name_to_idx.insert(pkg.name.to_lowercase(), i);
        }
    }

    /// What: Find a package by name in the official index using O(1) lookup.
    ///
    /// Inputs:
    /// - `name`: Package name to search for (case-insensitive)
    ///
    /// Output:
    /// - `Some(&OfficialPackage)` if the package is found, `None` otherwise.
    ///
    /// Details:
    /// - Uses the `name_to_idx` `HashMap` for O(1) lookup by lowercase name.
    /// - Falls back to linear scan if `HashMap` is empty (e.g., before rebuild).
    /// - Case-insensitive matching is performed.
    #[must_use]
    pub fn find_package_by_name(&self, name: &str) -> Option<&OfficialPackage> {
        // Try O(1) HashMap lookup first
        let name_lower = name.to_lowercase();
        if let Some(&idx) = self.name_to_idx.get(&name_lower) {
            return self.pkgs.get(idx);
        }
        // Fallback to linear scan if HashMap is empty or index mismatch
        self.pkgs.iter().find(|p| p.name.eq_ignore_ascii_case(name))
    }
}

/// What: Search result with optional fuzzy matching score.
///
/// Inputs:
/// - Created by search functions that match packages against queries.
///
/// Output:
/// - Contains the matched package and its fuzzy score (if fuzzy matching was used).
///
/// Details:
/// - Used to return search results with relevance scores for sorting.
/// - `fuzzy_score` is `None` for exact or substring matches.
/// - `fuzzy_score` is `Some(i64)` when fuzzy matching is enabled, with higher scores indicating better matches.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct IndexQueryResult {
    /// The matched package.
    pub package: OfficialPackage,
    /// Fuzzy matching score, if fuzzy matching was used.
    pub fuzzy_score: Option<i64>,
}

/// What: Filter mode for querying explicitly installed packages.
///
/// Inputs:
/// - Used as parameter to explicit package query functions.
///
/// Output:
/// - Determines which pacman command arguments are used.
///
/// Details:
/// - `LeafOnly`: Uses `pacman -Qetq` (explicitly installed AND not required by other packages).
/// - `AllExplicit`: Uses `pacman -Qeq` (all explicitly installed packages, including dependencies).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum InstalledPackagesMode {
    /// Query only leaf packages (explicitly installed and not required).
    LeafOnly,
    /// Query all explicitly installed packages.
    AllExplicit,
}

/// What: Represent one mirror-status row that can produce a pacman server line.
///
/// Inputs:
/// - Parsed from a caller-selected mirror-status JSON endpoint or constructed
///   directly by callers.
///
/// Output:
/// - Portable mirror metadata for deterministic filtering and mirrorlist generation.
///
/// Details:
/// - `url` is a mirror base URL; generation appends `/$repo/os/$arch`.
/// - `active` and `protocols` are source metadata, not a live health claim by
///   this library.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct MirrorInfo {
    /// Mirror base URL, normally ending in `/`.
    pub url: String,
    /// Whether the discovery source marked the mirror active.
    pub active: bool,
    /// Transport protocols advertised by the discovery source.
    pub protocols: Vec<String>,
}

/// What: Hold explicit bounds for caller-client mirror-status discovery.
///
/// Inputs:
/// - Constructed directly or with [`MirrorDiscoveryLimits::default`].
///
/// Output:
/// - Maximum response bytes and accepted mirror rows for one discovery request.
///
/// Details:
/// - Bounds apply before JSON parsing and while accepting valid rows, keeping
///   remote endpoint responses from causing unbounded resource use.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct MirrorDiscoveryLimits {
    /// Maximum response-body bytes accepted before JSON parsing.
    pub max_response_bytes: usize,
    /// Maximum valid mirror rows returned to the caller.
    pub max_mirrors: usize,
}

impl Default for MirrorDiscoveryLimits {
    /// What: Provide conservative default bounds for one mirror-status request.
    ///
    /// Inputs: None.
    ///
    /// Output:
    /// - A 512 KiB response bound and 128 returned mirrors.
    ///
    /// Details:
    /// - Callers can choose tighter limits for constrained environments or
    ///   larger explicit limits when their application has reviewed the cost.
    fn default() -> Self {
        Self {
            max_response_bytes: 512 * 1024,
            max_mirrors: 128,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    /// What: Verify `rebuild_name_index` populates `HashMap` correctly.
    ///
    /// Inputs:
    /// - `OfficialIndex` with two packages.
    ///
    /// Output:
    /// - `HashMap` contains lowercase names mapped to correct indices.
    ///
    /// Details:
    /// - Tests that the `HashMap` is built correctly and supports case-insensitive lookups.
    fn rebuild_name_index_populates_hashmap() {
        let mut index = OfficialIndex {
            pkgs: vec![
                OfficialPackage {
                    name: "PackageA".to_string(),
                    repo: "core".to_string(),
                    arch: "x86_64".to_string(),
                    version: "1.0".to_string(),
                    description: "Desc A".to_string(),
                },
                OfficialPackage {
                    name: "PackageB".to_string(),
                    repo: "extra".to_string(),
                    arch: "any".to_string(),
                    version: "2.0".to_string(),
                    description: "Desc B".to_string(),
                },
            ],
            name_to_idx: HashMap::new(),
        };

        index.rebuild_name_index();

        assert_eq!(index.name_to_idx.len(), 2);
        assert_eq!(index.name_to_idx.get("packagea"), Some(&0));
        assert_eq!(index.name_to_idx.get("packageb"), Some(&1));
        // Original case should not be found
        assert_eq!(index.name_to_idx.get("PackageA"), None);
    }

    #[test]
    /// What: Verify `find_package_by_name` uses `HashMap` for O(1) lookup.
    ///
    /// Inputs:
    /// - Seed index with packages and rebuilt `HashMap`.
    ///
    /// Output:
    /// - Package found via case-insensitive name lookup.
    ///
    /// Details:
    /// - Tests that find works with different case variations.
    fn find_package_by_name_uses_hashmap() {
        let mut index = OfficialIndex {
            pkgs: vec![
                OfficialPackage {
                    name: "ripgrep".to_string(),
                    repo: "extra".to_string(),
                    arch: "x86_64".to_string(),
                    version: "14.0.0".to_string(),
                    description: "Fast grep".to_string(),
                },
                OfficialPackage {
                    name: "vim".to_string(),
                    repo: "extra".to_string(),
                    arch: "x86_64".to_string(),
                    version: "9.0".to_string(),
                    description: "Text editor".to_string(),
                },
            ],
            name_to_idx: HashMap::new(),
        };

        index.rebuild_name_index();

        // Test exact case
        let result = index.find_package_by_name("ripgrep");
        assert!(result.is_some());
        assert_eq!(result.map(|p| p.name.as_str()), Some("ripgrep"));

        // Test different case (HashMap uses lowercase)
        let result_upper = index.find_package_by_name("RIPGREP");
        assert!(result_upper.is_some());
        assert_eq!(result_upper.map(|p| p.name.as_str()), Some("ripgrep"));

        // Test non-existent package
        let not_found = index.find_package_by_name("nonexistent");
        assert!(not_found.is_none());
    }

    #[test]
    /// What: Verify `find_package_by_name` falls back to linear scan when `HashMap` is empty.
    ///
    /// Inputs:
    /// - `OfficialIndex` with packages but empty `name_to_idx`.
    ///
    /// Output:
    /// - Package found via linear scan fallback.
    ///
    /// Details:
    /// - Tests that the fallback mechanism works when index is not rebuilt.
    fn find_package_by_name_fallback_to_linear_scan() {
        let index = OfficialIndex {
            pkgs: vec![OfficialPackage {
                name: "test-package".to_string(),
                repo: "core".to_string(),
                arch: "x86_64".to_string(),
                version: "1.0".to_string(),
                description: "Test".to_string(),
            }],
            name_to_idx: HashMap::new(),
        };

        // Should still find package via linear scan
        let result = index.find_package_by_name("test-package");
        assert!(result.is_some());
        assert_eq!(result.map(|p| p.name.as_str()), Some("test-package"));

        // Case-insensitive fallback
        let result_upper = index.find_package_by_name("TEST-PACKAGE");
        assert!(result_upper.is_some());
    }

    #[test]
    /// What: Verify serialization and deserialization of `OfficialIndex`.
    ///
    /// Inputs:
    /// - `OfficialIndex` with packages and rebuilt name index.
    ///
    /// Output:
    /// - Deserialized index matches original, and name index can be rebuilt.
    ///
    /// Details:
    /// - Tests that `name_to_idx` is skipped during serialization.
    /// - Verifies that index can be rebuilt after deserialization.
    fn serialization_deserialization() {
        let mut index = OfficialIndex {
            pkgs: vec![
                OfficialPackage {
                    name: "package1".to_string(),
                    repo: "core".to_string(),
                    arch: "x86_64".to_string(),
                    version: "1.0".to_string(),
                    description: "Package 1".to_string(),
                },
                OfficialPackage {
                    name: "package2".to_string(),
                    repo: "extra".to_string(),
                    arch: "any".to_string(),
                    version: "2.0".to_string(),
                    description: "Package 2".to_string(),
                },
            ],
            name_to_idx: HashMap::new(),
        };

        index.rebuild_name_index();

        // Serialize
        let json = serde_json::to_string(&index).expect("Serialization should succeed");
        assert!(!json.contains("name_to_idx")); // Should be skipped

        // Deserialize
        let mut deserialized: OfficialIndex =
            serde_json::from_str(&json).expect("Deserialization should succeed");
        assert_eq!(deserialized.pkgs.len(), 2);
        assert!(deserialized.name_to_idx.is_empty()); // Should be empty after deserialization

        // Rebuild index
        deserialized.rebuild_name_index();
        assert_eq!(deserialized.name_to_idx.len(), 2);
        assert_eq!(deserialized.name_to_idx.get("package1"), Some(&0));
        assert_eq!(deserialized.name_to_idx.get("package2"), Some(&1));

        // Verify find works after rebuild
        let found = deserialized.find_package_by_name("package1");
        assert!(found.is_some());
        assert_eq!(found.map(|p| p.name.as_str()), Some("package1"));
    }

    #[test]
    /// What: Verify `IndexQueryResult` creation and serialization.
    ///
    /// Inputs:
    /// - `IndexQueryResult` with package and optional fuzzy score.
    ///
    /// Output:
    /// - Result can be created and serialized correctly.
    ///
    /// Details:
    /// - Tests both with and without fuzzy score.
    fn index_query_result_creation() {
        let package = OfficialPackage {
            name: "test".to_string(),
            repo: "core".to_string(),
            arch: "x86_64".to_string(),
            version: "1.0".to_string(),
            description: "Test package".to_string(),
        };

        // With fuzzy score
        let result_with_score = IndexQueryResult {
            package: package.clone(),
            fuzzy_score: Some(100),
        };
        assert_eq!(result_with_score.fuzzy_score, Some(100));

        // Without fuzzy score
        let result_without_score = IndexQueryResult {
            package,
            fuzzy_score: None,
        };
        assert_eq!(result_without_score.fuzzy_score, None);

        // Serialization test
        let json = serde_json::to_string(&result_with_score).expect("Should serialize");
        let deserialized: IndexQueryResult =
            serde_json::from_str(&json).expect("Should deserialize");
        assert_eq!(deserialized.fuzzy_score, Some(100));
        assert_eq!(deserialized.package.name, "test");
    }
}