summaryrefslogtreecommitdiffstats
path: root/src/recipe.rs
diff options
context:
space:
mode:
authoraur-build <aur-build@localhost>2026-11-17 21:19:35 +0000
committeraur-build <aur-build@localhost>2026-11-17 21:19:35 +0000
commitf586d11f6a1711145ba4804787217a1bab58751d (patch)
tree3a8cd7d4a3d4097e315907c63e687bd243e8e686 /src/recipe.rs
parentfd3ecf91686b11feea078531baeddb60e6941116 (diff)
downloadaur-build-f586d11f6a1711145ba4804787217a1bab58751d.tar.gz
aur-build-f586d11f6a1711145ba4804787217a1bab58751d.zip
feat: AUR mirror watcher, recipe parsing, candidate creation
The detection path (§5.1, §5.1a, §5.3, §7.1): * git helpers, all subprocess git in one auditable place. Mirrors are cloned with --mirror and polled with git ls-remote, fetching only when the tip actually moved; --no-prune keeps history we may need forever. * .SRCINFO parsing (authoritative) with a PKGBUILD fallback, and source=() parsing that keeps VCS kind, #commit/#tag/#branch refs and the filename:: form. * recipe_hash over the whole snapshot tree, so a shipped patch is part of the recipe and cannot change silently. * source digest resolution: declared checksums are trusted-as-declared (makepkg enforces them, no bandwidth), local files are hashed from the mirror, and SKIP sources are downloaded and stream-hashed into the content-addressed source cache. Detection always re-fetches SKIP sources — answering from our own cache would defeat drift detection. * candidate creation with base = current_accepted_release, collapse in place while unviewed, supersede only once a human has looked, and a previously rejected identity is not re-raised. * non-publishable change handling (I11): unchanged version string means no review, but never silence — recipe drift and pin drift become notices, and a changed digest on a remote source with an unchanged version becomes a high-severity integrity_alert. Also vercmp + dep-string parsing with the ALPM test vectors, and the approval record with optimistic concurrency (§7.1a) that the CLI and web layers will both call. 16 detection tests against real file:// git fixtures, incl. I2 across three unattended detections and I11 for all three drift kinds. Part of P0 (DESIGN.md §17).
Diffstat (limited to 'src/recipe.rs')
-rw-r--r--src/recipe.rs426
1 files changed, 426 insertions, 0 deletions
diff --git a/src/recipe.rs b/src/recipe.rs
new file mode 100644
index 0000000..a43059d
--- /dev/null
+++ b/src/recipe.rs
@@ -0,0 +1,426 @@
+//! Recipe parsing: `.SRCINFO` (authoritative, present in every AUR repo) with a
+//! `PKGBUILD` fallback, plus `source=()` parsing.
+//!
+//! The recipe is what a human reviews, so parsing failures are loud: a recipe we
+//! cannot read must never silently produce a candidate with an empty source list.
+
+use std::collections::BTreeMap;
+
+use crate::db::model::{Recipe, SourceEntry};
+use crate::error::{Error, Result};
+
+/// Parse `.SRCINFO`. Sections are `pkgbase = X` followed by `key = value` lines,
+/// then one `pkgname = Y` section per emitted package.
+pub fn parse_srcinfo(text: &str) -> Result<Recipe> {
+ let mut r = Recipe::default();
+ let mut current: Option<String> = None; // Some(pkgname) when inside a pkgname section
+ let mut base_seen = false;
+ for line in text.lines() {
+ let line = line.trim_end();
+ if line.is_empty() {
+ continue;
+ }
+ let indented = line.starts_with('\t') || line.starts_with(' ');
+ let (k, v) = match line.split_once('=') {
+ Some((k, v)) => (k.trim().to_string(), v.trim().to_string()),
+ None => continue,
+ };
+ if !indented {
+ if k == "pkgbase" {
+ r.pkgbase = v;
+ base_seen = true;
+ current = None;
+ } else if k == "pkgname" {
+ current = Some(v.clone());
+ r.pkgnames.push(v.clone());
+ r.pkg_depends.push((v, Vec::new()));
+ }
+ continue;
+ }
+ if !base_seen {
+ return Err(Error::invalid(".SRCINFO has no pkgbase line"));
+ }
+ let in_pkg = current.is_some();
+ push_field(&mut r, in_pkg, current.as_deref(), &k, &v);
+ }
+ if r.pkgnames.is_empty() {
+ r.pkgnames.push(r.pkgbase.clone());
+ let deps = r.depends.clone();
+ r.pkg_depends.push((r.pkgbase.clone(), deps));
+ }
+ r.srcinfo = Some(text.to_string());
+ r.source_entries = parse_source_entries(&r.source)?;
+ Ok(r)
+}
+
+#[allow(clippy::too_many_arguments)]
+fn push_field(r: &mut Recipe, in_pkg: bool, pkg: Option<&str>, k: &str, v: &str) {
+ // Fields that belong to the base only are ignored inside pkgname sections.
+ match k {
+ "pkgver" if !in_pkg => r.pkgver = v.into(),
+ "pkgrel" if !in_pkg => r.pkgrel = v.into(),
+ "epoch" if !in_pkg => r.epoch = v.into(),
+ "pkgdesc" => r.pkgdesc = v.into(),
+ "url" if !in_pkg => r.url = v.into(),
+ "arch" => r.arch.push(v.into()),
+ "license" => r.license.push(v.into()),
+ "groups" => r.groups.push(v.into()),
+ "depends" => {
+ r.depends.push(v.into());
+ if let Some(p) = pkg {
+ if let Some((_, d)) = r.pkg_depends.iter_mut().find(|(n, _)| n == p) {
+ d.push(v.into());
+ }
+ }
+ }
+ "makedepends" => r.makedepends.push(v.into()),
+ "checkdepends" => r.checkdepends.push(v.into()),
+ "optdepends" => r.optdepends.push(v.into()),
+ "provides" => r.provides.push(v.into()),
+ "conflicts" => r.conflicts.push(v.into()),
+ "source" => r.source.push(v.into()),
+ "sha256sums" => r.sha256sums.push(v.into()),
+ "b2sums" => r.b2sums.push(v.into()),
+ "validpgpkeys" => r.validpgpkeys.push(v.into()),
+ "options" => r.options.push(v.into()),
+ "backup" => r.backup.push(v.into()),
+ "install" => r.install = Some(v.into()),
+ _ => {}
+ }
+}
+
+/// Minimal `PKGBUILD` variable reader: top-level `var=value` and `var=(...)`
+/// assignments, including arrays spanning several lines and quoted elements.
+///
+/// This is a fallback for recipes without `.SRCINFO`; it deliberately does not
+/// try to evaluate bash. Anything it cannot read is reported, not guessed.
+pub fn parse_pkgbuild(text: &str) -> Result<Recipe> {
+ let vars = pkgbuild_vars(text);
+ let mut r = Recipe::default();
+ let get = |k: &str| vars.get(k).cloned().unwrap_or_default();
+ r.pkgbase = get("pkgbase").into_iter().next().unwrap_or_default();
+ if r.pkgbase.is_empty() {
+ // A PKGBUILD without pkgbase emits one package named pkgname[0].
+ r.pkgbase = get("pkgname").into_iter().next().unwrap_or_default();
+ }
+ if r.pkgbase.is_empty() {
+ return Err(Error::invalid("PKGBUILD declares no pkgbase or pkgname"));
+ }
+ r.pkgver = get("pkgver").into_iter().next().unwrap_or_default();
+ r.pkgrel = get("pkgrel").into_iter().next().unwrap_or_default();
+ r.epoch = get("epoch").into_iter().next().unwrap_or_default();
+ if r.epoch.is_empty() {
+ r.epoch = "0".into();
+ }
+ if r.pkgver.is_empty() {
+ return Err(Error::invalid("PKGBUILD declares no pkgver"));
+ }
+ if r.pkgrel.is_empty() {
+ r.pkgrel = "1".into();
+ }
+ r.pkgdesc = get("pkgdesc").into_iter().next().unwrap_or_default();
+ r.url = get("url").into_iter().next().unwrap_or_default();
+ r.arch = get("arch");
+ r.license = get("license");
+ r.groups = get("groups");
+ r.depends = get("depends");
+ r.makedepends = get("makedepends");
+ r.checkdepends = get("checkdepends");
+ r.optdepends = get("optdepends");
+ r.provides = get("provides");
+ r.conflicts = get("conflicts");
+ r.source = get("source");
+ r.sha256sums = get("sha256sums");
+ r.b2sums = get("b2sums");
+ r.validpgpkeys = get("validpgpkeys");
+ r.options = get("options");
+ r.backup = get("backup");
+ r.install = get("install").into_iter().next();
+ let pkgnames = get("pkgname");
+ r.pkgnames = if pkgnames.is_empty() {
+ vec![r.pkgbase.clone()]
+ } else {
+ pkgnames.clone()
+ };
+ r.pkg_depends = r
+ .pkgnames
+ .iter()
+ .map(|n| (n.clone(), r.depends.clone()))
+ .collect();
+ r.skipgpcheck = text.contains("--skippgpcheck");
+ r.pkgbuild = text.to_string();
+ r.source_entries = parse_source_entries(&r.source)?;
+ Ok(r)
+}
+
+/// Extract top-level assignments from a PKGBUILD.
+fn pkgbuild_vars(text: &str) -> BTreeMap<String, Vec<String>> {
+ let mut out: BTreeMap<String, Vec<String>> = BTreeMap::new();
+ let mut lines = text.lines().peekable();
+ while let Some(line) = lines.next() {
+ let t = line.trim_start();
+ if t.starts_with('#') || t.is_empty() {
+ continue;
+ }
+ // Stop at the first function definition: variables inside functions are
+ // not part of the recipe metadata we diff.
+ if t.contains("()") && t.contains('{') {
+ break;
+ }
+ let Some((name, rest)) = split_assign(t) else { continue };
+ let rest = rest.trim();
+ if let Some(inner) = rest.strip_prefix('(') {
+ // Array: may close on this line or later ones.
+ let mut buf = String::from(inner);
+ while !buf.contains(')') {
+ match lines.next() {
+ Some(l) => {
+ buf.push(' ');
+ buf.push_str(l.trim());
+ }
+ None => break,
+ }
+ }
+ let inner = buf.split(')').next().unwrap_or(&buf).to_string();
+ out.entry(name).or_default().extend(split_array_elements(&inner));
+ } else {
+ let v = unquote(rest);
+ if !v.is_empty() {
+ out.entry(name).or_default().push(v);
+ }
+ }
+ }
+ out
+}
+
+/// `name=value` where the line is an assignment (no spaces before `=`).
+fn split_assign(t: &str) -> Option<(String, String)> {
+ let (name, rest) = t.split_once('=')?;
+ let name = name.trim();
+ if name.is_empty()
+ || !name
+ .chars()
+ .next()
+ .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
+ || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
+ {
+ return None;
+ }
+ // `foo[1]=x` and similar are not metadata.
+ if name.contains('[') {
+ return None;
+ }
+ Some((name.to_string(), rest.to_string()))
+}
+
+fn unquote(s: &str) -> String {
+ let s = s.trim();
+ let s = s.strip_prefix('"').unwrap_or(s);
+ let s = s.strip_suffix('"').unwrap_or(s);
+ let s = s.strip_prefix('\'').unwrap_or(s);
+ s.strip_suffix('\'').unwrap_or(s).to_string()
+}
+
+/// Split `(a "b c" 'd e')` into elements.
+fn split_array_elements(s: &str) -> Vec<String> {
+ let mut out = Vec::new();
+ let mut cur = String::new();
+ let mut quote: Option<char> = None;
+ let mut pushed = false;
+ for c in s.chars() {
+ match quote {
+ Some(q) => {
+ if c == q {
+ quote = None;
+ } else {
+ cur.push(c);
+ }
+ }
+ None => match c {
+ '\'' | '"' => quote = Some(c),
+ c if c.is_whitespace() => {
+ if !cur.is_empty() {
+ out.push(std::mem::take(&mut cur));
+ }
+ pushed = true;
+ }
+ c => {
+ cur.push(c);
+ pushed = false;
+ }
+ },
+ }
+ }
+ let _ = pushed;
+ if !cur.is_empty() {
+ out.push(cur);
+ }
+ out.into_iter().filter(|e| !e.is_empty()).collect()
+}
+
+/// Parse `source=()` entries into structured form (§5.2 needs the VCS refs,
+/// §5.3 needs the kind of each entry).
+pub fn parse_source_entries(list: &[String]) -> Result<Vec<SourceEntry>> {
+ let mut out = Vec::new();
+ for (index, raw) in list.iter().enumerate() {
+ let s = raw.trim();
+ if s.is_empty() {
+ return Err(Error::invalid("empty source entry"));
+ }
+ // `filename::url` (filename first, per makepkg).
+ let (filename, url) = match s.split_once("::") {
+ Some((f, u)) => (Some(f.to_string()), u.to_string()),
+ None => (None, s.to_string()),
+ };
+ let (url, frag) = match url.split_once('#') {
+ Some((u, f)) => (u.to_string(), Some(f.to_string())),
+ None => (url.clone(), None),
+ };
+ let (vcs, clean) = match url.split_once('+') {
+ Some((scheme, rest)) if ["git", "svn", "hg", "bzr", "fossil"].contains(&scheme) => {
+ (Some(scheme.to_string()), rest.to_string())
+ }
+ _ => (None, url.clone()),
+ };
+ let mut commit = None;
+ let mut tag = None;
+ let mut branch = None;
+ if let Some(f) = frag {
+ for pair in f.split('&') {
+ let (k, v) = match pair.split_once('=') {
+ Some((k, v)) => (k, v),
+ None => continue,
+ };
+ match k {
+ "commit" => commit = Some(v.to_string()),
+ "tag" => tag = Some(v.to_string()),
+ "branch" => branch = Some(v.to_string()),
+ _ => {}
+ }
+ }
+ }
+ let local = vcs.is_none() && !clean.contains("://");
+ let filename = filename.or_else(|| {
+ if local {
+ clean.rsplit('/').next().map(|s| s.to_string())
+ } else {
+ None
+ }
+ });
+ out.push(SourceEntry {
+ index,
+ url: clean,
+ filename,
+ commit,
+ tag,
+ branch,
+ vcs,
+ local,
+ });
+ }
+ Ok(out)
+}
+
+/// Build a recipe from a materialized AUR tree.
+///
+/// `.SRCINFO` wins when present — it is what `makepkg` itself reports and every
+/// real AUR repo ships it. Otherwise we fall back to reading the `PKGBUILD`.
+pub fn recipe_from_tree(files: &BTreeMap<String, String>) -> Result<Recipe> {
+ let pkgbuild_path = files
+ .keys()
+ .find(|k| k.ends_with("PKGBUILD"))
+ .cloned()
+ .ok_or_else(|| Error::invalid("snapshot tree contains no PKGBUILD"))?;
+ let pkgbuild = files.get(&pkgbuild_path).cloned().unwrap_or_default();
+ let mut r = match files.iter().find(|(k, _)| k.ends_with(".SRCINFO")) {
+ Some((_, srcinfo)) => parse_srcinfo(srcinfo)?,
+ None => parse_pkgbuild(&pkgbuild)?,
+ };
+ if r.pkgbuild.is_empty() {
+ r.pkgbuild = pkgbuild;
+ }
+ if r.pkgbase.is_empty() {
+ return Err(Error::invalid("recipe has no pkgbase"));
+ }
+ Ok(r)
+}
+
+/// Text files we render diffs for (§6 "recipe diff" panel).
+pub fn is_diffable(path: &str) -> bool {
+ let ext = path.rsplit('.').next().unwrap_or("");
+ !matches!(
+ ext,
+ "png" | "jpg" | "gif" | "ico" | "pdf" | "gz" | "zst" | "xz" | "bz2" | "zip" | "deb" | "rpm"
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn pkgbuild_arrays_span_lines_and_quotes() {
+ let r = parse_pkgbuild(
+ r#"# comment
+pkgbase=foo
+pkgver=1.0
+pkgrel=2
+pkgdesc="a package"
+arch=(x86_64)
+depends=('glibc' openssl
+ zlib)
+source=(git+https://example.invalid/foo.git
+ fix.patch::https://example.invalid/fix.patch)
+sha256sums=('SKIP' 'abc')
+build() {
+ local pkgver=not-this
+}
+"#,
+ )
+ .unwrap();
+ assert_eq!(r.pkgbase, "foo");
+ assert_eq!(r.full_version(), "1.0-2");
+ assert_eq!(r.depends, vec!["glibc", "openssl", "zlib"]);
+ assert_eq!(r.source.len(), 2);
+ assert_eq!(r.sha256sums, vec!["SKIP", "abc"]);
+ assert_eq!(r.pkgnames, vec!["foo"]);
+ }
+
+ #[test]
+ fn source_entries_carry_kind_and_refs() {
+ let e = parse_source_entries(&[
+ "git+https://github.com/foo/bar.git#commit=deadbeef".into(),
+ "git+https://github.com/foo/bar.git#branch=next".into(),
+ "hg+https://example.invalid/x".into(),
+ "name::https://example.invalid/file.tar.gz".into(),
+ "local.patch".into(),
+ ])
+ .unwrap();
+ assert_eq!(e[0].vcs.as_deref(), Some("git"));
+ assert_eq!(e[0].commit.as_deref(), Some("deadbeef"));
+ assert_eq!(e[0].url, "https://github.com/foo/bar.git");
+ assert_eq!(e[1].branch.as_deref(), Some("next"));
+ assert_eq!(e[2].vcs.as_deref(), Some("hg"));
+ assert_eq!(e[3].filename.as_deref(), Some("name"));
+ assert!(!e[3].local);
+ assert!(e[4].local);
+ assert_eq!(e[4].filename.as_deref(), Some("local.patch"));
+ }
+
+ #[test]
+ fn srcinfo_sections_describe_split_pkgbases() {
+ let r = parse_srcinfo(
+ "pkgbase = foo\n\tpkgver = 1.0\n\tpkgrel = 1\n\tmakedepends = cmake\n\tsource = x.tar\n\tsha256sums = SKIP\npkgname = foo\n\tdepends = glibc\npkgname = foo-lua\n\tdepends = lua\n",
+ )
+ .unwrap();
+ assert_eq!(r.pkgbase, "foo");
+ assert_eq!(r.pkgnames, vec!["foo", "foo-lua"]);
+ assert_eq!(r.makedepends, vec!["cmake"]);
+ assert_eq!(r.pkg_depends[1].1, vec!["lua"]);
+ }
+
+ #[test]
+ fn a_recipe_without_a_version_is_an_error_not_a_guess() {
+ assert!(parse_pkgbuild("pkgbase=foo\n").is_err());
+ }
+}