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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
#[cfg(not(target_os = "windows"))]
use crate::state::Source;
#[allow(unused_imports)]
use std::process::Command;

use crate::state::PackageItem;

#[cfg(not(target_os = "windows"))]
use super::command::{aur_install_body, aur_install_helper_flags};
#[cfg(not(target_os = "windows"))]
use super::logging::log_installed;
#[cfg(not(target_os = "windows"))]
use super::utils::{
    choose_terminal_index_prefer_path, command_on_path, shell_single_quote, validate_package_names,
};

#[cfg(not(target_os = "windows"))]
/// What: Build the shell command string for batch package installation.
///
/// Input:
/// - `items`: Packages to install
/// - `official`: Names of official packages
/// - `aur`: Names of AUR packages
/// - `dry_run`: When `true`, prints commands instead of executing
///
/// Output:
/// - `Ok(shell command string)` with hold tail appended
///
/// # Errors
///
/// Returns `Err` when the configured privilege tool cannot be resolved for official paths.
///
/// Details:
/// - Official packages are grouped into a single `pacman` invocation
/// - AUR packages are installed via `paru`/`yay` with `--aur` on **AUR-only** targets (mixed installs chain `pacman` then the helper)
/// - Appends a "hold" tail so the terminal remains open after command completion
fn build_batch_install_command(
    items: &[PackageItem],
    official: &[String],
    aur: &[String],
    dry_run: bool,
) -> Result<String, String> {
    validate_package_names(official, "batch install command (official)")?;
    validate_package_names(aur, "batch install command (AUR)")?;
    let official_quoted: Vec<String> = official
        .iter()
        .map(|name| shell_single_quote(name))
        .collect();
    let aur_quoted: Vec<String> = aur.iter().map(|name| shell_single_quote(name)).collect();
    let hold_tail = "; echo; echo 'Finished.'; echo 'Press any key to close...'; read -rn1 -s _ || (echo; echo 'Press Ctrl+C to close'; sleep infinity)";

    let installed_set = crate::logic::deps::get_installed_packages();
    let provided_set = crate::logic::deps::get_provided_packages(&installed_set);

    let official_has_reinstall = official.iter().any(|name| {
        crate::logic::deps::is_package_installed_or_provided(name, &installed_set, &provided_set)
    });
    let pacman_dry_flags = if official_has_reinstall {
        "--noconfirm"
    } else {
        "--needed --noconfirm"
    };

    let aur_has_reinstall = aur.iter().any(|name| {
        crate::logic::deps::is_package_installed_or_provided(name, &installed_set, &provided_set)
    });
    let aur_s_flags = aur_install_helper_flags(aur_has_reinstall);
    let aur_cli_suffix = if aur_has_reinstall {
        "--noconfirm"
    } else {
        "--needed --noconfirm"
    };

    if dry_run {
        if !aur.is_empty() && !official.is_empty() {
            let tool = crate::logic::privilege::active_tool()?;
            let off_cmd = crate::logic::privilege::build_privilege_command(
                tool,
                &format!("pacman -S {pacman_dry_flags} {}", official_quoted.join(" ")),
            );
            let cmd = format!(
                "{off_cmd} && (paru -S --aur {aur_cli_suffix} {n} || yay -S --aur {aur_cli_suffix} {n}){hold}",
                n = aur_quoted.join(" "),
                hold = hold_tail
            );
            let quoted = shell_single_quote(&cmd);
            Ok(format!("echo DRY RUN: {quoted}"))
        } else if !aur.is_empty() {
            let cmd = format!(
                "(paru -S --aur {aur_cli_suffix} {n} || yay -S --aur {aur_cli_suffix} {n}){hold}",
                n = aur_quoted.join(" "),
                hold = hold_tail
            );
            let quoted = shell_single_quote(&cmd);
            Ok(format!("echo DRY RUN: {quoted}"))
        } else if !official.is_empty() {
            let tool = crate::logic::privilege::active_tool()?;
            let cmd = format!(
                "{}{hold}",
                crate::logic::privilege::build_privilege_command(
                    tool,
                    &format!("pacman -S {pacman_dry_flags} {}", official_quoted.join(" "))
                ),
                hold = hold_tail
            );
            let quoted = shell_single_quote(&cmd);
            Ok(format!("echo DRY RUN: {quoted}"))
        } else {
            Ok(format!("echo DRY RUN: nothing to install{hold_tail}"))
        }
    } else if !aur.is_empty() && !official.is_empty() {
        let has_versions = items
            .iter()
            .any(|item| matches!(item.source, Source::Official { .. }) && !item.version.is_empty());
        let reinstall_any = items.iter().any(|item| {
            matches!(item.source, Source::Official { .. }) && crate::index::is_installed(&item.name)
        });

        let tool = crate::logic::privilege::active_tool()?;
        let aur_body = aur_install_body(aur_s_flags, &aur_quoted.join(" "));
        if has_versions && reinstall_any {
            Ok(format!(
                "{} bash -c 'pacman -Sy --noconfirm && pacman -S --noconfirm {n}' && {aur_body}{hold}",
                tool.binary_name(),
                n = official_quoted.join(" "),
                aur_body = aur_body,
                hold = hold_tail
            ))
        } else {
            Ok(format!(
                "{} && {aur_body}{hold}",
                crate::logic::privilege::build_privilege_command(
                    tool,
                    &format!(
                        "pacman -S --needed --noconfirm {}",
                        official_quoted.join(" ")
                    )
                ),
                aur_body = aur_body,
                hold = hold_tail
            ))
        }
    } else if !aur.is_empty() {
        Ok(format!(
            "{body}{hold}",
            body = aur_install_body(aur_s_flags, &aur_quoted.join(" ")),
            hold = hold_tail
        ))
    } else if !official.is_empty() {
        // Check if any packages have version info (coming from updates window)
        let has_versions = items
            .iter()
            .any(|item| matches!(item.source, Source::Official { .. }) && !item.version.is_empty());
        let reinstall_any = items.iter().any(|item| {
            matches!(item.source, Source::Official { .. }) && crate::index::is_installed(&item.name)
        });

        let tool = crate::logic::privilege::active_tool()?;
        if has_versions && reinstall_any {
            Ok(format!(
                "{} bash -c 'pacman -Sy --noconfirm && pacman -S --noconfirm {n}'{hold}",
                tool.binary_name(),
                n = official_quoted.join(" "),
                hold = hold_tail
            ))
        } else {
            Ok(format!(
                "{}{hold}",
                crate::logic::privilege::build_privilege_command(
                    tool,
                    &format!(
                        "pacman -S --needed --noconfirm {}",
                        official_quoted.join(" ")
                    )
                ),
                hold = hold_tail
            ))
        }
    } else {
        Ok(format!("echo nothing to install{hold_tail}"))
    }
}

#[cfg(not(target_os = "windows"))]
/// What: Attempt to spawn a terminal with the given command string.
///
/// Input:
/// - `term`: Terminal executable name
/// - `args`: Arguments for the terminal
/// - `needs_xfce_command`: Whether this terminal needs special xfce4-terminal command handling
/// - `cmd_str`: Command string to execute in the terminal
///
/// Output:
/// - `Ok(())` if the terminal was successfully spawned, `Err(())` otherwise
///
/// Details:
/// - Handles special cases for `konsole` (`Wayland`), `gnome-console`/`kgx` (rendering), and `xfce4-terminal` (command format)
/// - Sets up `PACSEA_TEST_OUT` environment variable if present
fn try_spawn_terminal(
    term: &str,
    args: &[&str],
    needs_xfce_command: bool,
    cmd_str: &str,
) -> Result<(), ()> {
    let mut cmd = Command::new(term);
    if needs_xfce_command && term == "xfce4-terminal" {
        let quoted = shell_single_quote(cmd_str);
        cmd.arg("--command").arg(format!("bash -lc {quoted}"));
    } else {
        cmd.args(args.iter().copied()).arg(cmd_str);
    }
    if let Ok(p) = std::env::var("PACSEA_TEST_OUT") {
        if let Some(parent) = std::path::Path::new(&p).parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        cmd.env("PACSEA_TEST_OUT", p);
    }
    if term == "konsole" && std::env::var_os("WAYLAND_DISPLAY").is_some() {
        cmd.env("QT_LOGGING_RULES", "qt.qpa.wayland.textinput=false");
    }
    if term == "gnome-console" || term == "kgx" {
        cmd.env("GSK_RENDERER", "cairo");
        cmd.env("LIBGL_ALWAYS_SOFTWARE", "1");
    }
    cmd.spawn().map(|_| ()).map_err(|_| ())
}

#[cfg(not(target_os = "windows"))]
/// What: Spawn a terminal to install a batch of packages.
///
/// Input:
/// - `items`: Packages to install
/// - `dry_run`: When `true`, prints commands instead of executing
///
/// Output:
/// - Launches a terminal (or falls back to `bash`) running the composed install commands.
///
/// Details:
/// - Official packages are grouped into a single `pacman` invocation
/// - AUR packages are installed via `paru`/`yay` (prompts to install a helper if missing)
/// - Prefers common terminals (GNOME Console/Terminal, kitty, alacritty, xterm, xfce4-terminal, etc.); falls back to `bash`
/// - Appends a "hold" tail so the terminal remains open after command completion
/// - During tests, this is a no-op to avoid opening real terminal windows.
pub fn spawn_install_all(items: &[PackageItem], dry_run: bool) {
    // Skip actual spawning during tests unless PACSEA_TEST_OUT is set (indicates a test with fake terminal)
    #[cfg(test)]
    if std::env::var("PACSEA_TEST_OUT").is_err() {
        return;
    }

    let mut official: Vec<String> = Vec::new();
    let mut aur: Vec<String> = Vec::new();
    for it in items {
        match it.source {
            Source::Official { .. } => official.push(it.name.clone()),
            Source::Aur => aur.push(it.name.clone()),
        }
    }
    let names_vec: Vec<String> = items.iter().map(|p| p.name.clone()).collect();
    tracing::info!(
        total = items.len(),
        aur_count = aur.len(),
        official_count = official.len(),
        dry_run = dry_run,
        names = %names_vec.join(" "),
        "spawning install"
    );

    let cmd_str = match build_batch_install_command(items, &official, &aur, dry_run) {
        Ok(s) => s,
        Err(err) => {
            tracing::error!(error = %err, "privilege tool resolution failed for batch install");
            return;
        }
    };

    // Prefer GNOME Terminal when running under GNOME desktop
    let is_gnome = std::env::var("XDG_CURRENT_DESKTOP")
        .ok()
        .is_some_and(|v| v.to_uppercase().contains("GNOME"));
    let terms_gnome_first: &[(&str, &[&str], bool)] = &[
        ("gnome-terminal", &["--", "bash", "-lc"], false),
        ("gnome-console", &["--", "bash", "-lc"], false),
        ("kgx", &["--", "bash", "-lc"], false),
        ("alacritty", &["-e", "bash", "-lc"], false),
        ("kitty", &["bash", "-lc"], false),
        ("konsole", &["-e", "bash", "-lc"], false),
        ("xterm", &["-hold", "-e", "bash", "-lc"], false),
        ("xfce4-terminal", &[], true),
        ("tilix", &["--", "bash", "-lc"], false),
        ("mate-terminal", &["--", "bash", "-lc"], false),
    ];
    let terms_default: &[(&str, &[&str], bool)] = &[
        ("alacritty", &["-e", "bash", "-lc"], false),
        ("kitty", &["bash", "-lc"], false),
        ("konsole", &["-e", "bash", "-lc"], false),
        ("gnome-terminal", &["--", "bash", "-lc"], false),
        ("gnome-console", &["--", "bash", "-lc"], false),
        ("kgx", &["--", "bash", "-lc"], false),
        ("xterm", &["-hold", "-e", "bash", "-lc"], false),
        ("xfce4-terminal", &[], true),
        ("tilix", &["--", "bash", "-lc"], false),
        ("mate-terminal", &["--", "bash", "-lc"], false),
    ];
    let terms = if is_gnome {
        terms_gnome_first
    } else {
        terms_default
    };
    let mut launched = false;
    if let Some(idx) = choose_terminal_index_prefer_path(terms) {
        let (term, args, needs_xfce_command) = terms[idx];
        match try_spawn_terminal(term, args, needs_xfce_command, &cmd_str) {
            Ok(()) => {
                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");
                launched = true;
            }
            Err(()) => {
                tracing::warn!(terminal = %term, names = %names_vec.join(" "), "failed to spawn terminal, trying next");
            }
        }
    }

    if !launched {
        for (term, args, needs_xfce_command) in terms {
            if command_on_path(term) {
                match try_spawn_terminal(term, args, *needs_xfce_command, &cmd_str) {
                    Ok(()) => {
                        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");
                        launched = true;
                        break;
                    }
                    Err(()) => {
                        tracing::warn!(terminal = %term, names = %names_vec.join(" "), "failed to spawn terminal, trying next");
                    }
                }
            }
        }
    }
    if !launched {
        let res = Command::new("bash").args(["-lc", &cmd_str]).spawn();
        if let Err(e) = res {
            tracing::error!(error = %e, names = %names_vec.join(" "), "failed to spawn bash to run install command");
        } else {
            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");
        }
    }

    if !dry_run {
        let names: Vec<String> = items.iter().map(|p| p.name.clone()).collect();
        if !names.is_empty()
            && let Err(e) = log_installed(&names)
        {
            tracing::warn!(error = %e, count = names.len(), "failed to write install audit log");
        }
    }
}

#[cfg(all(test, not(target_os = "windows")))]
mod tests {
    #[test]
    /// What: Confirm batch installs launch gnome-terminal with the expected separator arguments.
    ///
    /// Inputs:
    /// - Shim `gnome-terminal` scripted to capture argv via `PACSEA_TEST_OUT`.
    /// - `spawn_install_all` invoked with two official packages in dry-run mode.
    ///
    /// Output:
    /// - Captured argument list starts with `--`, `bash`, `-lc`, validating safe command invocation.
    ///
    /// Details:
    /// - Overrides `PATH` and environment variables, then restores them to avoid leaking state across tests.
    fn install_batch_uses_gnome_terminal_double_dash() {
        use std::fs;
        use std::os::unix::fs::PermissionsExt;
        use std::path::PathBuf;

        let mut dir: PathBuf = std::env::temp_dir();
        dir.push(format!(
            "pacsea_test_inst_batch_gnome_{}_{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("System time is before UNIX epoch")
                .as_nanos()
        ));
        let _ = fs::create_dir_all(&dir);
        let mut out_path = dir.clone();
        out_path.push("args.txt");
        let mut term_path = dir.clone();
        term_path.push("gnome-terminal");
        let script = "#!/bin/sh\n: > \"$PACSEA_TEST_OUT\"\nfor a in \"$@\"; do printf '%s\n' \"$a\" >> \"$PACSEA_TEST_OUT\"; done\n";
        fs::write(&term_path, script.as_bytes()).expect("Failed to write test terminal script");
        let mut perms = fs::metadata(&term_path)
            .expect("Failed to read test terminal script metadata")
            .permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&term_path, perms)
            .expect("Failed to set test terminal script permissions");

        let orig_path = std::env::var_os("PATH");
        unsafe {
            std::env::set_var("PATH", dir.display().to_string());
            std::env::set_var("PACSEA_TEST_OUT", out_path.display().to_string());
        }

        let items = vec![
            crate::state::PackageItem {
                name: "rg".into(),
                version: "1".into(),
                description: String::new(),
                source: crate::state::Source::Official {
                    repo: "extra".into(),
                    arch: "x86_64".into(),
                },
                popularity: None,
                out_of_date: None,
                orphaned: false,
            },
            crate::state::PackageItem {
                name: "fd".into(),
                version: "1".into(),
                description: String::new(),
                source: crate::state::Source::Official {
                    repo: "extra".into(),
                    arch: "x86_64".into(),
                },
                popularity: None,
                out_of_date: None,
                orphaned: false,
            },
        ];
        super::spawn_install_all(&items, true);
        std::thread::sleep(std::time::Duration::from_millis(50));

        let body = fs::read_to_string(&out_path).expect("fake terminal args file written");
        let lines: Vec<&str> = body.lines().collect();
        assert!(lines.len() >= 3, "expected at least 3 args, got: {body}");
        assert_eq!(lines[0], "--");
        assert_eq!(lines[1], "bash");
        assert_eq!(lines[2], "-lc");

        unsafe {
            if let Some(v) = orig_path {
                std::env::set_var("PATH", v);
            } else {
                std::env::remove_var("PATH");
            }
            std::env::remove_var("PACSEA_TEST_OUT");
        }
    }
}

#[cfg(target_os = "windows")]
/// What: Present an informational install message on Windows where package management is unsupported.
///
/// Input:
/// - `items`: Packages the user attempted to install.
/// - `dry_run`: When `true`, uses `PowerShell` to simulate the install operation.
///
/// Output:
/// - Launches a detached `PowerShell` window (if available) for dry-run simulation, or `cmd` window otherwise.
///
/// Details:
/// - When `dry_run` is true and `PowerShell` is available, uses `PowerShell` to simulate the batch install with Write-Host.
/// - Always logs install attempts when not in `dry_run` to remain consistent with Unix behaviour.
/// - During tests, this is a no-op to avoid opening real terminal windows.
#[allow(unused_variables, clippy::missing_const_for_fn)]
pub fn spawn_install_all(items: &[PackageItem], dry_run: bool) {
    #[cfg(not(test))]
    {
        let mut names: Vec<String> = items.iter().map(|p| p.name.clone()).collect();
        if names.is_empty() {
            names.push("nothing".into());
        }
        let names_str = names.join(" ");

        if dry_run && super::utils::is_powershell_available() {
            // Use PowerShell to simulate the batch install operation
            let powershell_cmd = format!(
                "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')",
                names.len(),
                names_str.replace('\'', "''")
            );
            let _ = Command::new("powershell.exe")
                .args(["-NoProfile", "-Command", &powershell_cmd])
                .spawn();
        } else {
            let msg = if dry_run {
                format!("DRY RUN: install {names_str}")
            } else {
                format!("Install {names_str} (not supported on Windows)")
            };
            let _ = Command::new("cmd")
                .args([
                    "/C",
                    "start",
                    "Pacsea Install",
                    "cmd",
                    "/K",
                    &super::utils::cmd_echo_command(&msg),
                ])
                .spawn();
        }

        if !dry_run {
            let _ = super::logging::log_installed(&names);
        }
    }
}