pacsea/util/
pacman.rs

1//! Pacman command execution utilities.
2//!
3//! This module provides functions for executing pacman commands and handling
4//! common error cases.
5use std::process::Command;
6use tracing::{debug, warn};
7
8/// Result type alias for pacman command operations.
9type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
10
11/// What: Execute `pacman` with the provided arguments and capture stdout.
12///
13/// Inputs:
14/// - `args`: Slice of CLI arguments passed directly to the pacman binary.
15///
16/// Output:
17/// - Returns the command's stdout as a UTF-8 string or propagates execution/parsing errors.
18///
19/// # Errors
20/// - Returns `Err` when `pacman` command execution fails (I/O error or pacman not found)
21/// - Returns `Err` when `pacman` exits with non-zero status
22/// - Returns `Err` when stdout cannot be decoded as UTF-8
23///
24/// Details:
25/// - Used internally by index and logic helpers to keep command invocation boilerplate centralized.
26pub fn run_pacman(args: &[&str]) -> Result<String> {
27    debug!(command = "pacman", args = ?args, "executing pacman command");
28
29    let out = match Command::new("pacman").args(args).output() {
30        Ok(output) => output,
31        Err(err) => {
32            warn!(command = "pacman", args = ?args, error = %err, "failed to spawn pacman");
33            return Err(err.into());
34        }
35    };
36
37    let status_code = out.status.code();
38    let stdout_len = out.stdout.len();
39    let stderr_len = out.stderr.len();
40
41    if !out.status.success() {
42        warn!(
43            command = "pacman",
44            args = ?args,
45            status = ?out.status,
46            status_code,
47            stdout_len,
48            stderr_len,
49            "pacman exited with non-zero status"
50        );
51        return Err(format!("pacman {:?} exited with {:?}", args, out.status).into());
52    }
53
54    debug!(
55        command = "pacman",
56        args = ?args,
57        status = ?out.status,
58        status_code,
59        stdout_len,
60        stderr_len,
61        "pacman command completed successfully"
62    );
63
64    Ok(String::from_utf8(out.stdout)?)
65}