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> {
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);
}
}