Skip to main content

pacsea/install/
command.rs

1//! Builds terminal shell commands from neutral arch-toolkit install plans.
2
3use crate::state::{PackageItem, Source};
4
5use super::utils::shell_single_quote;
6
7/// Terminal tail appended after one install plan finishes.
8const HOLD_TAIL: &str = "; echo; echo 'Finished.'; echo 'Press any key to close...'; read -rn1 -s _ || (echo; echo 'Press Ctrl+C to close'; sleep infinity)";
9
10/// What: Build a shell command to install one package from a neutral toolkit plan.
11///
12/// Inputs:
13/// - `item`: Package to install.
14/// - `password`: Optional privilege password for Pacsea's existing sudo session policy.
15/// - `dry_run`: Whether to display rather than execute the plan.
16///
17/// Output:
18/// - Shell command and whether the operation uses a privilege tool.
19///
20/// # Errors
21///
22/// Returns an actionable error when package validation, toolkit planning, or privilege resolution
23/// fails.
24///
25/// Details:
26/// - arch-toolkit validates operands and inserts `--`; Pacsea retains privilege/password, dry-run,
27///   PTY, hold-tail, and execution ownership. AUR helpers are never privilege-wrapped.
28pub fn build_install_command(
29    item: &PackageItem,
30    password: Option<&str>,
31    dry_run: bool,
32) -> Result<(String, bool), String> {
33    let reinstall = crate::index::is_installed(&item.name);
34    let neutral = crate::integrations::arch_toolkit::install::single_install(item, reinstall)?;
35    match item.source {
36        Source::Official { .. } => {
37            let tool = crate::logic::privilege::active_tool()?;
38            let privileged = password.filter(|value| !value.is_empty()).map_or_else(
39                || crate::logic::privilege::build_privilege_command(tool, &neutral),
40                |value| {
41                    crate::logic::privilege::build_password_pipe(tool, value, &neutral)
42                        .unwrap_or_else(|| {
43                            crate::logic::privilege::build_privilege_command(tool, &neutral)
44                        })
45                },
46            );
47            Ok((render_terminal_command(&privileged, dry_run), true))
48        }
49        Source::Aur => Ok((render_terminal_command(&neutral, dry_run), false)),
50    }
51}
52
53/// What: Add dry-run presentation and the external-terminal hold tail.
54///
55/// Inputs:
56/// - `command`: Shell-safe neutral or privilege-wrapped command.
57/// - `dry_run`: Whether to echo rather than execute it.
58///
59/// Output:
60/// - Final shell string for Pacsea's terminal launcher.
61///
62/// Details:
63/// - Dry-run quotes the complete command as one display operand and never executes it.
64fn render_terminal_command(command: &str, dry_run: bool) -> String {
65    let with_hold = format!("{command}{HOLD_TAIL}");
66    if dry_run {
67        format!("echo DRY RUN: {}", shell_single_quote(&with_hold))
68    } else {
69        with_hold
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use super::build_install_command;
76    use crate::state::{PackageItem, Source};
77
78    /// What: Verify official toolkit plans retain Pacsea privilege and dry-run policy.
79    ///
80    /// Inputs:
81    /// - One official package in normal and dry-run modes.
82    ///
83    /// Output:
84    /// - Privileged pacman command with operand terminator and nonexecuting dry-run display.
85    ///
86    /// Details:
87    /// - The command is built only and never spawned.
88    #[test]
89    fn official_install_uses_toolkit_plan() {
90        let tool = crate::logic::privilege::active_tool().expect("privilege tool should exist");
91        let item = package(Source::Official {
92            repo: "extra".to_string(),
93            arch: "x86_64".to_string(),
94        });
95        let (command, privileged) =
96            build_install_command(&item, None, false).expect("plan should build");
97        assert!(privileged);
98        assert!(command.contains(&format!(
99            "{} pacman -S --needed --noconfirm -- ripgrep",
100            tool.binary_name()
101        )));
102        assert!(command.contains("Press any key to close"));
103
104        let (dry_run, _) =
105            build_install_command(&item, None, true).expect("dry-run plan should build");
106        assert!(dry_run.starts_with("echo DRY RUN: '"));
107        assert!(dry_run.contains("pacman -S --needed --noconfirm -- ripgrep"));
108    }
109
110    /// What: Verify AUR toolkit planning remains unprivileged and fails when no helper exists.
111    ///
112    /// Inputs:
113    /// - One AUR package.
114    ///
115    /// Output:
116    /// - paru/yay fallback with `--aur`, operand terminator, and status-127 branch.
117    ///
118    /// Details:
119    /// - The helper is selected only when the shell body later executes.
120    #[test]
121    fn aur_install_uses_unprivileged_toolkit_fallback() {
122        let item = package(Source::Aur);
123        let (command, privileged) =
124            build_install_command(&item, None, false).expect("plan should build");
125        assert!(!privileged);
126        assert!(command.contains("paru -S --aur --needed --noconfirm -- ripgrep"));
127        assert!(command.contains("yay -S --aur --needed --noconfirm -- ripgrep"));
128        assert!(command.contains("exit 127"));
129    }
130
131    /// What: Create a deterministic package fixture.
132    ///
133    /// Inputs:
134    /// - `source`: Desired package source.
135    ///
136    /// Output:
137    /// - Pacsea package row named `ripgrep`.
138    ///
139    /// Details:
140    /// - No host package metadata is read while constructing the fixture.
141    fn package(source: Source) -> PackageItem {
142        PackageItem {
143            name: "ripgrep".to_string(),
144            version: String::new(),
145            description: String::new(),
146            source,
147            popularity: None,
148            out_of_date: None,
149            orphaned: false,
150        }
151    }
152}