haj 0.3.7

the beautiful, cross-distro package manager and tui.
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
use crate::cli::Cli;
use crate::core::ui::prompt_confirm;
use crate::core::ui::{InstallChoice, handle_conflicts_ui, prompt_install};
use crate::ui;
use crossterm::style::Stylize;
fn is_local_archive(arg: &str) -> bool {
    const ARCHIVE_EXTS: &[&str] = &[
        ".pkg.tar.zst",
        ".pkg.tar.xz",
        ".pkg.tar.gz",
        ".pkg.tar.bz2",
        ".pkg.tar.lz4",
        ".pkg.tar.lzo",
        ".pkg.tar",
        ".deb",
        ".rpm",
    ];
    ARCHIVE_EXTS.iter().any(|ext| arg.ends_with(ext))
}

type ResolvedAurPkg = (String, String, bool, Option<String>);

fn filter_needed_aur(
    resolved: Vec<ResolvedAurPkg>,
    needed: bool,
) -> (Vec<ResolvedAurPkg>, Vec<(String, String)>) {
    if !needed {
        return (resolved, Vec::new());
    }
    let mut build = Vec::new();
    let mut skipped = Vec::new();
    for item in resolved {
        if item.3.is_some() && !item.2 {
            skipped.push((item.0, item.1));
        } else {
            build.push(item);
        }
    }
    (build, skipped)
}

pub async fn process_installation(
    packages: Vec<String>,
    backend: &dyn crate::backend::traits::PackageManager,
    cli: &Cli,
) {
    process_installation_with_opts(packages, backend, cli, false).await;
}

pub async fn process_installation_with_opts(
    packages: Vec<String>,
    backend: &dyn crate::backend::traits::PackageManager,
    cli: &Cli,
    sync_system: bool,
) {
    let mut local_archives: Vec<String> = Vec::new();
    let mut native_pkgs: Vec<String> = Vec::new();
    let mut aur_pkgs: Vec<String> = Vec::new();

    for pkg in &packages {
        if is_local_archive(pkg) {
            local_archives.push(pkg.clone());
            continue;
        }
        if cli.aur && !cli.repo {
            if backend.capabilities().supports_external {
                aur_pkgs.push(pkg.clone());
            } else {
                eprintln!(
                    "{} error: external repositories not supported by this backend",
                    "✗".red()
                );
                std::process::exit(1);
            }
            continue;
        }

        match backend.info(pkg).await {
            Ok(Some(info))
                if matches!(
                    info.source(),
                    crate::core::package::PackageSource::Official(_)
                ) =>
            {
                native_pkgs.push(pkg.clone());
            }
            Ok(_)
                if !cli.aur
                    && backend.capabilities().supports_groups
                    && let Ok(group_pkgs) = backend.list_group_or_meta(pkg).await
                    && !group_pkgs.is_empty() =>
            {
                native_pkgs.extend(group_pkgs.into_iter().map(|p| p.name));
            }
            Ok(_) if !cli.repo && backend.capabilities().supports_external => {
                aur_pkgs.push(pkg.clone());
            }
            _ => {
                eprintln!(
                    "{} error: package '{}' not found",
                    "✗".red(),
                    pkg.clone().bold()
                );
                std::process::exit(1);
            }
        }
    }

    if !local_archives.is_empty() {
        println!("\n{}", "local packages:".bold().white());
        for archive in &local_archives {
            println!("  {}", archive.as_str().cyan().bold());
        }
        println!();
        if !cli.noconfirm
            && !cli.dry_run
            && !prompt_confirm("proceed with local package installation? [Y/n]")
        {
            println!("{} aborted.", "✗".red());
            return;
        }
    }

    let base_local_opts = crate::backend::TxOptions {
        noconfirm: true,
        needed: cli.needed,
        ignore: cli.ignore.clone(),
        root: cli.root.clone(),
        config: cli.config.clone(),
        ..Default::default()
    };
    for archive in local_archives {
        match backend
            .build_install_local_with_opts(std::path::Path::new(&archive), &base_local_opts)
        {
            Ok(plan) => {
                crate::core::process::execute_or_exit(
                    &plan,
                    &format!("installing local archive {archive}..."),
                    &format!("installed {archive}."),
                    cli.dry_run,
                    cli.verbose,
                )
                .await;
            }
            Err(e) => {
                eprintln!("{} {}", "✗".red(), e);
                std::process::exit(1);
            }
        }
    }

    if native_pkgs.is_empty() && aur_pkgs.is_empty() {
        return;
    }

    let mut native_summaries = Vec::new();
    let mut total_dl = 0.0;
    let mut total_inst = 0.0;

    if !native_pkgs.is_empty() {
        println!("{} resolving native dependencies...", "::".blue());
        let native_pkgs_str: Vec<&str> = native_pkgs.iter().map(|s| s.as_str()).collect();
        match backend.get_install_summaries(&native_pkgs_str).await {
            Ok(summaries) => {
                for sum in &summaries {
                    total_dl += sum.download_size_mb;
                    total_inst += sum.install_size_mb;
                }
                native_summaries = summaries;
            }
            Err(e) => {
                eprintln!("{} error: {}", "✗".red(), e);
                std::process::exit(1);
            }
        }
    }

    let mut resolved_aur_pkgs = Vec::new();
    if !aur_pkgs.is_empty() {
        let aur_pkgs_str: Vec<&str> = aur_pkgs.iter().map(|s| s.as_str()).collect();
        match backend.resolve_external(&aur_pkgs_str).await {
            Ok(resolution) => {
                let (to_build, skipped) = filter_needed_aur(resolution.packages, cli.needed);
                for (pkg, ver) in skipped {
                    println!(
                        "{} {} ({}) is up to date -- skipping.",
                        "::".yellow(),
                        pkg,
                        ver
                    );
                }
                resolved_aur_pkgs = to_build;
            }
            Err(e) => {
                eprintln!("{} error: failed to resolve aur packages: {}", "✗".red(), e);
                std::process::exit(1);
            }
        }
    }

    let mut all_targets: Vec<&str> = native_pkgs.iter().map(String::as_str).collect();
    for (pkg, _, _, _) in &resolved_aur_pkgs {
        all_targets.push(pkg.as_str());
    }
    let conflicts = match backend.detect_conflicts(&all_targets).await {
        Ok(conflicts) => conflicts,
        Err(e) => {
            eprintln!("{} error: conflict check failed: {e}", "✗".red());
            std::process::exit(1);
        }
    };

    let allow_conflict_removal = match handle_conflicts_ui(
        &conflicts,
        cli.dry_run,
        cli.noconfirm,
        crate::core::ui::prompt_confirm_default_no,
    ) {
        Ok(allowed) => allowed,
        Err(e) => {
            println!("{} {}", "✗".red(), e);
            std::process::exit(1);
        }
    };

    if native_summaries.is_empty() && resolved_aur_pkgs.is_empty() {
        println!("{} nothing to do.", "✓".green());
        return;
    }

    println!("\n{}", "targets:".bold().white());

    if !native_summaries.is_empty() {
        println!("  {}", "native repositories:".dim());
        for sum in &native_summaries {
            println!(
                "    {:<25} {}",
                sum.name.clone().cyan().bold(),
                sum.version.clone().dim()
            );
        }
    }

    if !resolved_aur_pkgs.is_empty() {
        println!("  {}", "arch user repository:".dim());
        for (pkg, aur_ver, is_update, local_ver) in &resolved_aur_pkgs {
            if *is_update {
                println!(
                    "    {:<25} {} -> {}",
                    pkg.clone().magenta().bold(),
                    local_ver.as_deref().unwrap_or_default().red(),
                    aur_ver.clone().green()
                );
            } else {
                println!(
                    "    {:<25} {}",
                    pkg.clone().magenta().bold(),
                    aur_ver.clone().green()
                );
            }
        }
    }

    if total_dl > 0.0 || total_inst > 0.0 {
        println!("\n{:<15} {:.2} mb", "download:", total_dl);
        println!("{:<15} {:.2} mb", "disk usage:", total_inst);
    } else {
        println!();
    }

    if !cli.noconfirm && !cli.dry_run {
        let has_aur = !resolved_aur_pkgs.is_empty();
        let mut prompt_msg = if has_aur {
            "proceed with installation? [Y/n/v] (v = view PKGBUILDs)".to_string()
        } else {
            "proceed with installation? [Y/n]".to_string()
        };

        loop {
            let choice = if has_aur {
                prompt_install(&prompt_msg)
            } else if prompt_confirm(&prompt_msg) {
                InstallChoice::Yes
            } else {
                InstallChoice::No
            };

            match choice {
                InstallChoice::Yes => break,
                InstallChoice::No => {
                    println!("{} aborted.", "✗".red());
                    return;
                }
                InstallChoice::View => {
                    let aur_names: Vec<String> = resolved_aur_pkgs
                        .iter()
                        .map(|(pkg, _, _, _)| pkg.clone())
                        .collect();
                    view_pkgbuilds(&aur_names).await;

                    prompt_msg = "proceed with installation? [Y/n]".to_string();
                }
            }
        }
    }

    if !native_pkgs.is_empty() {
        let native_pkgs_str: Vec<&str> = native_pkgs.iter().map(|s| s.as_str()).collect();
        let tx_opts = crate::backend::TxOptions {
            noconfirm: true,
            needed: cli.needed,
            ignore: cli.ignore.clone(),
            root: cli.root.clone(),
            config: cli.config.clone(),
            allow_conflict_removal,
        };
        let plans_res = if sync_system {
            backend.build_install_upgraded_with_opts(&native_pkgs_str, &tx_opts)
        } else {
            backend
                .build_install_with_opts(&native_pkgs_str, &tx_opts)
                .map(|p| vec![p])
        };
        match plans_res {
            Ok(plans) => {
                for plan in plans {
                    crate::core::process::execute_or_exit(
                        &plan,
                        "installing native packages...",
                        "native packages installed successfully.",
                        cli.dry_run,
                        cli.verbose,
                    )
                    .await;
                }
            }
            Err(e) => {
                eprintln!("{} {}", "✗".red(), e);
                std::process::exit(1);
            }
        }
    }

    if !resolved_aur_pkgs.is_empty() {
        let mut had_aur_error = false;
        for (pkg, aur_ver, is_update, _) in resolved_aur_pkgs {
            if cli.dry_run {
                println!(
                    "{} would build and install aur package: {}",
                    "[dry run]".bold().yellow(),
                    pkg.magenta()
                );
                continue;
            }

            println!(
                "\n{} preparing {} ({})...",
                "::".blue(),
                pkg.clone().magenta().bold(),
                aur_ver.clone().green()
            );

            match backend.build_external_package(&pkg, cli.verbose).await {
                Ok(pkg_path) => {
                    let spinner_msg = if is_update {
                        format!("updating built package {}...", pkg.clone().magenta().bold())
                    } else {
                        format!(
                            "installing built package {}...",
                            pkg.clone().magenta().bold()
                        )
                    };
                    let success_msg = if is_update {
                        format!(
                            "{} updated successfully ({}).",
                            pkg.as_str().magenta().bold(),
                            aur_ver.dim()
                        )
                    } else {
                        format!(
                            "{} installed successfully ({}).",
                            pkg.as_str().magenta().bold(),
                            aur_ver.dim()
                        )
                    };
                    let local_opts = crate::backend::TxOptions {
                        noconfirm: true,
                        needed: cli.needed,
                        ignore: cli.ignore.clone(),
                        root: cli.root.clone(),
                        config: cli.config.clone(),
                        allow_conflict_removal,
                    };
                    match backend.build_install_local_with_opts(&pkg_path, &local_opts) {
                        Ok(plan) => {
                            if crate::core::process::execute_plan(
                                &plan,
                                &spinner_msg,
                                &success_msg,
                                cli.dry_run,
                                cli.verbose,
                            )
                            .await
                            .is_err()
                            {
                                had_aur_error = true;
                            } else if !cli.dry_run {
                                crate::core::aur::record_devel_installed(&pkg, &pkg_path).await;
                            }
                        }
                        Err(e) => {
                            eprintln!("{} {}", "error:".red().bold(), e);
                            had_aur_error = true;
                        }
                    }
                }
                Err(e) => {
                    eprintln!("{} {}", "error:".red().bold(), e);
                    had_aur_error = true;
                }
            }
        }
        if had_aur_error {
            std::process::exit(1);
        }
    }
}

pub async fn view_pkgbuilds(pkgs: &[String]) -> bool {
    let editor = std::env::var("VISUAL")
        .or_else(|_| std::env::var("EDITOR"))
        .unwrap_or_else(|_| {
            if std::process::Command::new("nvim")
                .arg("--version")
                .output()
                .is_ok()
            {
                "nvim".to_string()
            } else if std::process::Command::new("vim")
                .arg("--version")
                .output()
                .is_ok()
            {
                "vim".to_string()
            } else if std::process::Command::new("nano")
                .arg("--version")
                .output()
                .is_ok()
            {
                "nano".to_string()
            } else {
                "less".to_string()
            }
        });

    let mut all_ok = true;
    for pkg in pkgs {
        let spinner = ui::spinner(&format!(
            "fetching PKGBUILD for {}...",
            pkg.clone().magenta()
        ));
        let clone_name = crate::core::aur::resolve_package_base(pkg).await;
        if !crate::core::aur::is_safe_aur_segment(&clone_name) {
            spinner.finish_and_clear();
            all_ok = false;
            println!(
                "{} unsafe AUR package name '{}'.",
                "✗".red(),
                clone_name.bold()
            );
            continue;
        }

        let Some(tmp_dir) = create_exclusive_view_dir() else {
            spinner.finish_and_clear();
            all_ok = false;
            println!("{} failed to allocate temporary view directory.", "✗".red());
            continue;
        };

        struct ViewCleanup(std::path::PathBuf);
        impl Drop for ViewCleanup {
            fn drop(&mut self) {
                let _ = std::fs::remove_dir_all(&self.0);
            }
        }
        let _cleanup = ViewCleanup(tmp_dir.clone());

        let clone_status = tokio::process::Command::new("git")
            .args([
                "clone",
                "--depth=1",
                "--quiet",
                "--",
                &format!("https://aur.archlinux.org/{clone_name}.git"),
            ])
            .arg(&tmp_dir)
            .kill_on_drop(true)
            .status()
            .await;

        spinner.finish_and_clear();

        if clone_status.is_ok_and(|s| s.success()) {
            let pkgbuild_path = tmp_dir.join("PKGBUILD");

            if pkgbuild_path.exists() {
                let parts: Vec<String> = editor
                    .split_whitespace()
                    .map(std::string::ToString::to_string)
                    .collect();
                if !parts.is_empty() {
                    let exec = &parts[0];
                    let mut cmd = std::process::Command::new(exec);

                    if parts.len() > 1 {
                        cmd.args(&parts[1..]);
                    }

                    if let Some(flag) = editor_read_only_flag(exec) {
                        cmd.arg(flag);
                    }

                    cmd.arg(&pkgbuild_path);
                    let _ = cmd.status();
                }
            } else {
                all_ok = false;
                println!(
                    "{} PKGBUILD not found in repository for {}.",
                    "✗".red(),
                    pkg.clone().bold()
                );
            }
        } else {
            all_ok = false;
            println!(
                "{} failed to fetch repository for {}.",
                "✗".red(),
                pkg.clone().bold()
            );
        }
    }
    all_ok
}

fn editor_read_only_flag(exec: &str) -> Option<&'static str> {
    let bin = std::path::Path::new(exec)
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or(exec)
        .to_ascii_lowercase();
    match bin.as_str() {
        "vi" | "vim" | "nvim" | "view" | "vimdiff" | "nvimdiff" | "gvim" => Some("-R"),
        "nano" => Some("-v"),
        _ => None,
    }
}

fn create_exclusive_view_dir() -> Option<std::path::PathBuf> {
    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let base = std::env::temp_dir();
    for _ in 0..16 {
        let id = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let candidate = base.join(format!("haj-view-{}-{id}", std::process::id()));
        match std::fs::create_dir(&candidate) {
            Ok(()) => return Some(candidate),
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(_) => return None,
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::{filter_needed_aur, is_local_archive};

    #[test]
    fn test_is_local_archive_extension_only() {
        assert!(is_local_archive("./pkg-1.0-1-x86_64.pkg.tar.zst"));
        assert!(is_local_archive("/tmp/old.pkg.tar.xz"));
        assert!(is_local_archive("foo.deb"));
        assert!(is_local_archive("bar.rpm"));
        assert!(!is_local_archive("./Cargo.toml"));
        assert!(!is_local_archive("bash"));
    }

    #[test]
    fn test_filter_needed_aur_skips_uptodate_installed() {
        let pkgs = vec![
            (
                "yay-bin".into(),
                "12.0-1".into(),
                false,
                Some("12.0-1".into()),
            ),
            ("paru".into(), "2.1-1".into(), true, Some("2.0-1".into())),
            ("newpkg".into(), "1.0-1".into(), false, None),
        ];

        let (all, skipped_none) = filter_needed_aur(pkgs.clone(), false);
        assert_eq!(all.len(), 3);
        assert!(skipped_none.is_empty());

        let (needed, skipped) = filter_needed_aur(pkgs, true);
        assert_eq!(needed.len(), 2);
        assert_eq!(needed[0].0, "paru");
        assert_eq!(needed[1].0, "newpkg");
        assert_eq!(skipped, vec![("yay-bin".into(), "12.0-1".into())]);
    }

    #[test]
    fn test_editor_read_only_flag_uses_basename() {
        assert_eq!(super::editor_read_only_flag("nvim"), Some("-R"));
        assert_eq!(super::editor_read_only_flag("/usr/bin/VIM"), Some("-R"));
        assert_eq!(super::editor_read_only_flag("/bin/nano"), Some("-v"));
        assert_eq!(super::editor_read_only_flag("vivaldi"), None);
        assert_eq!(super::editor_read_only_flag("helix"), None);
    }
}