pacsea 0.8.2

A fast, friendly TUI for browsing and installing Arch and AUR packages with built-in news and security scanning
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//! Package metadata fetching and parsing utilities.
//!
//! This module provides functions to fetch package metadata from pacman and
//! parse the output into structured data.

use super::command::{CommandError, CommandRunner};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

/// What: Extract remote download/install sizes for an official package via
/// `pacman -Si`.
///
/// Inputs:
/// - `runner`: Command executor.
/// - `repo`: Repository name (e.g., `"core"`).
/// - `name`: Package identifier.
/// - `expected_version`: Version string to cross-check.
///
/// Output:
/// - `Ok(OfficialMetadata)` containing optional size metrics.
/// - `Err(CommandError)` when the command fails.
///
/// Details:
/// - Performs best-effort verification of the returned version, logging
///   mismatches for diagnostics.
pub(super) fn fetch_official_metadata<R: CommandRunner>(
    runner: &R,
    repo: &str,
    name: &str,
    expected_version: &str,
) -> Result<OfficialMetadata, CommandError> {
    let spec = format!("{repo}/{name}");
    let output = runner.run("pacman", &["-Si", &spec])?;
    let fields = parse_pacman_key_values(&output);

    if let Some(version) = fields.get("Version")
        && version.trim() != expected_version
    {
        tracing::debug!(
            "Preflight summary: pacman -Si reported version {} for {} (expected {})",
            version.trim(),
            spec,
            expected_version
        );
    }

    let download_size = fields
        .get("Download Size")
        .and_then(|raw| parse_size_to_bytes(raw));
    let install_size = fields
        .get("Installed Size")
        .and_then(|raw| parse_size_to_bytes(raw));

    Ok(OfficialMetadata {
        download_size,
        install_size,
    })
}

/// What: Retrieve installed package version via `pacman -Q`.
///
/// Inputs:
/// - `runner`: Command executor.
/// - `name`: Package identifier.
///
/// Output:
/// - `Ok(String)` containing the installed version.
/// - `Err(CommandError)` when fetch fails.
///
/// Details:
/// - Trims stdout and returns the last whitespace-separated token.
pub(super) fn fetch_installed_version<R: CommandRunner>(
    runner: &R,
    name: &str,
) -> Result<String, CommandError> {
    let output = runner.run("pacman", &["-Q", name])?;
    let mut parts = output.split_whitespace();
    let _pkg_name = parts.next();
    parts
        .next_back()
        .map(ToString::to_string)
        .ok_or_else(|| CommandError::Parse {
            program: "pacman -Q".to_string(),
            field: "version".to_string(),
        })
}

/// What: Retrieve the installed size of a package via `pacman -Qi`.
///
/// Inputs:
/// - `runner`: Command executor.
/// - `name`: Package identifier.
///
/// Output:
/// - `Ok(u64)` representing bytes installed.
/// - `Err(CommandError)` when parsing fails.
///
/// Details:
/// - Parses the `Installed Size` field using [`parse_size_to_bytes`].
pub(super) fn fetch_installed_size<R: CommandRunner>(
    runner: &R,
    name: &str,
) -> Result<u64, CommandError> {
    let output = runner.run("pacman", &["-Qi", name])?;
    let fields = parse_pacman_key_values(&output);
    fields
        .get("Installed Size")
        .and_then(|raw| parse_size_to_bytes(raw))
        .ok_or_else(|| CommandError::Parse {
            program: "pacman -Qi".to_string(),
            field: "Installed Size".to_string(),
        })
}

/// What: Metadata extracted from `pacman -Si` to inform download/install
/// calculations.
///
/// Inputs: Populated by [`fetch_official_metadata`].
///
/// Output: Holds optional download and install sizes in bytes.
///
/// Details:
/// - Values are `None` when the upstream output omits a field.
#[derive(Default, Debug)]
pub struct OfficialMetadata {
    /// Download size in bytes, if available.
    pub(crate) download_size: Option<u64>,
    /// Install size in bytes, if available.
    pub(crate) install_size: Option<u64>,
}

/// What: Transform pacman key-value output into a `HashMap`.
///
/// Inputs:
/// - `output`: Raw stdout from `pacman` invocations.
///
/// Output:
/// - `HashMap<String, String>` mapping field names to raw string values.
///
/// Details:
/// - Continuation lines (prefixed with a space) are appended to the previous
///   key's value.
pub(super) fn parse_pacman_key_values(output: &str) -> HashMap<String, String> {
    let mut map = HashMap::new();
    let mut last_key: Option<String> = None;

    for line in output.lines() {
        if line.trim().is_empty() {
            continue;
        }
        if let Some((key, value)) = line.split_once(':') {
            let key = key.trim().to_string();
            let val = value.trim().to_string();
            map.insert(key.clone(), val);
            last_key = Some(key);
        } else if line.starts_with(' ')
            && let Some(key) = &last_key
        {
            map.entry(key.clone())
                .and_modify(|existing| {
                    if !existing.ends_with(' ') {
                        existing.push(' ');
                    }
                    existing.push_str(line.trim());
                })
                .or_insert_with(|| line.trim().to_string());
        }
    }

    map
}

/// What: Convert human-readable pacman size strings to bytes.
///
/// Inputs:
/// - `raw`: String such as `"1.5 MiB"` or `"512 KiB"`.
///
/// Output:
/// - `Some(u64)` with byte representation on success.
/// - `None` when parsing fails.
///
/// Details:
/// - Supports B, KiB, MiB, GiB, and TiB units.
pub(super) fn parse_size_to_bytes(raw: &str) -> Option<u64> {
    // Maximum f64 value that fits in u64 (2^64 - 1, but f64 can represent up to 2^53 exactly)
    // For values beyond 2^53, we check if they exceed u64::MAX by comparing with a threshold
    const MAX_U64_AS_F64: f64 = 18_446_744_073_709_551_615.0; // u64::MAX as approximate f64
    let mut parts = raw.split_whitespace();
    let number = parts.next()?.replace(',', "");
    let value = number.parse::<f64>().ok()?;
    let unit = parts.next().unwrap_or("B");
    let multiplier = match unit {
        "KiB" => 1024.0,
        "MiB" => 1024.0 * 1024.0,
        "GiB" => 1024.0 * 1024.0 * 1024.0,
        "TiB" => 1024.0 * 1024.0 * 1024.0 * 1024.0,
        _ => 1.0,
    };
    let result = value * multiplier;
    // Check bounds: negative values are invalid
    if result < 0.0 {
        return None;
    }
    if result > MAX_U64_AS_F64 {
        return None;
    }
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let bytes = result.round() as u64;
    Some(bytes)
}

/// What: Find AUR package file in pacman cache or AUR helper caches.
///
/// Inputs:
/// - `name`: Package name to search for.
/// - `version`: Package version (optional, for matching).
///
/// Output:
/// - `Some(PathBuf)` pointing to the package file if found.
/// - `None` if no package file is found in any cache.
///
/// Details:
/// - Checks pacman cache (`/var/cache/pacman/pkg/`).
/// - Checks AUR helper caches (paru/yay build directories).
/// - Matches package files by name prefix and optionally by version.
fn find_aur_package_file(name: &str, version: Option<&str>) -> Option<PathBuf> {
    // Try pacman cache first (fastest, most reliable)
    if let Ok(pacman_cache) = Path::new("/var/cache/pacman/pkg").read_dir() {
        for entry in pacman_cache.flatten() {
            let path = entry.path();
            if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) {
                // Match package name prefix (e.g., "yay-12.3.2-1-x86_64.pkg.tar.zst")
                if file_name.starts_with(name)
                    && (file_name.ends_with(".pkg.tar.zst") || file_name.ends_with(".pkg.tar.xz"))
                {
                    // If version specified, try to match it
                    if let Some(ver) = version {
                        if file_name.contains(ver) {
                            return Some(path);
                        }
                    } else {
                        return Some(path);
                    }
                }
            }
        }
    }

    // Try AUR helper caches
    if let Ok(home) = std::env::var("HOME") {
        let cache_paths = [
            format!("{home}/.cache/paru/clone/{name}"),
            format!("{home}/.cache/yay/{name}"),
        ];

        for cache_base in cache_paths {
            let cache_dir = Path::new(&cache_base);
            if let Ok(entries) = fs::read_dir(cache_dir) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    if path.is_file()
                        && let Some(file_name) = path.file_name().and_then(|n| n.to_str())
                        && file_name.starts_with(name)
                        && (file_name.ends_with(".pkg.tar.zst")
                            || file_name.ends_with(".pkg.tar.xz"))
                    {
                        if let Some(ver) = version {
                            if file_name.contains(ver) {
                                return Some(path);
                            }
                        } else {
                            return Some(path);
                        }
                    }
                }
            }
        }
    }

    None
}

/// What: Extract download and install sizes from an AUR package file.
///
/// Inputs:
/// - `runner`: Command executor.
/// - `pkg_path`: Path to the package file.
///
/// Output:
/// - `OfficialMetadata` with `download_size` (file size) and `install_size` (from package metadata).
///
/// Details:
/// - Download size is the actual file size on disk.
/// - Install size is extracted via `pacman -Qp` command.
/// - Errors are handled gracefully by returning None values.
fn extract_aur_package_sizes<R: CommandRunner>(runner: &R, pkg_path: &Path) -> OfficialMetadata {
    // Get download size (file size on disk)
    let download_size = fs::metadata(pkg_path).ok().map(|meta| meta.len());

    // Get install size from package metadata
    let install_size = pkg_path.to_str().and_then(|pkg_str| {
        runner
            .run("pacman", &["-Qp", pkg_str])
            .ok()
            .and_then(|output| {
                let fields = parse_pacman_key_values(&output);
                fields
                    .get("Installed Size")
                    .and_then(|raw| parse_size_to_bytes(raw))
            })
    });

    OfficialMetadata {
        download_size,
        install_size,
    }
}

/// What: Fetch metadata for AUR packages by checking local caches.
///
/// Inputs:
/// - `runner`: Command executor.
/// - `name`: Package name.
/// - `version`: Package version (optional, for matching).
///
/// Output:
/// - `OfficialMetadata` with sizes if package file found in cache.
///
/// Details:
/// - Checks pacman cache and AUR helper caches for built package files.
/// - Extracts sizes from found package files.
/// - Returns None values if package file is not found (graceful degradation).
/// - Errors are handled gracefully by returning None values.
pub(super) fn fetch_aur_metadata<R: CommandRunner>(
    runner: &R,
    name: &str,
    version: Option<&str>,
) -> OfficialMetadata {
    find_aur_package_file(name, version).map_or(
        // Package file not found in cache - return None values (graceful degradation)
        OfficialMetadata {
            download_size: None,
            install_size: None,
        },
        |pkg_path| extract_aur_package_sizes(runner, &pkg_path),
    )
}

#[cfg(not(windows))]
#[cfg(test)]
mod tests {
    use super::*;
    use crate::logic::preflight::command::{CommandError, CommandRunner};
    use std::collections::HashMap;
    use std::os::unix::process::ExitStatusExt;
    use std::sync::Mutex;

    type MockCommandKey = (String, Vec<String>);
    type MockCommandResult = Result<String, CommandError>;
    type MockResponseMap = HashMap<MockCommandKey, MockCommandResult>;

    #[derive(Default)]
    struct MockRunner {
        responses: Mutex<MockResponseMap>,
    }

    impl MockRunner {
        fn with(responses: MockResponseMap) -> Self {
            Self {
                responses: Mutex::new(responses),
            }
        }
    }

    impl CommandRunner for MockRunner {
        fn run(&self, program: &str, args: &[&str]) -> Result<String, CommandError> {
            let key = (
                program.to_string(),
                args.iter().map(ToString::to_string).collect::<Vec<_>>(),
            );
            let mut guard = self.responses.lock().expect("poisoned responses mutex");
            guard.remove(&key).unwrap_or_else(|| {
                Err(CommandError::Failed {
                    program: program.to_string(),
                    args: args.iter().map(ToString::to_string).collect(),
                    status: std::process::ExitStatus::from_raw(1),
                })
            })
        }
    }

    #[test]
    /// What: Ensure `parse_size_to_bytes` correctly converts various size formats.
    ///
    /// Inputs:
    /// - Various size strings with different units (B, KiB, MiB, GiB, TiB).
    ///
    /// Output:
    /// - Returns correct byte counts for valid inputs.
    ///
    /// Details:
    /// - Tests edge cases like decimal values and comma separators.
    fn test_parse_size_to_bytes() {
        assert_eq!(parse_size_to_bytes("10 B"), Some(10));
        assert_eq!(parse_size_to_bytes("1 KiB"), Some(1024));
        assert_eq!(parse_size_to_bytes("2.5 MiB"), Some(2_621_440));
        assert_eq!(parse_size_to_bytes("1.5 GiB"), Some(1_610_612_736));
        assert_eq!(parse_size_to_bytes("1,234.5 MiB"), Some(1_294_467_072));
        assert_eq!(parse_size_to_bytes("invalid"), None);
        assert_eq!(parse_size_to_bytes(""), None);
    }

    #[test]
    /// What: Ensure AUR metadata fetching returns None when package file is not found.
    ///
    /// Inputs:
    /// - AUR package name that doesn't exist in any cache.
    ///
    /// Output:
    /// - Returns `Ok(OfficialMetadata)` with `None` values for both sizes.
    ///
    /// Details:
    /// - Tests graceful degradation when package file is not available.
    fn test_fetch_aur_metadata_not_found() {
        let runner = MockRunner::default();
        let meta = fetch_aur_metadata(&runner, "nonexistent-package", Some("1.0.0"));
        assert_eq!(meta.download_size, None);
        assert_eq!(meta.install_size, None);
    }

    #[test]
    /// What: Ensure AUR metadata fetching extracts sizes from package file when found.
    ///
    /// Inputs:
    /// - Mock package file path and `pacman -Qp` output with install size.
    ///
    /// Output:
    /// - Returns `Ok(OfficialMetadata)` with extracted sizes.
    ///
    /// Details:
    /// - Tests size extraction from package metadata via `pacman -Qp`.
    fn test_extract_aur_package_sizes() {
        // Create a temporary file for testing
        let temp_dir = std::env::temp_dir().join(format!("pacsea_test_{}", std::process::id()));
        std::fs::create_dir_all(&temp_dir).expect("failed to create test temp directory");
        let pkg_path = temp_dir.join("test-1.0.0-1-x86_64.pkg.tar.zst");
        std::fs::write(&pkg_path, b"fake package data").expect("failed to write test package file");

        // Set up mock response using the actual temp file path
        let mut responses = HashMap::new();
        responses.insert(
            (
                "pacman".into(),
                vec!["-Qp".into(), pkg_path.to_string_lossy().to_string()],
            ),
            Ok("Name            : test\nInstalled Size  : 5.00 MiB\n".to_string()),
        );

        let runner = MockRunner::with(responses);

        let meta = extract_aur_package_sizes(&runner, &pkg_path);

        // Download size should be the file size (17 bytes in this case)
        assert_eq!(meta.download_size, Some(17));
        // Install size should be parsed from pacman -Qp output
        assert_eq!(meta.install_size, Some(5 * 1024 * 1024));

        // Cleanup
        let _ = std::fs::remove_dir_all(&temp_dir);
    }
}