haj 0.3.4

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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
use crossterm::style::Stylize;
use serde::Deserialize;
use std::collections::HashSet;
use std::path::PathBuf;
use std::process::Stdio;
use tokio::io::AsyncReadExt;
use tokio::process::Command;

pub type AurProgressTx = tokio::sync::mpsc::Sender<(Option<String>, Option<String>)>;

#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct AurPackage {
    pub name: String,
    #[serde(default)]
    pub package_base: Option<String>,
    pub version: String,
    pub description: Option<String>,
    #[serde(default)]
    pub num_votes: u64,
    #[serde(default, rename = "Conflicts")]
    pub conflicts: Vec<String>,
    #[serde(default)]
    pub depends: Vec<String>,
    #[serde(default)]
    pub opt_depends: Vec<String>,
}

#[derive(Debug, Deserialize)]
pub struct AurResponse {
    pub results: Vec<AurPackage>,
}

pub(crate) fn strip_dep_constraint(dep: &str) -> &str {
    dep.split(['>', '<', '=', ':']).next().unwrap_or(dep).trim()
}

pub(crate) fn parse_srcinfo_depends(srcinfo: &str, arch: &str) -> Vec<String> {
    let arch_dep_prefix = format!("depends_{arch}");
    let arch_make_prefix = format!("makedepends_{arch}");
    let mut deps = Vec::new();
    let mut seen = HashSet::new();

    for raw in srcinfo.lines() {
        let line = raw.trim();
        let Some((key, val)) = line.split_once(" = ") else {
            continue;
        };
        let key = key.trim();
        if key == "depends"
            || key == "makedepends"
            || key == arch_dep_prefix
            || key == arch_make_prefix
        {
            let dep = val.trim().to_string();
            if !dep.is_empty() && seen.insert(dep.clone()) {
                deps.push(dep);
            }
        }
    }
    deps
}

pub(crate) fn select_built_archive(packagelist_stdout: &str, pkg_name: &str) -> Option<PathBuf> {
    let candidates: Vec<PathBuf> = packagelist_stdout
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .map(PathBuf::from)
        .filter(|p| p.is_file())
        .collect();

    let is_debug = |p: &PathBuf| {
        p.file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .contains("-debug-")
    };

    candidates
        .iter()
        .find(|p| {
            let fname = p.file_name().unwrap_or_default().to_string_lossy();
            crate::core::downgrade::parse_package_filename(&fname)
                .is_some_and(|(name, _)| name == pkg_name)
        })
        .cloned()
        .or_else(|| candidates.iter().find(|p| !is_debug(p)).cloned())
        .or_else(|| candidates.into_iter().next())
}

pub(crate) async fn resolve_package_base(pkg_name: &str) -> String {
    match info(&[pkg_name]).await {
        Ok(res) => res
            .results
            .into_iter()
            .find(|p| p.name == pkg_name)
            .and_then(|p| p.package_base)
            .unwrap_or_else(|| pkg_name.to_string()),
        Err(_) => pkg_name.to_string(),
    }
}

async fn emit_progress(tx: Option<&AurProgressTx>, action: Option<String>, log: Option<String>) {
    if let Some(ch) = tx {
        let _ = ch.send((action, log)).await;
    }
}

async fn run_priv_pacman(args: &[String], in_tui: bool) -> anyhow::Result<()> {
    let is_root = crate::core::is_root();
    if !in_tui && !is_root {
        crate::core::ensure_sudo().await?;
    }

    let (prog, final_args) = if is_root {
        ("pacman".to_string(), args.to_vec())
    } else {
        let priv_cmd = crate::core::resolve_privilege_cmd();
        crate::core::build_privileged_invocation(&priv_cmd, "pacman", args, &[])
    };

    let output = Command::new(prog)
        .args(&final_args)
        .stdin(if in_tui {
            Stdio::null()
        } else {
            Stdio::inherit()
        })
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true)
        .spawn()?
        .wait_with_output()
        .await?;

    if output.status.success() {
        return Ok(());
    }

    let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
    let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
    let detail = if !stderr.is_empty() { stderr } else { stdout };
    if detail.is_empty() {
        anyhow::bail!(
            "pacman exited with code {}",
            output.status.code().unwrap_or(1)
        );
    }
    anyhow::bail!("pacman failed: {detail}");
}

pub async fn build(pkg_name: &str, is_verbose: bool) -> anyhow::Result<PathBuf> {
    let mut visited = HashSet::new();
    build_internal(pkg_name, is_verbose, None, &mut visited).await
}

pub async fn build_with_progress(
    pkg_name: &str,
    tx: Option<&AurProgressTx>,
) -> anyhow::Result<PathBuf> {
    let mut visited = HashSet::new();
    build_internal(pkg_name, false, tx, &mut visited).await
}

fn build_internal<'a>(
    pkg_name: &'a str,
    is_verbose: bool,
    progress_tx: Option<&'a AurProgressTx>,
    visited: &'a mut HashSet<String>,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<PathBuf>> + Send + 'a>> {
    Box::pin(async move {
        if crate::core::is_root() {
            anyhow::bail!(
                "{} makepkg cannot run as root. please run haj as a normal user.",
                "✗".red().bold()
            );
        }

        if !visited.insert(pkg_name.to_string()) {
            anyhow::bail!("circular AUR dependency detected involving '{pkg_name}'");
        }

        if progress_tx.is_none() {
            crate::core::ensure_sudo().await?;
        }

        let aur_cache_dir = crate::config::resolve_aur_cache_dir();
        tokio::fs::create_dir_all(&aur_cache_dir).await?;

        let clone_name = resolve_package_base(pkg_name).await;
        let pkg_dir = aur_cache_dir.join(&clone_name);

        let fetch_spinner = progress_tx
            .is_none()
            .then(|| crate::ui::spinner(&format!("fetching {} from aur...", pkg_name.bold())));
        emit_progress(
            progress_tx,
            Some(format!("fetching {pkg_name} from aur...")),
            Some(format!(":: fetching {pkg_name} from aur...")),
        )
        .await;

        if pkg_dir.exists() {
            let fetch_ok = Command::new("git")
                .args([
                    "-C",
                    &pkg_dir.to_string_lossy(),
                    "fetch",
                    "--quiet",
                    "origin",
                ])
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .kill_on_drop(true)
                .status()
                .await?
                .success();
            let reset_ok = if fetch_ok {
                Command::new("git")
                    .args([
                        "-C",
                        &pkg_dir.to_string_lossy(),
                        "reset",
                        "--hard",
                        "FETCH_HEAD",
                    ])
                    .stdin(Stdio::null())
                    .stdout(Stdio::null())
                    .stderr(Stdio::null())
                    .kill_on_drop(true)
                    .status()
                    .await?
                    .success()
            } else {
                false
            };

            if !reset_ok {
                if let Some(sp) = fetch_spinner {
                    sp.finish_and_clear();
                }
                anyhow::bail!("failed to update cached repository for {pkg_name}");
            }
        } else {
            let aur_url = format!("https://aur.archlinux.org/{clone_name}.git");
            let status = Command::new("git")
                .arg("clone")
                .arg(&aur_url)
                .arg(&pkg_dir)
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .kill_on_drop(true)
                .status()
                .await?;

            if !status.success() {
                if let Some(sp) = fetch_spinner {
                    sp.finish_and_clear();
                }
                anyhow::bail!("failed to clone {pkg_name}. does it exist?");
            }
        }
        if let Some(sp) = fetch_spinner {
            sp.finish_and_clear();
        }

        let dep_spinner = progress_tx
            .is_none()
            .then(|| crate::ui::spinner("resolving dependencies..."));
        emit_progress(
            progress_tx,
            Some("resolving aur dependencies...".into()),
            None,
        )
        .await;

        let srcinfo_out = Command::new("makepkg")
            .arg("--printsrcinfo")
            .current_dir(&pkg_dir)
            .kill_on_drop(true)
            .output()
            .await?;

        if !srcinfo_out.status.success() {
            if let Some(sp) = dep_spinner {
                sp.finish_and_clear();
            }
            anyhow::bail!("failed to read PKGBUILD for {pkg_name}");
        }

        let srcinfo_str = String::from_utf8_lossy(&srcinfo_out.stdout);
        let all_deps = parse_srcinfo_depends(&srcinfo_str, std::env::consts::ARCH);

        let mut missing_deps = Vec::new();
        if !all_deps.is_empty() {
            let pacman_t = Command::new("pacman")
                .arg("-T")
                .args(&all_deps)
                .kill_on_drop(true)
                .output()
                .await?;

            let missing_str = String::from_utf8_lossy(&pacman_t.stdout);
            for dep in missing_str.lines() {
                let dep = dep.trim();
                if !dep.is_empty() {
                    missing_deps.push(dep.to_string());
                }
            }
        }
        if let Some(sp) = dep_spinner {
            sp.finish_and_clear();
        }

        if !missing_deps.is_empty() {
            let mut repo_deps = Vec::new();
            let mut aur_deps = Vec::new();

            for dep in &missing_deps {
                let is_repo = Command::new("pacman")
                    .args(["-Sp", "--print-format", "%n", dep])
                    .stdin(Stdio::null())
                    .stdout(Stdio::null())
                    .stderr(Stdio::null())
                    .kill_on_drop(true)
                    .status()
                    .await
                    .is_ok_and(|s| s.success());
                if is_repo {
                    repo_deps.push(dep.clone());
                } else {
                    aur_deps.push(strip_dep_constraint(dep).to_string());
                }
            }

            if !repo_deps.is_empty() {
                let install_spinner = progress_tx.is_none().then(|| {
                    crate::ui::spinner(&format!(
                        "installing {} missing repo dependencies...",
                        repo_deps.len()
                    ))
                });
                emit_progress(
                    progress_tx,
                    Some(format!(
                        "installing {} build dependencies...",
                        repo_deps.len()
                    )),
                    Some(format!(":: installing repo deps: {}", repo_deps.join(" "))),
                )
                .await;

                let mut pac_args = vec![
                    "-S".to_string(),
                    "--asdeps".to_string(),
                    "--noconfirm".to_string(),
                    "--color=never".to_string(),
                ];
                pac_args.extend(repo_deps.iter().cloned());

                let res = run_priv_pacman(&pac_args, progress_tx.is_some()).await;
                if let Some(sp) = install_spinner {
                    sp.finish_and_clear();
                }
                if let Err(e) = res {
                    anyhow::bail!(
                        "failed to install missing build dependencies ({}): {e}",
                        repo_deps.join(" ")
                    );
                }
            }

            for aur_dep in aur_deps {
                let still_missing = Command::new("pacman")
                    .args(["-T", &aur_dep])
                    .kill_on_drop(true)
                    .status()
                    .await
                    .is_ok_and(|s| !s.success());
                if !still_missing {
                    continue;
                }

                let dep_archive =
                    build_internal(&aur_dep, is_verbose, progress_tx, visited).await?;
                emit_progress(
                    progress_tx,
                    Some(format!("installing aur dependency {aur_dep}...")),
                    Some(format!(":: installing aur dep {aur_dep}")),
                )
                .await;

                let u_args = vec![
                    "-U".to_string(),
                    "--asdeps".to_string(),
                    "--noconfirm".to_string(),
                    "--color=never".to_string(),
                    dep_archive.to_string_lossy().to_string(),
                ];
                if let Err(e) = run_priv_pacman(&u_args, progress_tx.is_some()).await {
                    anyhow::bail!("failed to install built AUR dependency '{aur_dep}': {e}");
                }
            }
        }

        if is_verbose && progress_tx.is_none() {
            println!(
                "{} [verbose] building {} with native output...",
                "::".blue(),
                pkg_name.bold()
            );
            let mut child = Command::new("makepkg")
                .current_dir(&pkg_dir)
                .args(["-cf", "--noconfirm", "--nocheck"])
                .stdin(Stdio::inherit())
                .stdout(Stdio::inherit())
                .stderr(Stdio::inherit())
                .kill_on_drop(true)
                .spawn()?;

            let status = child.wait().await?;
            if !status.success() {
                anyhow::bail!("makepkg failed with code {}", status.code().unwrap_or(1));
            }
        } else {
            let build_spinner = progress_tx
                .is_none()
                .then(|| crate::ui::spinner(&format!("preparing to build {}...", pkg_name.bold())));
            emit_progress(
                progress_tx,
                Some(format!("building {pkg_name}...")),
                Some(format!(":: building {pkg_name} with makepkg")),
            )
            .await;

            let mut child = Command::new("makepkg")
                .current_dir(&pkg_dir)
                .args(["-cf", "--noconfirm", "--nocheck"])
                .stdin(Stdio::null())
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .kill_on_drop(true)
                .spawn()?;

            let mut stdout = child
                .stdout
                .take()
                .ok_or_else(|| anyhow::anyhow!("failed to capture stdout"))?;
            let mut stderr = child
                .stderr
                .take()
                .ok_or_else(|| anyhow::anyhow!("failed to capture stderr"))?;

            let err_handle = tokio::spawn(async move {
                let mut err_str = String::new();
                let mut buf = [0u8; 1024];
                while let Ok(n) = stderr.read(&mut buf).await {
                    if n == 0 {
                        break;
                    }
                    err_str.push_str(&String::from_utf8_lossy(&buf[..n]));
                }
                err_str
            });

            let mut buf = [0u8; 128];
            let mut current_line = String::new();

            while let Ok(n) = stdout.read(&mut buf).await {
                if n == 0 {
                    break;
                }
                let chunk = String::from_utf8_lossy(&buf[..n]);

                for c in chunk.chars() {
                    if c == '\n' || c == '\r' {
                        let clean = current_line.trim();
                        if clean.starts_with("==> Making package:") {
                            if let Some(ref sp) = build_spinner {
                                sp.set_message(format!(
                                    "{} initializing build environment...",
                                    "::".blue()
                                ));
                            }
                            emit_progress(
                                progress_tx,
                                Some(format!("initializing build for {pkg_name}...")),
                                None,
                            )
                            .await;
                        } else if clean.starts_with("==> Retrieving sources") {
                            if let Some(ref sp) = build_spinner {
                                sp.set_message(format!(
                                    "{} downloading source code...",
                                    "::".blue()
                                ));
                            }
                            emit_progress(
                                progress_tx,
                                Some(format!("downloading sources for {pkg_name}...")),
                                None,
                            )
                            .await;
                        } else if clean.starts_with("==> Starting build()") {
                            if let Some(ref sp) = build_spinner {
                                sp.set_message(format!(
                                    "{} compiling {} (this may take a while)...",
                                    "::".blue(),
                                    pkg_name.bold()
                                ));
                            }
                            emit_progress(
                                progress_tx,
                                Some(format!("compiling {pkg_name}...")),
                                None,
                            )
                            .await;
                        } else if clean.starts_with("==> Starting package()") {
                            if let Some(ref sp) = build_spinner {
                                sp.set_message(format!("{} packaging binary...", "::".blue()));
                            }
                            emit_progress(
                                progress_tx,
                                Some(format!("packaging {pkg_name}...")),
                                None,
                            )
                            .await;
                        }
                        current_line.clear();
                    } else {
                        current_line.push(c);
                    }
                }
            }

            let status = child.wait().await?;
            if let Some(sp) = build_spinner {
                sp.finish_and_clear();
            }

            let err_output = err_handle.await.unwrap_or_default();

            if !status.success() {
                anyhow::bail!(
                    "makepkg failed (code {}):\n{}",
                    status.code().unwrap_or(1),
                    err_output.trim().red()
                );
            }
        }

        let pkglist_out = Command::new("makepkg")
            .arg("--packagelist")
            .current_dir(&pkg_dir)
            .kill_on_drop(true)
            .output()
            .await?;

        if pkglist_out.status.success()
            && let Some(path) =
                select_built_archive(&String::from_utf8_lossy(&pkglist_out.stdout), pkg_name)
        {
            return Ok(path);
        }

        anyhow::bail!("build succeeded but could not locate the .pkg.tar archive")
    })
}

fn aur_client() -> anyhow::Result<reqwest::Client> {
    // AUR RPC gates empty User-Agent requests behind an Anubis HTML challenge.
    reqwest::Client::builder()
        .user_agent(concat!("haj/", env!("CARGO_PKG_VERSION")))
        .build()
        .map_err(Into::into)
}

pub async fn search(query: &str) -> anyhow::Result<AurResponse> {
    let mut url = reqwest::Url::parse("https://aur.archlinux.org/rpc/v5/search/")?;
    url.path_segments_mut()
        .map_err(|()| anyhow::anyhow!("invalid base URL"))?
        .push(query);
    url.query_pairs_mut().append_pair("by", "name");

    let response = aur_client()?.get(url).send().await?.error_for_status()?;
    let data = response.json::<AurResponse>().await?;
    Ok(data)
}

pub async fn info(packages: &[&str]) -> anyhow::Result<AurResponse> {
    if packages.is_empty() {
        return Ok(AurResponse {
            results: Vec::new(),
        });
    }
    let mut url = reqwest::Url::parse("https://aur.archlinux.org/rpc/v5/info")?;
    {
        let mut qp = url.query_pairs_mut();
        for pkg in packages {
            qp.append_pair("arg[]", pkg);
        }
    }

    let response = aur_client()?.get(url).send().await?.error_for_status()?;
    let data = response.json::<AurResponse>().await?;
    Ok(data)
}

pub fn is_newer(remote: &str, local: &str) -> bool {
    crate::core::pacman::vercmp(remote, local) == std::cmp::Ordering::Greater
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_srcinfo_depends_handles_arch_and_dedup() {
        let srcinfo = "\
pkgbase = demo
\tdepends = glibc
\tdepends_x86_64 = zlib>=1.3
\tdepends_aarch64 = ignored-other-arch
\tmakedepends = cargo
\tmakedepends = glibc
\tmakedepends_x86_64 = git
";
        assert_eq!(
            parse_srcinfo_depends(srcinfo, "x86_64"),
            vec!["glibc", "zlib>=1.3", "cargo", "git"]
        );
        assert_eq!(strip_dep_constraint("zlib>=1.3"), "zlib");
    }

    #[test]
    fn test_select_built_archive_prefers_non_debug_existing_file() {
        let unique = format!("haj-aur-test-{}", std::process::id());
        let dir = std::env::temp_dir().join(unique);
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        let debug_pkg = dir.join("demo-debug-1.0-1-x86_64.pkg.tar.zst");
        let sibling_pkg = dir.join("demo-common-1.0-1-x86_64.pkg.tar.zst");
        let main_pkg = dir.join("demo-1.0-1-x86_64.pkg.tar.zst");
        std::fs::write(&debug_pkg, b"dbg").unwrap();
        std::fs::write(&sibling_pkg, b"common").unwrap();
        std::fs::write(&main_pkg, b"main").unwrap();

        let packagelist = format!(
            "{}\n{}\n{}\n",
            debug_pkg.display(),
            sibling_pkg.display(),
            main_pkg.display()
        );
        assert_eq!(select_built_archive(&packagelist, "demo"), Some(main_pkg));
        assert_eq!(
            select_built_archive(&packagelist, "demo-common"),
            Some(sibling_pkg)
        );
        let _ = std::fs::remove_dir_all(&dir);
    }
}