use std::path::PathBuf; use clap::{Parser, Subcommand}; use aur_build::config::Config; use aur_build::db::{self, builds, model::*}; use aur_build::pipeline; use aur_build::review::{approve as ap, candidates, diff}; #[derive(Parser)] #[command(name = "aur-build", version, about = "AUR build server: nothing is published that a human did not approve")] struct Cli { /// Server root (holds config.json, db, mirrors, repo). #[arg(short, long, env = "AUR_BUILD_ROOT", global = true)] root: Option, #[command(subcommand)] cmd: Cmd, } #[derive(Subcommand)] enum Cmd { /// Create the root, config and database. Init { #[arg(long)] repo: Option, #[arg(long)] signing_key: Option, }, /// Start watching a pkgbase. Subscribe { pkgbase: String, /// Override the AUR URL; a `file://` path is fine, which is how the /// test suite drives the real binary. #[arg(long)] url: Option, }, /// Stop watching a pkgbase. Unsubscribe { pkgbase: String }, /// Poll AUR now (without this, detection runs on the watcher's schedule). Detect { pkgbase: Option }, /// List reviews. Reviews { #[arg(long)] all: bool, }, /// Show one review: the diff panels and the two hashes an approval must echo. Show { candidate: i64 }, /// Approve a review. Without --yes this only prints what would be approved. Approve { candidate: i64, #[arg(long)] yes: bool, #[arg(long)] note: Option, /// Approve against hashes you were shown earlier instead of re-rendering. #[arg(long)] identity: Option, #[arg(long)] diff: Option, }, /// Reject a review with a reason. Reject { candidate: i64, #[arg(long)] note: String, }, /// Queue a build for a pending review. Build { candidate: i64 }, /// Queue a rebuild of the currently accepted version (no new approval, I6). Rebuild { pkgbase: String }, /// Run a queued build to completion in this process. Run { build: String }, /// List builds. Builds, /// Show a build's step timeline. Status { build: String }, /// Show the current index. Packages, /// Run the web server and the watcher until interrupted. Serve { /// Override the bind address, e.g. 127.0.0.1:8484. #[arg(long)] bind: Option, }, /// Show recent audit rows. Audit { #[arg(long, default_value_t = 30)] limit: i64, }, /// Print metrics in Prometheus text format (the same numbers /metrics serves). Metrics, /// Drop the files of releases beyond the retention window, and sweep /// abandoned staging directories. Rows are never deleted (§15). Gc { /// Versions per pkgbase whose files are kept. Defaults to the /// `retention_versions` setting. #[arg(long)] keep: Option, /// Show what would be removed without removing it. #[arg(long)] dry_run: bool, }, /// Write a consistent snapshot of the database with `VACUUM INTO`. Backup { /// Destination file. It must not already exist: a backup that silently /// overwrites last week's backup is not a backup. to: PathBuf, }, } fn main() -> anyhow::Result<()> { let cli = Cli::parse(); // `init` is the only command that runs before a config exists. For everything // else a missing config is an error, not a reason to invent one: the old // unconditional fallback turned a typo'd `--root` into a fresh empty server // at the wrong path. let root = cli.root.clone().unwrap_or_else(|| Config::default().root); let cfg = if matches!(cli.cmd, Cmd::Init { .. }) { Config::load(&root).unwrap_or_else(|_| Config { root: root.clone(), ..Config::default() }) } else { Config::load(&root)? }; // Startup, not first-build: a configuration that cannot work is refused // before the watcher, the dispatcher or the UI are up and looking healthy. cfg.validate()?; if let Cmd::Serve { bind } = &cli.cmd { let mut cfg = cfg; if let Some(b) = bind { cfg.bind = b.clone(); } cfg.ensure_dirs()?; db::migrate(&cfg.db_path())?; let db = db::Db::open_migrated(&cfg.db_path())?; db::ensure_repo( &db.writer, &cfg.repo_name, &cfg.repo_arch_dir().display().to_string(), &cfg.arch, &cfg.signing_key_id, )?; // Re-materialize the served index from the DB: if a crash left the file // behind the database, close the gap before anyone asks for it. let _ = pipeline::publish::reconcile(&cfg, &db); let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); aur_build::watch::scheduler::spawn_scheduler(std::sync::Arc::new(cfg.clone()), db.clone(), stop.clone()); let _server = aur_build::http::spawn(cfg.clone(), db.clone())?; // The dispatcher reaps expired leases before its first claim, so a restart // recovers whatever a crash left leased (§8.2). let _pool = aur_build::pipeline::dispatch::Pool::spawn(std::sync::Arc::new(cfg.clone()), db.clone()); println!("serving on http://{} — ctrl-c to stop", cfg.bind); // Single process, thread per connection: the main thread has nothing to // do but wait to be killed. loop { std::thread::sleep(std::time::Duration::from_secs(3600)); } } let ctx = Ctx::open(&cfg)?; match cli.cmd { // Handled above, before the CLI's own database context is opened. Cmd::Serve { .. } => Ok(()), Cmd::Init { repo, signing_key } => { let mut cfg = cfg; if let Some(r) = repo { cfg.repo_name = r; } if let Some(k) = signing_key { cfg.signing_key_id = k; } cfg.save()?; cfg.ensure_dirs()?; db::migrate(&cfg.db_path())?; let db = db::Db::open_migrated(&cfg.db_path())?; let rid = db::ensure_repo( &db.writer, &cfg.repo_name, &cfg.repo_arch_dir().display().to_string(), &cfg.arch, &cfg.signing_key_id, )?; println!("initialized {} (repo id {rid})", cfg.root.display()); println!("add to pacman.conf:\n [{}]\n Server = {}/$repo/os/$arch", cfg.repo_name, cfg.base_url); Ok(()) } Cmd::Subscribe { pkgbase, url } => { let rid = db::repo_id(&ctx.db)?; let url = url.unwrap_or_else(|| format!("https://aur.archlinux.org/{pkgbase}.git")); db::subscribe(&ctx.db.writer, rid, &pkgbase, &url)?; println!("subscribed {pkgbase} ({url})"); Ok(()) } Cmd::Unsubscribe { pkgbase } => { db::set_subscription_state(&ctx.db.writer, &pkgbase, SubscriptionState::Removed)?; println!("unsubscribed {pkgbase}"); Ok(()) } Cmd::Detect { pkgbase } => { let names: Vec = match pkgbase { Some(n) => vec![n], None => db::list_subscriptions(&ctx.db)? .into_iter() .filter(|s| s.state == SubscriptionState::Active) .map(|s| s.pkgbase) .collect(), }; for n in names { match aur_build::watch::detect::check_pkgbase(&cfg, &ctx.db, &n) { Ok(r) => println!("{n}: {:?}", r.outcome), Err(e) => eprintln!("{n}: {e}"), } } Ok(()) } Cmd::Reviews { all } => { let rows = if all { candidates::all_candidates(&ctx.db)? } else { candidates::pending_candidates(&ctx.db)? }; if rows.is_empty() { println!("nothing pending"); } for c in rows { println!( "#{:<5} {:<28} {:<16} {:<10} rev{} {}", c.id, c.pkgbase, aur_build::pkgver::full_version(&c.epoch, &c.pkgver, &c.pkgrel), c.kind, c.revision, c.state ); } Ok(()) } Cmd::Show { candidate } => { let c = need_candidate(&ctx.db, candidate)?; let (text, digest) = diff::render_current(&ctx.db, &cfg, &c)?; candidates::set_diff_digest(&ctx.db, c.id, &digest)?; candidates::mark_viewed(&ctx.db, c.id)?; println!("{text}"); println!("---"); println!("identity_hash: {}", c.identity_hash); println!("diff_digest: {digest}"); println!("approve with: aur-build approve {} --yes", c.id); Ok(()) } Cmd::Approve { candidate, yes, note, identity, diff: diff_arg } => { let c = need_candidate(&ctx.db, candidate)?; // Render first, always: the hashes we send are the hashes of what we // just rendered, unless the operator explicitly names older ones. let (text, digest) = diff::render_current(&ctx.db, &cfg, &c)?; candidates::set_diff_digest(&ctx.db, c.id, &digest)?; let identity = identity.unwrap_or_else(|| c.identity_hash.clone()); let diff_arg = diff_arg.unwrap_or(digest); println!("{text}"); println!("---"); if !yes { println!("not approved: re-run with --yes to approve exactly this"); return Ok(()); } let who = whoami(); match ap::approve(&ctx.db, &who, c.id, &identity, &diff_arg, note.as_deref()) { Ok(a) => { println!("approved #{} (approval {})", c.id, a.id); let id = pipeline::enqueue_for_candidate(&cfg, &ctx.db, &c)?; println!("queued build {id}"); println!("run it with: aur-build run {id}"); Ok(()) } Err(ap::ApproveError::Stale(stale)) => { eprintln!("refused: {stale}"); std::process::exit(2) } Err(ap::ApproveError::System(e)) => Err(e.into()), } } Cmd::Reject { candidate, note } => { let c = need_candidate(&ctx.db, candidate)?; let who = whoami(); ap::reject(&ctx.db, &who, c.id, ¬e)?; println!("rejected #{}", c.id); Ok(()) } Cmd::Build { candidate } => { let c = need_candidate(&ctx.db, candidate)?; let id = pipeline::enqueue_for_candidate(&cfg, &ctx.db, &c)?; println!("queued build {id}"); Ok(()) } Cmd::Rebuild { pkgbase } => { let id = pipeline::enqueue_manual_rebuild(&cfg, &ctx.db, &pkgbase)?; println!("queued rebuild {id}"); Ok(()) } Cmd::Run { build } => match pipeline::run(&cfg, &ctx.db, &build)? { pipeline::Outcome::Succeeded { release_id } => { println!("succeeded (release {release_id})"); Ok(()) } pipeline::Outcome::Blocked { on } => { println!("blocked on: {}", on.join(", ")); std::process::exit(3) } pipeline::Outcome::Cancelled => { println!("cancelled"); std::process::exit(0) } pipeline::Outcome::Failed { step, error, .. } => { eprintln!("failed at {step}: {error}"); std::process::exit(1) } }, Cmd::Builds => { for b in builds::list(&ctx.db, BuildState::active(), 50)? { println!("{:<66} {:<20} {}", b.id, b.state, b.current_step.unwrap_or_default()); } Ok(()) } Cmd::Status { build } => { for s in builds::steps(&ctx.db, &build)? { println!("{:<12} {:<12} {}", s.step, s.status, s.error.unwrap_or_default()); } Ok(()) } Cmd::Packages => { for p in db::index_packages(&ctx.db)? { println!("{:<28} {:<16} {}", p.name, p.version, p.arch); } Ok(()) } Cmd::Audit { limit } => { for a in db::list_audit(&ctx.db, limit)? { println!("{} [{}] {} {} {} {}", a.at, a.actor_kind, a.actor, a.action, a.entity_id, a.detail_json); } Ok(()) } Cmd::Metrics => { print!("{}", aur_build::ops::metrics(&cfg, &ctx.db)?.to_prometheus()); Ok(()) } Cmd::Gc { keep, dry_run } => { let keep = keep.unwrap_or(aur_build::ops::DEFAULT_KEEP); if dry_run { let (kept, evict) = aur_build::ops::plan_retention(&ctx.db, keep)?; println!("retention: keep {keep} version(s) per pkgbase"); println!(" {} release(s) keep their files", kept.len()); for e in evict { let files = aur_build::ops::release_files(&cfg, &ctx.db, e.release_id)?; println!(" release {} would lose {} file(s)", e.release_id, files.len()); for f in files { println!(" {}", f.display()); } } return Ok(()); } let r = aur_build::ops::retention(&cfg, &ctx.db, Some(keep))?; println!( "kept {} release(s), evicted {}, removed {} file(s), freed {} bytes, swept {} staging dir(s)", r.releases_kept, r.releases_evicted, r.files_removed, r.bytes_freed, r.staging_swept ); Ok(()) } Cmd::Backup { to } => { let path = aur_build::ops::backup(&ctx.db, &to)?; println!( "wrote {} bytes to {} (VACUUM INTO, single file, no WAL)", std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0), path.display() ); Ok(()) } } } struct Ctx { db: db::Db, } impl Ctx { fn open(cfg: &Config) -> anyhow::Result { cfg.ensure_dirs()?; db::migrate(&cfg.db_path())?; let db = db::Db::open_migrated(&cfg.db_path())?; db::ensure_repo( &db.writer, &cfg.repo_name, &cfg.repo_arch_dir().display().to_string(), &cfg.arch, &cfg.signing_key_id, )?; Ok(Self { db }) } } fn whoami() -> String { std::env::var("USER").or_else(|_| std::env::var("USERNAME")).unwrap_or_else(|_| "cli".into()) } fn need_candidate(db: &db::Db, id: i64) -> anyhow::Result { candidates::candidate_by_id(db, id)? .ok_or_else(|| anyhow::anyhow!("no candidate #{id}")) }