summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authoraur-build <aur-build@localhost>2026-11-18 07:16:36 +0000
committeraur-build <aur-build@localhost>2026-11-18 07:16:36 +0000
commit0b3cb443e70b46ec61455255c3ddfc2a26997613 (patch)
tree457d5e0bf3b1733b79829de3c146e1cabcc85e8c /src
parentd7c386a703a9b69211d83854547218d6e1da9a51 (diff)
downloadaur-build-0b3cb443e70b46ec61455255c3ddfc2a26997613.tar.gz
aur-build-0b3cb443e70b46ec61455255c3ddfc2a26997613.zip
watch: two-stage VCS watcher — ls-remote probe, pkgver() resolution, pin capture (§5.2)
Stage A probes every VCS source in source=() with git ls-remote, respecting #commit/#tag/#branch fragments, and returns one UpstreamPin per source. If the tip set equals the accepted release's pins, nothing can have changed and Stage B never runs — the common case costs one round trip per source and no clone. svn/hg have no cheap universal probe, so they are reported as unprobed and force Stage B rather than being silently treated as unchanged. Stage B runs only on movement: it fetches into a persistent vcs_cache (rather than re-cloning a multi-gigabyte upstream daily), runs makepkg --vercheck, and captures the pins from the clone it already has. Results are cached on (pkgbase, recipe_hash, upstream_tip) with a per-pkgbase cooldown, and a process-wide slot cap bounds concurrent resolutions. The resolved epoch:pkgver-pkgrel plus the pins go into identity_hash, so a different commit is a different thing to approve. Also fixes a misclassification the new path exposed: a VCS source's digest is its pin, so upstream movement showed up as an integrity_alert. Integrity events are now restricted to fixed downloads; VCS movement under a frozen pkgver is pin_drift, as §5.2 specifies. New fixtures git-multi (two upstreams) and git-tagged (#tag pin). 10 tests in tests/vcs.rs.
Diffstat (limited to 'src')
-rw-r--r--src/db/migrations.rs22
-rw-r--r--src/db/queries.rs85
-rw-r--r--src/error.rs10
-rw-r--r--src/watch/detect.rs62
-rw-r--r--src/watch/mod.rs1
-rw-r--r--src/watch/upstream.rs293
6 files changed, 462 insertions, 11 deletions
diff --git a/src/db/migrations.rs b/src/db/migrations.rs
index 8ba925c..bb8974f 100644
--- a/src/db/migrations.rs
+++ b/src/db/migrations.rs
@@ -299,6 +299,26 @@ BEGIN
END;
"#;
+/// Stage B results, keyed on `(pkgbase, recipe_hash, upstream_tip)` (§5.2).
+/// Re-resolving means cloning an upstream repo and running makepkg, so the
+/// answer is worth keeping; the same key also implements the per-pkgbase
+/// cooldown, because a fresh tip inside the window reuses the old answer.
+const M_0007_STAGE_B_CACHE: &str = r#"
+CREATE TABLE stage_b_cache (
+ pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id),
+ recipe_hash TEXT NOT NULL,
+ tip_hash TEXT NOT NULL,
+ epoch TEXT NOT NULL,
+ pkgver TEXT NOT NULL,
+ pkgrel TEXT NOT NULL,
+ pins_json TEXT NOT NULL,
+ resolved_at TEXT NOT NULL,
+ PRIMARY KEY (pkgbase_id, recipe_hash, tip_hash)
+);
+
+CREATE INDEX stage_b_cache_by_pkgbase ON stage_b_cache (pkgbase_id, resolved_at);
+"#;
+
pub static MIGRATIONS: &[Migration] = &[
Migration { version: 1, name: "core", sql: M_0001_CORE },
Migration { version: 2, name: "build", sql: M_0002_BUILD },
@@ -306,6 +326,7 @@ pub static MIGRATIONS: &[Migration] = &[
Migration { version: 4, name: "audit-triggers", sql: M_0004_TRIGGERS },
Migration { version: 5, name: "artifact-build", sql: M_0005_ARTIFACT_BUILD },
Migration { version: 6, name: "approval-immutable", sql: M_0006_APPROVAL_IMMUTABLE },
+ Migration { version: 7, name: "stage-b-cache", sql: M_0007_STAGE_B_CACHE },
];
/// Default settings seeded into `settings` (DESIGN.md §11).
@@ -314,6 +335,7 @@ pub const DEFAULT_SETTINGS: &[(&str, &str)] = &[
("build_timeout", "5400"),
("poll_interval", "86400"),
("stage_b_cooldown", "86400"),
+ ("stage_b_concurrency", "1"),
("retention_versions", "3"),
("dry_run", "0"),
("review_budget_days", "14"),
diff --git a/src/db/queries.rs b/src/db/queries.rs
index b1f7e4d..fe3109a 100644
--- a/src/db/queries.rs
+++ b/src/db/queries.rs
@@ -575,6 +575,91 @@ pub fn our_package_names(db: &Db) -> Result<std::collections::BTreeSet<String>>
})
}
+// --------------------------------------------------------- stage B cache --
+
+/// Exact cache hit: same recipe, same upstream tips (§5.2).
+pub fn stage_b_cache_get(db: &Db, pkgbase_id: i64, recipe_hash: &str, tip_hash: &str) -> Result<Option<crate::watch::upstream::StageB>> {
+ let (rh, th) = (recipe_hash.to_string(), tip_hash.to_string());
+ db.read(move |c| {
+ use rusqlite::OptionalExtension;
+ Ok(c.query_row(
+ "SELECT epoch, pkgver, pkgrel, pins_json FROM stage_b_cache
+ WHERE pkgbase_id=?1 AND recipe_hash=?2 AND tip_hash=?3",
+ params![pkgbase_id, rh, th],
+ |r| {
+ Ok((
+ r.get::<_, String>(0)?,
+ r.get::<_, String>(1)?,
+ r.get::<_, String>(2)?,
+ r.get::<_, String>(3)?,
+ ))
+ },
+ )
+ .optional()?
+ .map(|(epoch, pkgver, pkgrel, pins_json)| crate::watch::upstream::StageB {
+ epoch,
+ pkgver,
+ pkgrel,
+ pins: serde_json::from_str(&pins_json).unwrap_or_default(),
+ cached: true,
+ }))
+ })
+}
+
+/// The most recent answer for this pkgbase, if it is inside the cooldown window.
+pub fn stage_b_recent(db: &Db, pkgbase_id: i64, cooldown_secs: i64) -> Result<Option<crate::watch::upstream::StageB>> {
+ let cutoff = crate::time::secs_ago(cooldown_secs);
+ db.read(move |c| {
+ use rusqlite::OptionalExtension;
+ Ok(c.query_row(
+ "SELECT epoch, pkgver, pkgrel, pins_json FROM stage_b_cache
+ WHERE pkgbase_id=?1 AND resolved_at > ?2
+ ORDER BY resolved_at DESC LIMIT 1",
+ params![pkgbase_id, cutoff],
+ |r| {
+ Ok((
+ r.get::<_, String>(0)?,
+ r.get::<_, String>(1)?,
+ r.get::<_, String>(2)?,
+ r.get::<_, String>(3)?,
+ ))
+ },
+ )
+ .optional()?
+ .map(|(epoch, pkgver, pkgrel, pins_json)| crate::watch::upstream::StageB {
+ epoch,
+ pkgver,
+ pkgrel,
+ pins: serde_json::from_str(&pins_json).unwrap_or_default(),
+ cached: true,
+ }))
+ })
+}
+
+pub fn stage_b_cache_put(
+ db: &Db,
+ pkgbase_id: i64,
+ recipe_hash: &str,
+ tip_hash: &str,
+ r: &crate::watch::upstream::StageB,
+) -> Result<()> {
+ let (rh, th) = (recipe_hash.to_string(), tip_hash.to_string());
+ let (epoch, pkgver, pkgrel) = (r.epoch.clone(), r.pkgver.clone(), r.pkgrel.clone());
+ let pins = serde_json::to_string(&r.pins)?;
+ let at = crate::time::now();
+ db.writer.tx(move |tx| {
+ tx.execute(
+ "INSERT INTO stage_b_cache (pkgbase_id, recipe_hash, tip_hash, epoch, pkgver, pkgrel, pins_json, resolved_at)
+ VALUES (?1,?2,?3,?4,?5,?6,?7,?8)
+ ON CONFLICT(pkgbase_id, recipe_hash, tip_hash) DO UPDATE SET
+ epoch=excluded.epoch, pkgver=excluded.pkgver, pkgrel=excluded.pkgrel,
+ pins_json=excluded.pins_json, resolved_at=excluded.resolved_at",
+ params![pkgbase_id, rh, th, epoch, pkgver, pkgrel, pins, at],
+ )?;
+ Ok(())
+ })
+}
+
// ----------------------------------------------------------------- notice --
pub fn put_notice(
diff --git a/src/error.rs b/src/error.rs
index a60843c..ac47fc8 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -30,6 +30,11 @@ pub enum Error {
Invalid(String),
#[error("blocked: {0}")]
Blocked(String),
+ /// A failure the outside world caused and a retry may clear: an unreachable
+ /// upstream, a half-written mirror. Distinct from a deterministic failure,
+ /// which must never be retried into a different answer (§8.4).
+ #[error("transient: {0}")]
+ Transient(String),
#[error("{0}")]
Other(String),
}
@@ -59,11 +64,14 @@ impl Error {
pub fn other(s: impl fmt::Display) -> Self {
Error::Other(s.to_string())
}
+ pub fn transient(s: impl fmt::Display) -> Self {
+ Error::Transient(s.to_string())
+ }
/// True when a retry could plausibly help (network, mirror 5xx). Deterministic
/// build failures must not auto-retry (§8.4).
pub fn is_transient(&self) -> bool {
- matches!(self, Error::Http(_) | Error::Io(_))
+ matches!(self, Error::Http(_) | Error::Io(_) | Error::Transient(_))
}
}
diff --git a/src/watch/detect.rs b/src/watch/detect.rs
index e00a2f9..d5f5c46 100644
--- a/src/watch/detect.rs
+++ b/src/watch/detect.rs
@@ -118,14 +118,47 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor
let tree = read_tree(&mirror, head)?;
let recipe = recipe_from_tree(&tree.files)?;
let recipe_hash = tree.recipe_hash();
- let digests = resolve_sources(cfg, db, &mirror, head, &tree, &recipe, &[])?;
- let pins: Vec<UpstreamPin> = Vec::new(); // P1 fills this in for VCS sources
+
+ // §5.2, the two-stage funnel. Stage A is one `ls-remote` per VCS source and
+ // costs no clone; if the tip set is what the accepted release was built
+ // from, nothing can have changed and Stage B never runs.
+ let has_vcs = recipe.source_entries.iter().any(|e| e.is_vcs());
+ let accepted_pins: Vec<UpstreamPin> = accepted.as_ref().map(|a| a.pins()).unwrap_or_default();
+ // A recipe with no VCS sources states its own version; there is nothing to
+ // probe and nothing to resolve.
+ let stage_a = if has_vcs {
+ Some(crate::watch::upstream::probe(&recipe, &accepted_pins)?)
+ } else {
+ None
+ };
+ let resolved = if !has_vcs {
+ None
+ } else if stage_a.as_ref().unwrap().needs_stage_b() {
+ crate::watch::upstream::resolve(cfg, db, pb, &recipe, &recipe_hash, stage_a.as_ref().unwrap())?
+ } else {
+ // Upstream has not moved. The version we serve is still the answer, and
+ // reusing its pins is what makes the next pass cheap too.
+ accepted.as_ref().map(|a| crate::watch::upstream::StageB {
+ epoch: a.epoch.clone(),
+ pkgver: a.pkgver.clone(),
+ pkgrel: a.pkgrel.clone(),
+ pins: accepted_pins.clone(),
+ cached: true,
+ })
+ };
+ // For a VCS package the literal `pkgver=` is frozen; the resolved one is the
+ // only version a consumer could actually install.
+ let (epoch, pkgver, pkgrel, pins) = match &resolved {
+ Some(r) => (r.epoch.clone(), r.pkgver.clone(), r.pkgrel.clone(), r.pins.clone()),
+ None => (recipe.epoch.clone(), recipe.pkgver.clone(), recipe.pkgrel.clone(), Vec::new()),
+ };
+ let digests = resolve_sources(cfg, db, &mirror, head, &tree, &recipe, &pins)?;
let identity = Identity {
aur_commit: head.to_string(),
- epoch: recipe.epoch.clone(),
- pkgver: recipe.pkgver.clone(),
- pkgrel: recipe.pkgrel.clone(),
+ epoch: epoch.clone(),
+ pkgver: pkgver.clone(),
+ pkgrel: pkgrel.clone(),
upstream_pins: pins.clone(),
source_digests: digests.clone(),
};
@@ -141,9 +174,9 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor
let nc = NewCandidate {
snapshot_id: snap_id,
- epoch: recipe.epoch.clone(),
- pkgver: recipe.pkgver.clone(),
- pkgrel: recipe.pkgrel.clone(),
+ epoch: epoch.clone(),
+ pkgver: pkgver.clone(),
+ pkgrel: pkgrel.clone(),
upstream_pins_json: serde_json::to_string(&pins)?,
source_digests_json: serde_json::to_string(&digests)?,
identity_hash: identity_hash.clone(),
@@ -216,9 +249,19 @@ fn non_publishable(
// A local source is part of the recipe: when its bytes move, that *is* the
// recipe drift, not an integrity event. The integrity alert is specifically
// "the bytes upstream serves no longer match what we built" (§5.3).
+ // A VCS source's digest *is* its pin, so upstream moving shows up there too
+ // — but that is ordinary drift, handled by the pin check below, not an
+ // integrity event. Integrity means "the bytes we built are gone and the
+ // version says nothing moved", which only applies to fixed downloads.
+ let vcs_indices: std::collections::BTreeSet<usize> = recipe
+ .source_entries
+ .iter()
+ .filter(|e| e.is_vcs())
+ .map(|e| e.index)
+ .collect();
let changed_remote: Vec<&SourceDigest> = new_digests
.iter()
- .filter(|n| n.kind != "local")
+ .filter(|n| n.kind != "local" && !vcs_indices.contains(&n.index))
.filter(|n| match old_digests.iter().find(|o| o.index == n.index) {
Some(o) => o.digest != n.digest,
None => true,
@@ -271,7 +314,6 @@ fn non_publishable(
}
// The recipe drifted under a static version: the maintainer probably forgot
// to bump pkgrel, and the user should know.
- let _ = recipe;
db::put_notice_once(
&db.writer,
pb.id,
diff --git a/src/watch/mod.rs b/src/watch/mod.rs
index 3f0d217..2016166 100644
--- a/src/watch/mod.rs
+++ b/src/watch/mod.rs
@@ -5,6 +5,7 @@ pub mod detect;
pub mod digests;
pub mod mirror;
pub mod scheduler;
+pub mod upstream;
pub use detect::{check_pkgbase, CheckReport, Outcome};
pub use digests::{cached_path, download_and_cache, resolve_sources, skip_on_non_vcs};
diff --git a/src/watch/upstream.rs b/src/watch/upstream.rs
new file mode 100644
index 0000000..442647c
--- /dev/null
+++ b/src/watch/upstream.rs
@@ -0,0 +1,293 @@
+//! The two-stage VCS watcher (§5.2) — the expensive path, made cheap.
+//!
+//! For a `-git` package the `pkgver=` field is frozen and the real version is
+//! computed by `pkgver()` at build time, so detection cannot read it off the
+//! recipe. Running the real thing every poll would be absurd, so:
+//!
+//! **Stage A** asks each upstream where its tip is now (`git ls-remote`, which
+//! costs one network round trip and no clone). If the set of tips is identical
+//! to the set recorded on the accepted release, *nothing can have changed* and
+//! we stop. This is the common case: most days, nothing moves.
+//!
+//! **Stage B** runs only when Stage A saw movement: clone/fetch into the
+//! persistent cache, run `makepkg --vercheck` against the recipe, and read back
+//! the computed `epoch:pkgver-pkgrel` — the only correct answer, because
+//! `pkgver()` can do arbitrary things. The clone is already there, so this is
+//! also where the pins are captured.
+
+use std::collections::BTreeSet;
+use std::path::PathBuf;
+use std::process::Command;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Condvar, Mutex};
+
+use crate::config::Config;
+use crate::db::{self, model::*, Db, Pkgbase};
+use crate::error::{Error, Result};
+use crate::git;
+
+/// What Stage A found.
+#[derive(Debug, Clone)]
+pub struct StageA {
+ /// One pin per VCS source, in `source=()` order.
+ pub pins: Vec<UpstreamPin>,
+ /// URLs we could not probe cheaply (svn, hg, or a dead remote). Treated as
+ /// "assume it moved" — we would rather run Stage B than miss a release.
+ pub unprobed: Vec<String>,
+ /// True when the tip set differs from the accepted release's pins.
+ pub moved: bool,
+}
+
+impl StageA {
+ /// Stage B is worth running: something upstream moved, or we cannot prove
+ /// that nothing did.
+ pub fn needs_stage_b(&self) -> bool {
+ self.moved || !self.unprobed.is_empty()
+ }
+}
+
+/// Probe every VCS source in the recipe. **Every** one, not just the first: a
+/// pkgbase can build from two upstream repos and either can move alone.
+pub fn probe(recipe: &Recipe, accepted: &[UpstreamPin]) -> Result<StageA> {
+ let mut pins = Vec::new();
+ let mut unprobed = Vec::new();
+ for entry in recipe.source_entries.iter().filter(|e| e.is_vcs()) {
+ let want = if let Some(c) = &entry.commit {
+ // Pinned to a commit by the recipe itself: it cannot move.
+ pins.push(UpstreamPin {
+ index: entry.index,
+ url: entry.url.clone(),
+ ref_: format!("commit={c}"),
+ branch: entry.branch.clone(),
+ commit: c.clone(),
+ });
+ continue;
+ } else if let Some(t) = &entry.tag {
+ (format!("refs/tags/{t}"), t.clone())
+ } else if let Some(b) = &entry.branch {
+ (format!("refs/heads/{b}"), b.clone())
+ } else {
+ ("HEAD".into(), "HEAD".into())
+ };
+
+ match entry.vcs.as_deref() {
+ Some("git") | None => {
+ let sha = match want.0.as_str() {
+ "HEAD" => git::ls_remote_head(&entry.url)?,
+ refname => git::ls_remote_ref(&entry.url, refname)?,
+ };
+ match sha {
+ Some(sha) => pins.push(UpstreamPin {
+ index: entry.index,
+ url: entry.url.clone(),
+ ref_: want.1,
+ branch: entry.branch.clone(),
+ commit: sha,
+ }),
+ // The remote is gone or the ref vanished: that is movement
+ // we must not swallow, and Stage B will report it properly.
+ None => unprobed.push(entry.url.clone()),
+ }
+ }
+ // svn/hg/bzr: no cheap universal probe. Be honest about it and let
+ // Stage B decide, rather than claiming nothing moved.
+ Some(other) => {
+ unprobed.push(format!("{other}:{}", entry.url));
+ pins.push(UpstreamPin {
+ index: entry.index,
+ url: entry.url.clone(),
+ ref_: want.1,
+ branch: entry.branch.clone(),
+ commit: String::new(),
+ });
+ }
+ }
+ }
+ let now: BTreeSet<(usize, String)> = pins.iter().map(|p| (p.index, p.commit.clone())).collect();
+ let then: BTreeSet<(usize, String)> = accepted.iter().map(|p| (p.index, p.commit.clone())).collect();
+ Ok(StageA { pins, unprobed, moved: now != then })
+}
+
+/// What Stage B produced: the authoritative version plus the pins it was
+/// computed from.
+#[derive(Debug, Clone)]
+pub struct StageB {
+ pub epoch: String,
+ pub pkgver: String,
+ pub pkgrel: String,
+ pub pins: Vec<UpstreamPin>,
+ /// True when the answer came from the cache instead of a fresh resolution.
+ pub cached: bool,
+}
+
+impl StageB {
+ pub fn version(&self) -> String {
+ crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel)
+ }
+}
+
+/// A process-wide cap on concurrent Stage B resolutions (§5.2 "a global
+/// concurrency cap"). Each one clones repositories and runs a chroot-less
+/// makepkg; letting twenty run at once would be silly.
+static RUNNING: AtomicUsize = AtomicUsize::new(0);
+static SLOT_FREE: Condvar = Condvar::new();
+static SLOT_LOCK: Mutex<()> = Mutex::new(());
+
+pub struct StageBSlot(());
+
+impl StageBSlot {
+ /// Take a Stage B slot, blocking until one is free.
+ pub fn acquire(cap: usize) -> Self {
+ let cap = cap.max(1);
+ let guard = SLOT_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ let mut guard = guard;
+ loop {
+ let n = RUNNING.load(Ordering::SeqCst);
+ if n < cap {
+ RUNNING.fetch_add(1, Ordering::SeqCst);
+ drop(guard);
+ return StageBSlot(());
+ }
+ guard = SLOT_FREE.wait(guard).unwrap_or_else(|e| e.into_inner());
+ }
+ }
+}
+
+impl Drop for StageBSlot {
+ fn drop(&mut self) {
+ RUNNING.fetch_sub(1, Ordering::SeqCst);
+ SLOT_FREE.notify_one();
+ }
+}
+
+/// Stage B: resolve the real `pkgver` for a VCS pkgbase.
+///
+/// `None` means "there is nothing to resolve" — the recipe has no VCS sources,
+/// so the literal `pkgver=` is already the answer.
+pub fn resolve(
+ cfg: &Config,
+ db: &Db,
+ pb: &Pkgbase,
+ recipe: &Recipe,
+ recipe_hash: &str,
+ stage_a: &StageA,
+) -> Result<Option<StageB>> {
+ if !recipe.source_entries.iter().any(|e| e.is_vcs()) {
+ return Ok(None);
+ }
+ let tip_hash = tip_hash(&stage_a.pins);
+
+ // Cache hit: same recipe, same upstream tips. Keyed on
+ // (pkgbase, recipe_hash, upstream_tip) exactly as §5.2 asks.
+ if let Some(hit) = db::stage_b_cache_get(db, pb.id, recipe_hash, &tip_hash)? {
+ return Ok(Some(hit));
+ }
+
+ // Per-pkgbase cooldown: even if the tips moved again, we do not re-resolve
+ // the same pkgbase more than once per cooldown window. The previous answer
+ // is reused, so a chatty upstream cannot turn detection into a build loop.
+ let cooldown = db::setting_i64(db, "stage_b_cooldown", 86400);
+ if let Some(recent) = db::stage_b_recent(db, pb.id, cooldown)? {
+ return Ok(Some(recent));
+ }
+
+ let _slot = StageBSlot::acquire(db::setting_i64(db, "stage_b_concurrency", 1) as usize);
+ let resolved = run(cfg, db, pb, recipe, recipe_hash, &tip_hash, stage_a)?;
+ db::stage_b_cache_put(db, pb.id, recipe_hash, &tip_hash, &resolved)?;
+ Ok(Some(resolved))
+}
+
+/// The actual work: warm the clone cache, then ask `makepkg` what it computes.
+fn run(
+ cfg: &Config,
+ db: &Db,
+ pb: &Pkgbase,
+ recipe: &Recipe,
+ recipe_hash: &str,
+ tip_hash: &str,
+ stage_a: &StageA,
+) -> Result<StageB> {
+ // Clone reuse: fetch into a persistent bare cache rather than re-cloning a
+ // multi-gigabyte upstream every day (§5.2).
+ let mut pins = stage_a.pins.clone();
+ for pin in &mut pins {
+ if pin.commit.is_empty() {
+ continue;
+ }
+ let cache = cfg.vcs_cache_path(&pin.url);
+ if !cache.exists() {
+ git::clone_bare(&pin.url, &cache)
+ .map_err(|e| Error::transient(format!("vcs_cache clone {}: {e}", pin.url)))?;
+ } else {
+ let _ = git::fetch_and_head(&cache);
+ }
+ // The clone is here anyway, so confirm the tip locally: that also proves
+ // the commit we probed actually exists and is reachable.
+ if let Ok(local) = git::head(&cache) {
+ if !local.is_empty() && git::has_commit(&cache, &pin.commit) {
+ pin.branch = pin.branch.clone().or_else(|| default_branch(&cache));
+ let _ = local;
+ }
+ }
+ }
+
+ // Run `makepkg --vercheck` against the recipe in a scratch directory. The
+ // real tool clones the sources itself; the shim reports the fixture value.
+ let scratch = scratch_dir(cfg, &pb.name, recipe_hash, tip_hash);
+ let _ = std::fs::remove_dir_all(&scratch);
+ std::fs::create_dir_all(&scratch)?;
+ std::fs::write(scratch.join("PKGBUILD"), &recipe.pkgbuild)?;
+ if let Some(srcinfo) = &recipe.srcinfo {
+ std::fs::write(scratch.join(".SRCINFO"), srcinfo)?;
+ }
+ let mut cmd = Command::new(&cfg.makepkg_bin);
+ cmd.current_dir(&scratch).arg("--vercheck");
+ cfg.child_env(&mut cmd);
+ let out = cmd.output()?;
+ let _ = std::fs::remove_dir_all(&scratch);
+ if !out.status.success() {
+ return Err(Error::transient(format!(
+ "makepkg --vercheck: {}",
+ String::from_utf8_lossy(&out.stderr).trim()
+ )));
+ }
+ let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
+ let (pkgver, pkgrel) = match text.rsplit_once('-') {
+ Some((v, r)) => (v.to_string(), r.to_string()),
+ None => (text.clone(), "1".to_string()),
+ };
+ if pkgver.is_empty() {
+ return Err(Error::other(format!("makepkg --vercheck produced {text:?}")));
+ }
+ let _ = db;
+ Ok(StageB {
+ epoch: recipe.epoch.clone(),
+ pkgver,
+ pkgrel,
+ pins,
+ cached: false,
+ })
+}
+
+fn default_branch(cache: &std::path::Path) -> Option<String> {
+ git::git(Some(cache), &["symbolic-ref", "--short", "HEAD"])
+ .ok()
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+}
+
+/// A stable hash of the upstream tip set — the cache key's third component.
+pub fn tip_hash(pins: &[UpstreamPin]) -> String {
+ let mut v: Vec<String> = pins
+ .iter()
+ .map(|p| format!("{}:{}:{}", p.index, p.url, p.commit))
+ .collect();
+ v.sort();
+ crate::hash::hex_str(&v.join("\n"))
+}
+
+fn scratch_dir(cfg: &Config, pkgbase: &str, recipe_hash: &str, tip_hash: &str) -> PathBuf {
+ cfg.staging_dir()
+ .join("vercheck")
+ .join(format!("{pkgbase}-{}-{}", &recipe_hash[..8.min(recipe_hash.len())], &tip_hash[..8.min(tip_hash.len())]))
+}