Skip to main content

pacsea/install/
batch.rs

1#[cfg(not(target_os = "windows"))]
2use crate::state::Source;
3#[allow(unused_imports)]
4use std::process::Command;
5
6use crate::state::PackageItem;
7
8#[cfg(not(target_os = "windows"))]
9use super::logging::log_installed;
10#[cfg(not(target_os = "windows"))]
11use super::utils::{choose_terminal_index_prefer_path, command_on_path, shell_single_quote};
12
13#[cfg(not(target_os = "windows"))]
14/// What: Build the shell command string for batch package installation.
15///
16/// Input:
17/// - `items`: Packages to install
18/// - `official`: Names of official packages
19/// - `aur`: Names of AUR packages
20/// - `dry_run`: When `true`, prints commands instead of executing
21///
22/// Output:
23/// - `Ok(shell command string)` with hold tail appended
24///
25/// # Errors
26///
27/// Returns `Err` when the configured privilege tool cannot be resolved for official paths.
28///
29/// Details:
30/// - Official packages are grouped into a single `pacman` invocation
31/// - AUR packages are installed via `paru`/`yay` with `--aur` on **AUR-only** targets (mixed installs chain `pacman` then the helper)
32/// - Appends a "hold" tail so the terminal remains open after command completion
33fn build_batch_install_command(
34    items: &[PackageItem],
35    official: &[String],
36    aur: &[String],
37    dry_run: bool,
38) -> Result<String, String> {
39    let hold_tail = "; echo; echo 'Finished.'; echo 'Press any key to close...'; read -rn1 -s _ || (echo; echo 'Press Ctrl+C to close'; sleep infinity)";
40    let installed = crate::logic::deps::get_installed_packages();
41    let provided = crate::logic::deps::get_provided_packages(&installed);
42    let official_reinstall = official.iter().any(|name| {
43        crate::logic::deps::is_package_installed_or_provided(name, &installed, &provided)
44    });
45    let aur_reinstall = aur.iter().any(|name| {
46        crate::logic::deps::is_package_installed_or_provided(name, &installed, &provided)
47    });
48    let (official_plan, aur_plan) = crate::integrations::arch_toolkit::install::batch_install(
49        official,
50        aur,
51        official_reinstall,
52        aur_reinstall,
53    )?;
54
55    let official_command = if let Some(plan) = official_plan {
56        let tool = crate::logic::privilege::active_tool()?;
57        let has_versioned_reinstall = items.iter().any(|item| {
58            matches!(item.source, Source::Official { .. })
59                && !item.version.is_empty()
60                && crate::index::is_installed(&item.name)
61        });
62        if has_versioned_reinstall && !dry_run {
63            let sync = force_sync_before_install(&plan);
64            Some(format!(
65                "{} bash -c {}",
66                tool.binary_name(),
67                shell_single_quote(&sync)
68            ))
69        } else {
70            Some(crate::logic::privilege::build_privilege_command(
71                tool, &plan,
72            ))
73        }
74    } else {
75        None
76    };
77
78    let body = match (official_command, aur_plan) {
79        (Some(official), Some(aur)) => format!("{official} && {aur}"),
80        (Some(official), None) => official,
81        (None, Some(aur)) => aur,
82        (None, None) => "echo nothing to install".to_string(),
83    };
84    let with_hold = format!("{body}{hold_tail}");
85    if dry_run {
86        Ok(format!("echo DRY RUN: {}", shell_single_quote(&with_hold)))
87    } else {
88        Ok(with_hold)
89    }
90}
91
92#[cfg(not(target_os = "windows"))]
93/// What: Prepend a forced database refresh to a validated toolkit install plan.
94///
95/// Inputs:
96/// - `plan`: Shell-safe install plan produced by arch-toolkit.
97///
98/// Output:
99/// - Chained refresh and install command body.
100///
101/// Details:
102/// - Reuses the validated plan verbatim instead of reconstructing package operands.
103fn force_sync_before_install(plan: &str) -> String {
104    format!("pacman -Sy --noconfirm && {plan}")
105}
106
107#[cfg(not(target_os = "windows"))]
108/// What: Attempt to spawn a terminal with the given command string.
109///
110/// Input:
111/// - `term`: Terminal executable name
112/// - `args`: Arguments for the terminal
113/// - `needs_xfce_command`: Whether this terminal needs special xfce4-terminal command handling
114/// - `cmd_str`: Command string to execute in the terminal
115///
116/// Output:
117/// - `Ok(())` if the terminal was successfully spawned, `Err(())` otherwise
118///
119/// Details:
120/// - Handles special cases for `konsole` (`Wayland`), `gnome-console`/`kgx` (rendering), and `xfce4-terminal` (command format)
121/// - Sets up `PACSEA_TEST_OUT` environment variable if present
122fn try_spawn_terminal(
123    term: &str,
124    args: &[&str],
125    needs_xfce_command: bool,
126    cmd_str: &str,
127) -> Result<(), ()> {
128    let mut cmd = Command::new(term);
129    if needs_xfce_command && term == "xfce4-terminal" {
130        let quoted = shell_single_quote(cmd_str);
131        cmd.arg("--command").arg(format!("bash -lc {quoted}"));
132    } else {
133        cmd.args(args.iter().copied()).arg(cmd_str);
134    }
135    if let Ok(p) = std::env::var("PACSEA_TEST_OUT") {
136        if let Some(parent) = std::path::Path::new(&p).parent() {
137            let _ = std::fs::create_dir_all(parent);
138        }
139        cmd.env("PACSEA_TEST_OUT", p);
140    }
141    if term == "konsole" && std::env::var_os("WAYLAND_DISPLAY").is_some() {
142        cmd.env("QT_LOGGING_RULES", "qt.qpa.wayland.textinput=false");
143    }
144    if term == "gnome-console" || term == "kgx" {
145        cmd.env("GSK_RENDERER", "cairo");
146        cmd.env("LIBGL_ALWAYS_SOFTWARE", "1");
147    }
148    cmd.spawn().map(|_| ()).map_err(|_| ())
149}
150
151#[cfg(not(target_os = "windows"))]
152/// What: Spawn a terminal to install a batch of packages.
153///
154/// Input:
155/// - `items`: Packages to install
156/// - `dry_run`: When `true`, prints commands instead of executing
157///
158/// Output:
159/// - Launches a terminal (or falls back to `bash`) running the composed install commands.
160///
161/// Details:
162/// - Official packages are grouped into a single `pacman` invocation
163/// - AUR packages are installed via `paru`/`yay` (prompts to install a helper if missing)
164/// - Prefers common terminals (GNOME Console/Terminal, kitty, alacritty, xterm, xfce4-terminal, etc.); falls back to `bash`
165/// - Appends a "hold" tail so the terminal remains open after command completion
166/// - During tests, this is a no-op to avoid opening real terminal windows.
167pub fn spawn_install_all(items: &[PackageItem], dry_run: bool) {
168    // Skip actual spawning during tests unless PACSEA_TEST_OUT is set (indicates a test with fake terminal)
169    #[cfg(test)]
170    if std::env::var("PACSEA_TEST_OUT").is_err() {
171        return;
172    }
173
174    let mut official: Vec<String> = Vec::new();
175    let mut aur: Vec<String> = Vec::new();
176    for it in items {
177        match it.source {
178            Source::Official { .. } => official.push(it.name.clone()),
179            Source::Aur => aur.push(it.name.clone()),
180        }
181    }
182    let names_vec: Vec<String> = items.iter().map(|p| p.name.clone()).collect();
183    tracing::info!(
184        total = items.len(),
185        aur_count = aur.len(),
186        official_count = official.len(),
187        dry_run = dry_run,
188        names = %names_vec.join(" "),
189        "spawning install"
190    );
191
192    let cmd_str = match build_batch_install_command(items, &official, &aur, dry_run) {
193        Ok(s) => s,
194        Err(err) => {
195            tracing::error!(error = %err, "privilege tool resolution failed for batch install");
196            return;
197        }
198    };
199
200    // Prefer GNOME Terminal when running under GNOME desktop
201    let is_gnome =
202        std::env::var("XDG_CURRENT_DESKTOP").is_ok_and(|v| v.to_uppercase().contains("GNOME"));
203    let terms_gnome_first: &[(&str, &[&str], bool)] = &[
204        ("gnome-terminal", &["--", "bash", "-lc"], false),
205        ("gnome-console", &["--", "bash", "-lc"], false),
206        ("kgx", &["--", "bash", "-lc"], false),
207        ("alacritty", &["-e", "bash", "-lc"], false),
208        ("kitty", &["bash", "-lc"], false),
209        ("konsole", &["-e", "bash", "-lc"], false),
210        ("xterm", &["-hold", "-e", "bash", "-lc"], false),
211        ("xfce4-terminal", &[], true),
212        ("tilix", &["--", "bash", "-lc"], false),
213        ("mate-terminal", &["--", "bash", "-lc"], false),
214    ];
215    let terms_default: &[(&str, &[&str], bool)] = &[
216        ("alacritty", &["-e", "bash", "-lc"], false),
217        ("kitty", &["bash", "-lc"], false),
218        ("konsole", &["-e", "bash", "-lc"], false),
219        ("gnome-terminal", &["--", "bash", "-lc"], false),
220        ("gnome-console", &["--", "bash", "-lc"], false),
221        ("kgx", &["--", "bash", "-lc"], false),
222        ("xterm", &["-hold", "-e", "bash", "-lc"], false),
223        ("xfce4-terminal", &[], true),
224        ("tilix", &["--", "bash", "-lc"], false),
225        ("mate-terminal", &["--", "bash", "-lc"], false),
226    ];
227    let terms = if is_gnome {
228        terms_gnome_first
229    } else {
230        terms_default
231    };
232    let mut launched = false;
233    if let Some(idx) = choose_terminal_index_prefer_path(terms) {
234        let (term, args, needs_xfce_command) = terms[idx];
235        match try_spawn_terminal(term, args, needs_xfce_command, &cmd_str) {
236            Ok(()) => {
237                tracing::info!(terminal = %term, total = items.len(), aur_count = aur.len(), official_count = official.len(), dry_run = dry_run, names = %names_vec.join(" "), "launched terminal for install");
238                launched = true;
239            }
240            Err(()) => {
241                tracing::warn!(terminal = %term, names = %names_vec.join(" "), "failed to spawn terminal, trying next");
242            }
243        }
244    }
245
246    if !launched {
247        for (term, args, needs_xfce_command) in terms {
248            if command_on_path(term) {
249                match try_spawn_terminal(term, args, *needs_xfce_command, &cmd_str) {
250                    Ok(()) => {
251                        tracing::info!(terminal = %term, total = items.len(), aur_count = aur.len(), official_count = official.len(), dry_run = dry_run, names = %names_vec.join(" "), "launched terminal for install");
252                        launched = true;
253                        break;
254                    }
255                    Err(()) => {
256                        tracing::warn!(terminal = %term, names = %names_vec.join(" "), "failed to spawn terminal, trying next");
257                    }
258                }
259            }
260        }
261    }
262    if !launched {
263        let res = Command::new("bash").args(["-lc", &cmd_str]).spawn();
264        if let Err(e) = res {
265            tracing::error!(error = %e, names = %names_vec.join(" "), "failed to spawn bash to run install command");
266        } else {
267            tracing::info!(total = items.len(), aur_count = aur.len(), official_count = official.len(), dry_run = dry_run, names = %names_vec.join(" "), "launched bash for install");
268        }
269    }
270
271    if !dry_run {
272        let names: Vec<String> = items.iter().map(|p| p.name.clone()).collect();
273        if !names.is_empty()
274            && let Err(e) = log_installed(&names)
275        {
276            tracing::warn!(error = %e, count = names.len(), "failed to write install audit log");
277        }
278    }
279}
280
281#[cfg(all(test, not(target_os = "windows")))]
282mod tests {
283    #[test]
284    /// What: Verify forced refresh composition preserves the validated toolkit plan verbatim.
285    ///
286    /// Inputs:
287    /// - A toolkit-style pacman install plan with an operand terminator.
288    ///
289    /// Output:
290    /// - Refresh command chained to the unchanged install plan.
291    ///
292    /// Details:
293    /// - Prevents regression to rebuilding shell operands from raw package names.
294    fn forced_sync_reuses_validated_install_plan() {
295        let plan = "pacman -S --noconfirm -- ripgrep fd";
296        assert_eq!(
297            super::force_sync_before_install(plan),
298            "pacman -Sy --noconfirm && pacman -S --noconfirm -- ripgrep fd"
299        );
300    }
301
302    #[test]
303    /// What: Confirm batch installs launch gnome-terminal with the expected separator arguments.
304    ///
305    /// Inputs:
306    /// - Shim `gnome-terminal` scripted to capture argv via `PACSEA_TEST_OUT`.
307    /// - `spawn_install_all` invoked with two official packages in dry-run mode.
308    ///
309    /// Output:
310    /// - Captured argument list starts with `--`, `bash`, `-lc`, validating safe command invocation.
311    ///
312    /// Details:
313    /// - Overrides `PATH` and environment variables, then restores them to avoid leaking state across tests.
314    fn install_batch_uses_gnome_terminal_double_dash() {
315        use std::fs;
316        use std::os::unix::fs::PermissionsExt;
317        use std::path::PathBuf;
318
319        let mut dir: PathBuf = std::env::temp_dir();
320        dir.push(format!(
321            "pacsea_test_inst_batch_gnome_{}_{}",
322            std::process::id(),
323            std::time::SystemTime::now()
324                .duration_since(std::time::UNIX_EPOCH)
325                .expect("System time is before UNIX epoch")
326                .as_nanos()
327        ));
328        let _ = fs::create_dir_all(&dir);
329        let mut out_path = dir.clone();
330        out_path.push("args.txt");
331        let mut term_path = dir.clone();
332        term_path.push("gnome-terminal");
333        let script = "#!/bin/sh\n: > \"$PACSEA_TEST_OUT\"\nfor a in \"$@\"; do printf '%s\n' \"$a\" >> \"$PACSEA_TEST_OUT\"; done\n";
334        fs::write(&term_path, script.as_bytes()).expect("Failed to write test terminal script");
335        let mut perms = fs::metadata(&term_path)
336            .expect("Failed to read test terminal script metadata")
337            .permissions();
338        perms.set_mode(0o755);
339        fs::set_permissions(&term_path, perms)
340            .expect("Failed to set test terminal script permissions");
341
342        let orig_path = std::env::var_os("PATH");
343        unsafe {
344            std::env::set_var("PATH", dir.display().to_string());
345            std::env::set_var("PACSEA_TEST_OUT", out_path.display().to_string());
346        }
347
348        let items = vec![
349            crate::state::PackageItem {
350                name: "rg".into(),
351                version: "1".into(),
352                description: String::new(),
353                source: crate::state::Source::Official {
354                    repo: "extra".into(),
355                    arch: "x86_64".into(),
356                },
357                popularity: None,
358                out_of_date: None,
359                orphaned: false,
360            },
361            crate::state::PackageItem {
362                name: "fd".into(),
363                version: "1".into(),
364                description: String::new(),
365                source: crate::state::Source::Official {
366                    repo: "extra".into(),
367                    arch: "x86_64".into(),
368                },
369                popularity: None,
370                out_of_date: None,
371                orphaned: false,
372            },
373        ];
374        super::spawn_install_all(&items, true);
375        std::thread::sleep(std::time::Duration::from_millis(50));
376
377        let body = fs::read_to_string(&out_path).expect("fake terminal args file written");
378        let lines: Vec<&str> = body.lines().collect();
379        assert!(lines.len() >= 3, "expected at least 3 args, got: {body}");
380        assert_eq!(lines[0], "--");
381        assert_eq!(lines[1], "bash");
382        assert_eq!(lines[2], "-lc");
383
384        unsafe {
385            if let Some(v) = orig_path {
386                std::env::set_var("PATH", v);
387            } else {
388                std::env::remove_var("PATH");
389            }
390            std::env::remove_var("PACSEA_TEST_OUT");
391        }
392    }
393}
394
395#[cfg(target_os = "windows")]
396/// What: Present an informational install message on Windows where package management is unsupported.
397///
398/// Input:
399/// - `items`: Packages the user attempted to install.
400/// - `dry_run`: When `true`, uses `PowerShell` to simulate the install operation.
401///
402/// Output:
403/// - Launches a detached `PowerShell` window (if available) for dry-run simulation, or `cmd` window otherwise.
404///
405/// Details:
406/// - When `dry_run` is true and `PowerShell` is available, uses `PowerShell` to simulate the batch install with Write-Host.
407/// - Always logs install attempts when not in `dry_run` to remain consistent with Unix behaviour.
408/// - During tests, this is a no-op to avoid opening real terminal windows.
409#[allow(unused_variables, clippy::missing_const_for_fn)]
410pub fn spawn_install_all(items: &[PackageItem], dry_run: bool) {
411    #[cfg(not(test))]
412    {
413        let mut names: Vec<String> = items.iter().map(|p| p.name.clone()).collect();
414        if names.is_empty() {
415            names.push("nothing".into());
416        }
417        let names_str = names.join(" ");
418
419        if dry_run && super::utils::is_powershell_available() {
420            // Use PowerShell to simulate the batch install operation
421            let powershell_cmd = format!(
422                "Write-Host 'DRY RUN: Simulating batch install of {}' -ForegroundColor Yellow; Write-Host 'Packages: {}' -ForegroundColor Cyan; Write-Host ''; Write-Host 'Press any key to close...'; $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')",
423                names.len(),
424                names_str.replace('\'', "''")
425            );
426            let _ = Command::new("powershell.exe")
427                .args(["-NoProfile", "-Command", &powershell_cmd])
428                .spawn();
429        } else {
430            let msg = if dry_run {
431                format!("DRY RUN: install {names_str}")
432            } else {
433                format!("Install {names_str} (not supported on Windows)")
434            };
435            let _ = Command::new("cmd")
436                .args([
437                    "/C",
438                    "start",
439                    "Pacsea Install",
440                    "cmd",
441                    "/K",
442                    &super::utils::cmd_echo_command(&msg),
443                ])
444                .spawn();
445        }
446
447        if !dry_run {
448            let _ = super::logging::log_installed(&names);
449        }
450    }
451}