Skip to main content

pacsea/install/
executor.rs

1//! PTY-based command executor for in-TUI execution.
2
3use crate::state::SecureString;
4use crate::state::{PackageItem, modal::CascadeMode};
5
6/// What: Request types for command execution.
7///
8/// Inputs:
9/// - Various operation types (Install, Remove, etc.) with their parameters.
10///
11/// Output:
12/// - Sent to executor worker to trigger command execution.
13///
14/// Details:
15/// - Each variant contains all necessary information to build and execute the command.
16#[derive(Debug, Clone)]
17pub enum ExecutorRequest {
18    /// Install packages.
19    Install {
20        /// Packages to install.
21        items: Vec<PackageItem>,
22        /// Optional sudo password for official packages.
23        password: Option<SecureString>,
24        /// Whether to run in dry-run mode.
25        dry_run: bool,
26    },
27    /// Remove packages.
28    Remove {
29        /// Package names to remove.
30        names: Vec<String>,
31        /// Optional sudo password.
32        password: Option<SecureString>,
33        /// Cascade removal mode.
34        cascade: CascadeMode,
35        /// Whether to run in dry-run mode.
36        dry_run: bool,
37    },
38    /// Downgrade packages.
39    Downgrade {
40        /// Package names to downgrade.
41        names: Vec<String>,
42        /// Optional sudo password.
43        password: Option<SecureString>,
44        /// Whether to run in dry-run mode.
45        dry_run: bool,
46    },
47    /// Custom command execution (for special cases like paru/yay installation).
48    CustomCommand {
49        /// Command string to execute.
50        command: String,
51        /// Optional sudo password for commands that need sudo (e.g., makepkg -si).
52        password: Option<SecureString>,
53        /// Whether to run in dry-run mode.
54        dry_run: bool,
55    },
56    /// System update (mirrors, pacman, AUR, cache).
57    Update {
58        /// Commands to execute in sequence.
59        commands: Vec<String>,
60        /// Optional sudo password for commands that need sudo.
61        password: Option<SecureString>,
62        /// Whether to run in dry-run mode.
63        dry_run: bool,
64    },
65    /// Security scan for AUR package (excluding aur-sleuth).
66    Scan {
67        /// Package name to scan.
68        package: String,
69        /// Scan configuration flags.
70        do_clamav: bool,
71        /// Trivy scan flag.
72        do_trivy: bool,
73        /// Semgrep scan flag.
74        do_semgrep: bool,
75        /// `ShellCheck` scan flag.
76        do_shellcheck: bool,
77        /// `VirusTotal` scan flag.
78        do_virustotal: bool,
79        /// Custom pattern scan flag.
80        do_custom: bool,
81        /// Whether to run in dry-run mode.
82        dry_run: bool,
83    },
84}
85
86/// What: Output messages from command execution.
87///
88/// Inputs:
89/// - Generated by executor worker during command execution.
90///
91/// Output:
92/// - Sent to main event loop for display in `PreflightExec` modal.
93///
94/// Details:
95/// - Line messages contain output from the `PTY`, Finished indicates completion.
96#[derive(Debug, Clone)]
97pub enum ExecutorOutput {
98    /// Output line from command execution.
99    Line(String),
100    /// Replace the last line (used for progress bars with carriage return).
101    ReplaceLastLine(String),
102    /// Command execution finished.
103    Finished {
104        /// Whether execution succeeded.
105        success: bool,
106        /// Exit code if available.
107        exit_code: Option<i32>,
108        /// Name of the failed command (if execution failed and this is an update operation).
109        failed_command: Option<String>,
110    },
111    /// Error occurred during execution.
112    Error(String),
113}
114
115/// What: Build install command string without hold tail for `PTY` execution.
116///
117/// Inputs:
118/// - `items`: Packages to install.
119/// - `_password`: Optional sudo password (unused - password is written to PTY stdin when sudo prompts).
120/// - `dry_run`: Whether to run in dry-run mode.
121///
122/// Output:
123/// - Command string ready for `PTY` execution (no hold tail).
124///
125/// Details:
126/// - Groups official and `AUR` packages separately; mixed installs run `pacman` then `paru`/`yay` with `--aur` on **AUR-only** names.
127/// - Uses `--noconfirm` for non-interactive execution.
128/// - Always uses `sudo -S` for official packages (password written to PTY stdin when sudo prompts).
129/// - Removes hold tail since we're not spawning a terminal.
130///
131/// # Errors
132///
133/// Returns `Err` when the configured privilege tool cannot be resolved for official package paths.
134pub fn build_install_command_for_executor(
135    items: &[PackageItem],
136    password: Option<&str>,
137    dry_run: bool,
138) -> Result<String, String> {
139    use crate::state::Source;
140
141    let mut official = Vec::new();
142    let mut aur = Vec::new();
143    for item in items {
144        match item.source {
145            Source::Official { .. } => official.push(item.name.clone()),
146            Source::Aur => aur.push(item.name.clone()),
147        }
148    }
149    let installed = crate::logic::deps::get_installed_packages();
150    let provided = crate::logic::deps::get_provided_packages(&installed);
151    let official_reinstall = official.iter().any(|name| {
152        crate::logic::deps::is_package_installed_or_provided(name, &installed, &provided)
153    });
154    let aur_reinstall = aur.iter().any(|name| {
155        crate::logic::deps::is_package_installed_or_provided(name, &installed, &provided)
156    });
157    let (official_plan, aur_plan) = crate::integrations::arch_toolkit::install::batch_install(
158        &official,
159        &aur,
160        official_reinstall,
161        aur_reinstall,
162    )?;
163
164    let official_command = match official_plan {
165        Some(plan) if dry_run => Some(privilege_command(&plan, None)?),
166        Some(plan) => {
167            let sync = privilege_command("pacman -Sy", password)?;
168            let install = privilege_command(&plan, password)?;
169            Some(format!("{sync} && {install}"))
170        }
171        None => None,
172    };
173    let body = match (official_command, aur_plan) {
174        (Some(official), Some(aur)) => format!("{official} && {aur}"),
175        (Some(official), None) => official,
176        (None, Some(aur)) => aur,
177        (None, None) => "echo nothing to install".to_string(),
178    };
179    if dry_run {
180        Ok(format!(
181            "echo DRY RUN: {}",
182            super::utils::shell_single_quote(&body)
183        ))
184    } else {
185        Ok(body)
186    }
187}
188
189/// What: Apply Pacsea privilege and optional password policy to a neutral toolkit command.
190///
191/// Inputs:
192/// - `command`: Neutral shell-safe command body.
193/// - `password`: Optional password used only when the active tool supports stdin authentication.
194///
195/// Output:
196/// - Privilege-wrapped command or an actionable tool-resolution error.
197///
198/// Details:
199/// - arch-toolkit never handles credentials; password ownership and redaction remain in Pacsea.
200fn privilege_command(command: &str, password: Option<&str>) -> Result<String, String> {
201    let tool = crate::logic::privilege::active_tool()?;
202    Ok(password.filter(|value| !value.is_empty()).map_or_else(
203        || crate::logic::privilege::build_privilege_command(tool, command),
204        |value| {
205            crate::logic::privilege::build_password_pipe(tool, value, command)
206                .unwrap_or_else(|| crate::logic::privilege::build_privilege_command(tool, command))
207        },
208    ))
209}
210
211/// What: Build remove command string without hold tail for `PTY` execution.
212///
213/// Inputs:
214/// - `names`: Package names to remove.
215/// - `password`: Optional sudo password (password is written to PTY stdin when sudo prompts).
216/// - `cascade`: Cascade removal mode.
217/// - `dry_run`: Whether to run in dry-run mode.
218///
219/// Output:
220/// - Command string ready for `PTY` execution (no hold tail).
221///
222/// Details:
223/// - Uses `-R`, `-Rs`, or `-Rns` based on cascade mode.
224/// - Uses `--noconfirm` for non-interactive execution.
225/// - Always uses `sudo -S` for remove operations (password written to PTY stdin when sudo prompts).
226/// - Removes hold tail since we're not spawning a terminal.
227///
228/// # Errors
229///
230/// Returns `Err` when the configured privilege tool cannot be resolved.
231pub fn build_remove_command_for_executor(
232    names: &[String],
233    password: Option<&str>,
234    cascade: crate::state::modal::CascadeMode,
235    dry_run: bool,
236) -> Result<String, String> {
237    use super::utils::shell_single_quote;
238
239    if names.is_empty() {
240        return Ok(if dry_run {
241            "echo DRY RUN: nothing to remove".to_string()
242        } else {
243            "echo nothing to remove".to_string()
244        });
245    }
246
247    let base_cmd = crate::integrations::arch_toolkit::install::remove(names, cascade)?;
248    if dry_run {
249        let command = privilege_command(&base_cmd, None)?;
250        Ok(format!("echo DRY RUN: {}", shell_single_quote(&command)))
251    } else {
252        privilege_command(&base_cmd, password)
253    }
254}
255
256/// What: Build downgrade command string without hold tail for `PTY` execution.
257///
258/// Inputs:
259/// - `names`: Package names to downgrade.
260/// - `_password`: Optional password (unused - downgrade runs interactively in PTY).
261/// - `dry_run`: Whether to run in dry-run mode.
262///
263/// Output:
264/// - Command string ready for `PTY` execution (no hold tail).
265///
266/// Details:
267/// - Uses the `downgrade` tool to downgrade packages.
268/// - Checks if `downgrade` tool is available before executing.
269/// - Read-only package checks use `pacman -Qi` without privilege escalation.
270/// - Removes hold tail since we're not spawning a terminal.
271///
272/// # Errors
273///
274/// Returns `Err` when the configured privilege tool cannot be resolved.
275pub fn build_downgrade_command_for_executor(
276    names: &[String],
277    _password: Option<&str>,
278    dry_run: bool,
279) -> Result<String, String> {
280    use super::utils::shell_single_quote;
281    if names.is_empty() {
282        return Ok(if dry_run {
283            "echo DRY RUN: nothing to downgrade".to_string()
284        } else {
285            "echo nothing to downgrade".to_string()
286        });
287    }
288
289    let names_str = names.join(" ");
290
291    let tool = crate::logic::privilege::active_tool()?;
292    let bin = tool.binary_name();
293
294    if dry_run {
295        let cmd = crate::logic::privilege::build_privilege_command(
296            tool,
297            &format!("downgrade {names_str}"),
298        );
299        let quoted = shell_single_quote(&cmd);
300        Ok(format!("echo DRY RUN: {quoted}"))
301    } else {
302        Ok(format!(
303            "if (command -v downgrade >/dev/null 2>&1) || pacman -Qi downgrade >/dev/null 2>&1; then {bin} downgrade {names_str}; else echo 'downgrade tool not found. Install \"downgrade\" package.'; fi"
304        ))
305    }
306}
307
308/// What: Build system update command string by chaining multiple commands.
309///
310/// Inputs:
311/// - `commands`: List of commands to execute in sequence.
312/// - `password`: Optional sudo password for commands that need sudo.
313/// - `dry_run`: Whether to run in dry-run mode.
314///
315/// Output:
316/// - Command string ready for `PTY` execution (commands chained with `&&`).
317///
318/// Details:
319/// - Chains commands with `&&` so execution stops on first failure.
320/// - For commands starting with `sudo`, pipes password if provided.
321/// - In dry-run mode, wraps each command in `echo DRY RUN:`.
322/// - Removes hold tail since we're not spawning a terminal.
323///
324/// # Errors
325///
326/// Returns `Err` when the configured privilege tool cannot be resolved for non-dry-run paths
327/// or credential warm-up.
328pub fn build_update_command_for_executor(
329    commands: &[String],
330    password: Option<&str>,
331    dry_run: bool,
332) -> Result<String, String> {
333    use super::utils::shell_single_quote;
334
335    if commands.is_empty() {
336        return Ok(if dry_run {
337            "echo DRY RUN: nothing to update".to_string()
338        } else {
339            "echo nothing to update".to_string()
340        });
341    }
342
343    let processed_commands: Vec<String> = if dry_run {
344        // Check if we should simulate failure for testing (first command only, if it's pacman)
345        let simulate_failure = std::env::var("PACSEA_TEST_SIMULATE_PACMAN_FAILURE").is_ok()
346            && !commands.is_empty()
347            && commands[0].contains("pacman");
348
349        if simulate_failure {
350            tracing::info!(
351                "[DRY-RUN] Simulating pacman failure for testing - first command will fail with exit code 1"
352            );
353        }
354
355        commands
356            .iter()
357            .enumerate()
358            .map(|(idx, c)| {
359                // Properly quote the command to avoid syntax errors with complex shell constructs
360                let quoted = shell_single_quote(c);
361                if simulate_failure && idx == 0 {
362                    // Simulate pacman failure for testing confirmation popup
363                    // Use false to ensure the command fails with exit code 1
364                    // The && will prevent subsequent commands from running
365                    format!("echo DRY RUN: {quoted} && false")
366                } else {
367                    format!("echo DRY RUN: {quoted}")
368                }
369            })
370            .collect()
371    } else {
372        let tool = crate::logic::privilege::active_tool()?;
373        let prefix = format!("{} ", tool.binary_name());
374        commands
375            .iter()
376            .map(|cmd| {
377                password.map_or_else(
378                    || cmd.clone(),
379                    |pass| {
380                        cmd.strip_prefix(&prefix).map_or_else(
381                            || cmd.clone(),
382                            |base_cmd| {
383                                crate::logic::privilege::build_password_pipe(tool, pass, base_cmd)
384                                    .unwrap_or_else(|| cmd.clone())
385                            },
386                        )
387                    },
388                )
389            })
390            .collect()
391    };
392
393    let joined = processed_commands.join(" && ");
394
395    // Warm up privilege credentials so internal sudo/doas calls don't re-prompt.
396    if let Some(pass) = password {
397        let tool = crate::logic::privilege::active_tool()?;
398        if let Some(warmup) = crate::logic::privilege::build_credential_warmup(tool, pass) {
399            return Ok(format!("{warmup} ; {joined}"));
400        }
401    }
402
403    Ok(joined)
404}
405
406/// What: Build scan command string for `PTY` execution (excluding aur-sleuth).
407///
408/// Inputs:
409/// - `package`: Package name to scan.
410/// - `do_clamav`/`do_trivy`/`do_semgrep`/`do_shellcheck`/`do_virustotal`/`do_custom`: Scan configuration flags.
411/// - `dry_run`: Whether to run in dry-run mode.
412///
413/// Output:
414/// - Command string ready for `PTY` execution (no hold tail, excludes aur-sleuth).
415///
416/// Details:
417/// - Builds scan pipeline commands excluding aur-sleuth (which runs separately in terminal).
418/// - Sets environment variables for scan configuration.
419/// - Removes hold tail since we're not spawning a terminal.
420#[cfg(not(target_os = "windows"))]
421#[must_use]
422#[allow(clippy::fn_params_excessive_bools, clippy::too_many_arguments)]
423pub fn build_scan_command_for_executor(
424    package: &str,
425    do_clamav: bool,
426    do_trivy: bool,
427    do_semgrep: bool,
428    do_shellcheck: bool,
429    do_virustotal: bool,
430    do_custom: bool,
431    dry_run: bool,
432) -> String {
433    use super::utils::shell_single_quote;
434    use crate::install::scan::pkg::build_scan_cmds_for_pkg_without_sleuth;
435
436    // Prepend environment exports so subsequent steps honor the selection
437    let mut cmds: Vec<String> = Vec::new();
438    cmds.push(format!(
439        "export PACSEA_SCAN_DO_CLAMAV={}",
440        if do_clamav { "1" } else { "0" }
441    ));
442    cmds.push(format!(
443        "export PACSEA_SCAN_DO_TRIVY={}",
444        if do_trivy { "1" } else { "0" }
445    ));
446    cmds.push(format!(
447        "export PACSEA_SCAN_DO_SEMGREP={}",
448        if do_semgrep { "1" } else { "0" }
449    ));
450    cmds.push(format!(
451        "export PACSEA_SCAN_DO_SHELLCHECK={}",
452        if do_shellcheck { "1" } else { "0" }
453    ));
454    cmds.push(format!(
455        "export PACSEA_SCAN_DO_VIRUSTOTAL={}",
456        if do_virustotal { "1" } else { "0" }
457    ));
458    cmds.push(format!(
459        "export PACSEA_SCAN_DO_CUSTOM={}",
460        if do_custom { "1" } else { "0" }
461    ));
462    // Export default pattern sets
463    cmds.push("export PACSEA_PATTERNS_CRIT='/dev/(tcp|udp)/|bash -i *>& *[^ ]*/dev/(tcp|udp)/[0-9]+|exec [0-9]{2,}<>/dev/(tcp|udp)/|rm -rf[[:space:]]+/|dd if=/dev/zero of=/dev/sd[a-z]|[>]{1,2}[[:space:]]*/dev/sd[a-z]|: *\\(\\) *\\{ *: *\\| *: *& *\\};:|/etc/sudoers([[:space:]>]|$)|echo .*[>]{2}.*(/etc/sudoers|/root/.ssh/authorized_keys)|/etc/ld\\.so\\.preload|LD_PRELOAD=|authorized_keys.*[>]{2}|ssh-rsa [A-Za-z0-9+/=]+.*[>]{2}.*authorized_keys|curl .*(169\\.254\\.169\\.254)'".to_string());
464    cmds.push("export PACSEA_PATTERNS_HIGH='eval|base64 -d|wget .*(sh|bash|dash|ksh|zsh)([^A-Za-z]|$)|curl .*(sh|bash|dash|ksh|zsh)([^A-Za-z]|$)|sudo[[:space:]]|chattr[[:space:]]|useradd|adduser|groupadd|systemctl|service[[:space:]]|crontab|/etc/cron\\.|[>]{2}.*(\\.bashrc|\\.bash_profile|/etc/profile|\\.zshrc)|cat[[:space:]]+/etc/shadow|cat[[:space:]]+~/.ssh/id_rsa|cat[[:space:]]+~/.bash_history|systemctl stop (auditd|rsyslog)|service (auditd|rsyslog) stop|scp .*@|curl -F|nc[[:space:]].*<|tar -czv?f|zip -r'".to_string());
465    cmds.push("export PACSEA_PATTERNS_MEDIUM='whoami|uname -a|hostname|id|groups|nmap|netstat -anp|ss -anp|ifconfig|ip addr|arp -a|grep -ri .*secret|find .*-name.*(password|\\.key)|env[[:space:]]*\\|[[:space:]]*grep -i pass|wget https?://|curl https?://'".to_string());
466    cmds.push("export PACSEA_PATTERNS_LOW='http_proxy=|https_proxy=|ALL_PROXY=|yes[[:space:]]+> */dev/null *&|ulimit -n [0-9]{5,}'".to_string());
467
468    // Append the scan pipeline commands (excluding sleuth)
469    cmds.extend(build_scan_cmds_for_pkg_without_sleuth(package));
470
471    let full_cmd = cmds.join(" && ");
472
473    if dry_run {
474        let quoted = shell_single_quote(&full_cmd);
475        format!("echo DRY RUN: {quoted}")
476    } else {
477        full_cmd
478    }
479}
480
481#[cfg(test)]
482mod tests {
483    use super::*;
484    use crate::state::Source;
485
486    /// What: Create a test package item with specified source.
487    ///
488    /// Inputs:
489    /// - `name`: Package name
490    /// - `source`: Package source (Official or AUR)
491    ///
492    /// Output:
493    /// - `PackageItem` ready for testing
494    ///
495    /// Details:
496    /// - Helper to create test packages with consistent structure
497    fn create_test_package(name: &str, source: Source) -> PackageItem {
498        PackageItem {
499            name: name.into(),
500            version: "1.0.0".into(),
501            description: String::new(),
502            source,
503            popularity: None,
504            out_of_date: None,
505            orphaned: false,
506        }
507    }
508
509    #[test]
510    /// What: Verify executor command builder creates correct commands without hold tail.
511    ///
512    /// Inputs:
513    /// - Official and AUR packages.
514    /// - Optional password.
515    /// - Dry-run flag.
516    ///
517    /// Output:
518    /// - Commands without hold tail, suitable for PTY execution.
519    ///
520    /// Details:
521    /// - Ensures commands are properly formatted and don't include terminal hold prompts.
522    /// - Uses privilege abstraction so output adapts to active tool (sudo or doas).
523    fn executor_build_install_command_variants() {
524        let tool = crate::logic::privilege::active_tool().expect("privilege tool");
525        let bin = tool.binary_name();
526
527        let official_pkg = create_test_package(
528            "ripgrep",
529            Source::Official {
530                repo: "extra".into(),
531                arch: "x86_64".into(),
532            },
533        );
534
535        let aur_pkg = create_test_package("yay-bin", Source::Aur);
536
537        let installed_set = crate::logic::deps::get_installed_packages();
538        let provided_set = crate::logic::deps::get_provided_packages(&installed_set);
539        let is_installed = crate::logic::deps::is_package_installed_or_provided(
540            "ripgrep",
541            &installed_set,
542            &provided_set,
543        );
544        let cmd1 =
545            build_install_command_for_executor(std::slice::from_ref(&official_pkg), None, false)
546                .expect("build install");
547        if is_installed {
548            assert!(
549                cmd1.contains("pacman -S --noconfirm -- ripgrep"),
550                "expected validated package operand in: {cmd1}"
551            );
552            assert!(!cmd1.contains("--needed"));
553        } else {
554            assert!(
555                cmd1.contains("pacman -S --needed --noconfirm -- ripgrep"),
556                "expected validated package operand in: {cmd1}"
557            );
558        }
559        assert!(!cmd1.contains("Press any key to close"));
560
561        // Official package with password (only works when tool supports stdin password)
562        let cmd2 = build_install_command_for_executor(
563            std::slice::from_ref(&official_pkg),
564            Some("pass"),
565            false,
566        )
567        .expect("build install");
568        if tool.capabilities().supports_stdin_password {
569            assert!(cmd2.contains("printf "), "expected printf in: {cmd2}");
570            if is_installed {
571                assert!(
572                    cmd2.contains("pacman -S --noconfirm -- ripgrep"),
573                    "expected validated package operand in password command: {cmd2}"
574                );
575            } else {
576                assert!(
577                    cmd2.contains("pacman -S --needed --noconfirm -- ripgrep"),
578                    "expected validated package operand in password command: {cmd2}"
579                );
580            }
581        } else {
582            assert!(
583                cmd2.contains(&format!("{bin} pacman")),
584                "doas fallback should use plain command: {cmd2}"
585            );
586        }
587
588        // AUR package
589        let cmd3 = build_install_command_for_executor(std::slice::from_ref(&aur_pkg), None, false)
590            .expect("build install");
591        assert!(cmd3.contains("command -v paru"));
592        assert!(cmd3.contains("paru -S --aur"));
593        assert!(!cmd3.contains("Press any key to close"));
594
595        // Dry run
596        let cmd4 =
597            build_install_command_for_executor(&[official_pkg], None, true).expect("build install");
598        assert!(cmd4.starts_with("echo DRY RUN:"));
599    }
600
601    #[test]
602    /// What: Verify command builder handles mixed official and AUR packages.
603    ///
604    /// Inputs:
605    /// - Mixed list of official and AUR packages.
606    ///
607    /// Output:
608    /// - Command that installs all packages using appropriate tool.
609    ///
610    /// Details:
611    /// - Official names go through `pacman`; AUR names use `paru`/`yay` with `--aur` only on the AUR target list.
612    fn executor_build_mixed_packages() {
613        let tool = crate::logic::privilege::active_tool().expect("privilege tool");
614        let bin = tool.binary_name();
615
616        let official_pkg = create_test_package(
617            "ripgrep",
618            Source::Official {
619                repo: "extra".into(),
620                arch: "x86_64".into(),
621            },
622        );
623        let aur_pkg = create_test_package("yay-bin", Source::Aur);
624
625        let cmd = build_install_command_for_executor(&[official_pkg, aur_pkg], None, false)
626            .expect("build install");
627        assert!(
628            cmd.contains(&format!("{bin} pacman")),
629            "expected privileged pacman in mixed install: {cmd}"
630        );
631        assert!(
632            cmd.contains("ripgrep"),
633            "expected official pkg in cmd: {cmd}"
634        );
635        assert!(
636            cmd.contains("paru -S --aur") || cmd.contains("yay -S --aur"),
637            "expected helper --aur for AUR targets: {cmd}"
638        );
639        assert!(
640            cmd.contains("yay-bin"),
641            "expected AUR pkg name in helper invocation: {cmd}"
642        );
643    }
644
645    #[test]
646    /// What: Verify command builder handles empty package list.
647    ///
648    /// Inputs:
649    /// - Empty package list.
650    ///
651    /// Output:
652    /// - Command that indicates nothing to install.
653    ///
654    /// Details:
655    /// - Empty list should produce a safe no-op command.
656    fn executor_build_empty_list() {
657        let cmd = build_install_command_for_executor(&[], None, false).expect("build install");
658        assert!(cmd.contains("nothing to install") || cmd.is_empty());
659    }
660
661    #[test]
662    /// What: Verify command builder handles multiple official packages.
663    ///
664    /// Inputs:
665    /// - Multiple official packages.
666    ///
667    /// Output:
668    /// - Command that installs all packages via pacman.
669    ///
670    /// Details:
671    /// - Multiple packages should be space-separated in the command.
672    fn executor_build_multiple_official() {
673        let pkg1 = create_test_package(
674            "ripgrep",
675            Source::Official {
676                repo: "extra".into(),
677                arch: "x86_64".into(),
678            },
679        );
680        let pkg2 = create_test_package(
681            "fd",
682            Source::Official {
683                repo: "extra".into(),
684                arch: "x86_64".into(),
685            },
686        );
687
688        let installed_set = crate::logic::deps::get_installed_packages();
689        let provided_set = crate::logic::deps::get_provided_packages(&installed_set);
690        let ripgrep_installed = crate::logic::deps::is_package_installed_or_provided(
691            "ripgrep",
692            &installed_set,
693            &provided_set,
694        );
695        let fd_installed = crate::logic::deps::is_package_installed_or_provided(
696            "fd",
697            &installed_set,
698            &provided_set,
699        );
700        let has_reinstall = ripgrep_installed || fd_installed;
701
702        let cmd =
703            build_install_command_for_executor(&[pkg1, pkg2], None, false).expect("build install");
704        assert!(cmd.contains("ripgrep"));
705        assert!(cmd.contains("fd"));
706        let bin = crate::logic::privilege::active_tool()
707            .expect("privilege tool")
708            .binary_name();
709        if has_reinstall {
710            assert!(
711                cmd.contains(&format!("{bin} pacman -S --noconfirm")),
712                "expected '{bin} pacman -S --noconfirm' in: {cmd}"
713            );
714            assert!(!cmd.contains("--needed"));
715        } else {
716            assert!(
717                cmd.contains(&format!("{bin} pacman -S --needed --noconfirm")),
718                "expected '{bin} pacman -S --needed --noconfirm' in: {cmd}"
719            );
720        }
721    }
722
723    #[test]
724    /// What: Verify dry-run mode produces echo commands.
725    ///
726    /// Inputs:
727    /// - Package list with `dry_run=true`.
728    ///
729    /// Output:
730    /// - Command that starts with "echo DRY RUN:".
731    ///
732    /// Details:
733    /// - Dry-run should never execute actual install commands.
734    fn executor_build_dry_run() {
735        let pkg = create_test_package(
736            "ripgrep",
737            Source::Official {
738                repo: "extra".into(),
739                arch: "x86_64".into(),
740            },
741        );
742
743        let cmd = build_install_command_for_executor(&[pkg], None, true).expect("build install");
744        assert!(cmd.starts_with("echo DRY RUN:"));
745        // In dry-run mode, the command is wrapped in echo, so it may contain the original command text
746        // The important thing is that it starts with "echo DRY RUN:" which prevents execution
747    }
748
749    #[test]
750    /// What: Verify password is properly escaped in command.
751    ///
752    /// Inputs:
753    /// - Official package with password containing special characters.
754    ///
755    /// Output:
756    /// - Command with properly escaped password.
757    ///
758    /// Details:
759    /// - Password should be single-quoted to prevent shell injection.
760    fn executor_build_password_escaping() {
761        let tool = crate::logic::privilege::active_tool().expect("privilege tool");
762        let pkg = create_test_package(
763            "ripgrep",
764            Source::Official {
765                repo: "extra".into(),
766                arch: "x86_64".into(),
767            },
768        );
769
770        let password = "pass'word\"with$special";
771        let cmd = build_install_command_for_executor(&[pkg], Some(password), false)
772            .expect("build install");
773        if tool.capabilities().supports_stdin_password {
774            assert!(cmd.contains("printf"), "expected printf in: {cmd}");
775            assert!(
776                cmd.contains(&format!("{} -S", tool.binary_name())),
777                "expected '{} -S' in: {cmd}",
778                tool.binary_name()
779            );
780            // Password should be quoted/escaped when injected into a shell command.
781            assert!(
782                cmd.contains('\'') || cmd.contains('"'),
783                "password must be shell-escaped in: {cmd}"
784            );
785        } else {
786            // Tools without stdin password support (e.g. doas) must never embed the password.
787            assert!(
788                !cmd.contains(password),
789                "password must not be embedded for non-stdin tools: {cmd}"
790            );
791        }
792    }
793
794    #[test]
795    /// What: Verify remove command builder creates correct commands without hold tail.
796    ///
797    /// Inputs:
798    /// - Package names, cascade mode, optional password, dry-run flag.
799    ///
800    /// Output:
801    /// - Commands without hold tail, suitable for PTY execution.
802    ///
803    /// Details:
804    /// - Ensures commands are properly formatted and don't include terminal hold prompts.
805    fn executor_build_remove_command_variants() {
806        use crate::state::modal::CascadeMode;
807
808        let tool = crate::logic::privilege::active_tool().expect("privilege tool");
809        let bin = tool.binary_name();
810        let names = vec!["test-pkg1".to_string(), "test-pkg2".to_string()];
811
812        // Basic mode without password
813        let cmd1 = build_remove_command_for_executor(&names, None, CascadeMode::Basic, false)
814            .expect("build remove");
815        assert!(
816            cmd1.contains(&format!("{bin} pacman -R --noconfirm")),
817            "expected '{bin} pacman -R --noconfirm' in: {cmd1}"
818        );
819        assert!(cmd1.contains("test-pkg1"));
820        assert!(cmd1.contains("test-pkg2"));
821        assert!(!cmd1.contains("Press any key to close"));
822
823        // Cascade mode with password
824        let cmd2 =
825            build_remove_command_for_executor(&names, Some("pass"), CascadeMode::Cascade, false)
826                .expect("build remove");
827        if tool.capabilities().supports_stdin_password {
828            assert!(cmd2.contains("printf "), "expected printf in: {cmd2}");
829            assert!(
830                cmd2.contains(&format!("{bin} -S pacman -Rs --noconfirm")),
831                "expected '{bin} -S pacman -Rs --noconfirm' in: {cmd2}"
832            );
833        } else {
834            assert!(
835                cmd2.contains(&format!("{bin} pacman -Rs --noconfirm")),
836                "expected '{bin} pacman -Rs --noconfirm' in: {cmd2}"
837            );
838        }
839
840        // CascadeWithConfigs mode
841        let cmd3 =
842            build_remove_command_for_executor(&names, None, CascadeMode::CascadeWithConfigs, false)
843                .expect("build remove");
844        assert!(
845            cmd3.contains(&format!("{bin} pacman -Rns --noconfirm")),
846            "expected '{bin} pacman -Rns --noconfirm' in: {cmd3}"
847        );
848
849        // Dry run
850        let cmd4 = build_remove_command_for_executor(&names, None, CascadeMode::Basic, true)
851            .expect("build remove");
852        assert!(cmd4.starts_with("echo DRY RUN:"));
853        assert!(cmd4.contains("pacman -R --noconfirm"));
854
855        // Empty list
856        let cmd5 = build_remove_command_for_executor(&[], None, CascadeMode::Basic, false)
857            .expect("build remove");
858        assert_eq!(cmd5, "echo nothing to remove");
859    }
860
861    #[test]
862    /// What: Verify downgrade executor command uses tool-aware execution and unprivileged package check.
863    ///
864    /// Inputs:
865    /// - Non-empty package names list.
866    /// - Dry-run and non-dry-run modes.
867    ///
868    /// Output:
869    /// - Dry-run command prefixed with `echo DRY RUN:`.
870    /// - Live command that checks `downgrade` availability and runs `<tool> downgrade ...`.
871    ///
872    /// Details:
873    /// - `pacman -Qi downgrade` must remain unprivileged because it is read-only.
874    fn executor_build_downgrade_command_uses_unprivileged_qi_check() {
875        let names = vec!["linux".to_string(), "linux-headers".to_string()];
876        let tool = crate::logic::privilege::active_tool().expect("privilege tool");
877        let bin = tool.binary_name();
878
879        let live =
880            build_downgrade_command_for_executor(&names, None, false).expect("build downgrade");
881        assert!(
882            live.contains("pacman -Qi downgrade"),
883            "expected unprivileged pacman -Qi check in: {live}"
884        );
885        assert!(
886            live.contains(&format!("{bin} downgrade linux linux-headers")),
887            "expected tool-aware downgrade command in: {live}"
888        );
889
890        let dry =
891            build_downgrade_command_for_executor(&names, None, true).expect("build downgrade");
892        assert!(dry.starts_with("echo DRY RUN:"));
893        assert!(dry.contains(&format!("{bin} downgrade linux linux-headers")));
894    }
895}