//! `aur-build` — the operator's command line (§7.2, §12). //! //! P0 ships the approval path as a CLI subcommand: the same code the web UI //! will call in P2, so the invariant "we build exactly what was displayed, or //! nothing" is enforced here too. `approve` renders the review, prints it, and //! then approves with the hashes it just displayed — it cannot approve a diff it //! did not show you. 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, }, } fn main() -> anyhow::Result<()> { let cli = Cli::parse(); let cfg = match &cli.root { Some(r) => Config::load(r).unwrap_or_else(|_| Config { root: r.clone(), ..Config::default() }), None => Config::load(&Config::default().root)?, }; 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); let _server = aur_build::http::spawn(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, subscription_state::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 == subscription_state::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(stale) => { eprintln!("refused: {stale}"); std::process::exit(2) } } } 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, &[build_state::QUEUED, build_state::RUNNING, build_state::LEASED, build_state::BLOCKED_MISSING_DEP], 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(()) } } } 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}")) }