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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
|
//! Toolchain shims (§16a).
//!
//! The pipeline shells out to `mkarchroot`, `makechrootpkg`, `makepkg`,
//! `repo-add`, `gpg` and `pacman`. In test mode the harness prepends a directory
//! of fakes to `PATH`; each fake records its invocation, obeys a scripted
//! outcome from the fixture manifest, and emits plausible
//! `.PKGINFO`/`.BUILDINFO`/`.sig` output.
//!
//! That is what makes the full step machine, checkpointing, lease/reaper
//! recovery, publishing and index regeneration runnable in milliseconds on any
//! machine — no Arch host, no root, no network.
//!
//! Protocol, all via environment so the pipeline needs no test-only code paths:
//!
//! | var | meaning |
//! |---|---|
//! | `AUR_SHIM_DIR` | where invocations are recorded (`invocations.jsonl`) |
//! | `AUR_SHIM_MANIFEST` | fixture manifest describing the scripted outcome |
//! | `AUR_SHIM_FAIL` | optional step name that must fail, e.g. `build` |
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::hash;
/// One package the fake toolchain emits.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct FakePackage {
pub name: String,
pub version: String,
pub arch: String,
pub desc: String,
pub url: String,
pub license: Vec<String>,
pub depends: Vec<String>,
pub makedepends: Vec<String>,
pub checkdepends: Vec<String>,
pub provides: Vec<String>,
pub conflicts: Vec<String>,
pub backup: Vec<String>,
}
impl Default for FakePackage {
fn default() -> Self {
Self {
name: String::new(),
version: "1.0-1".into(),
arch: "x86_64".into(),
desc: "fake package".into(),
url: String::new(),
license: vec!["MIT".into()],
depends: vec![],
makedepends: vec![],
checkdepends: vec![],
provides: vec![],
conflicts: vec![],
backup: vec![],
}
}
}
impl FakePackage {
/// `1.0-1` split into the `(pkgver, pkgrel)` pacman expects in `.PKGINFO`.
pub fn split_version(&self) -> (String, String) {
match self.version.rsplit_once('-') {
Some((v, r)) => (v.to_string(), r.to_string()),
None => (self.version.clone(), "1".into()),
}
}
}
/// A member of the fake chroot world, for `.BUILDINFO` (§10.1).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct FakeInstalled {
pub name: String,
pub version: String,
pub arch: String,
}
/// The scripted outcome of a fixture.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Manifest {
pub name: String,
/// `succeed` | `fail` | `check-fail` | `no-pkgver`
pub build: String,
/// Text the fake build writes to its log, for log-tail tests.
pub log_lines: Vec<String>,
pub packages: Vec<FakePackage>,
pub installed: Vec<FakeInstalled>,
/// Emit `.sig` files (default true).
pub sig: bool,
/// `pkgver` the fake `makepkg --vercheck` computes (VCS fixtures, §5.2).
pub vercheck: Option<String>,
/// Extra files to drop into the package tarball.
pub files: Vec<String>,
}
impl Default for Manifest {
fn default() -> Self {
Self {
name: "fixture".into(),
build: "succeed".into(),
log_lines: vec!["==> Making package.".into()],
packages: vec![],
installed: vec![],
sig: true,
vercheck: None,
files: vec![],
}
}
}
pub fn manifest() -> Manifest {
match std::env::var("AUR_SHIM_MANIFEST") {
Ok(p) => match std::fs::read_to_string(&p) {
Ok(s) => serde_json::from_str(&s).unwrap_or_default(),
Err(_) => Manifest::default(),
},
Err(_) => Manifest::default(),
}
}
/// Record that a shim ran, so tests can assert on what the pipeline actually
/// invoked rather than what it intended to invoke.
pub fn record(tool: &str, args: &[String]) {
let dir = match std::env::var("AUR_SHIM_DIR") {
Ok(d) => d,
Err(_) => return,
};
let _ = std::fs::create_dir_all(&dir);
let entry = serde_json::json!({
"tool": tool,
"args": args,
"cwd": std::env::current_dir().map(|p| p.display().to_string()).unwrap_or_default(),
});
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(Path::new(&dir).join("invocations.jsonl"))
{
use std::io::Write;
let _ = f.write_all(format!("{entry}\n").as_bytes());
}
}
/// Test hook: kill the process that invoked us, mid-step, with a signal it
/// cannot catch. This is how the crash-resume invariant (I5) is tested for real:
/// the pipeline process dies while a step is running, with no chance to clean
/// up, and the next process must pick up from the checkpoints.
fn kill_parent_if_asked(tool: &str) {
let want = std::env::var("AUR_SHIM_KILL_PARENT").unwrap_or_default();
if want == tool {
// Flush the invocation log first (record() already closed the file),
// then murder the parent. No cleanup, no unwinding, no atexit.
unsafe {
libc::kill(libc::getppid(), libc::SIGKILL);
}
// If the kill somehow did not land, do not let the step complete — that
// would make the test silently test nothing.
std::process::exit(137);
}
}
/// True when the harness asked this tool to fail.
fn forced_fail(tool: &str) -> bool {
std::env::var("AUR_SHIM_FAIL").map(|v| v == tool).unwrap_or(false)
}
/// Read the invocation log back (test side).
pub fn invocations(dir: &Path) -> Vec<serde_json::Value> {
let path = dir.join("invocations.jsonl");
match std::fs::read_to_string(path) {
Ok(s) => s
.lines()
.filter_map(|l| serde_json::from_str(l).ok())
.collect(),
Err(_) => Vec::new(),
}
}
/// Entries whose `args` mention `needle`.
pub fn called_with(dir: &Path, tool: &str, needle: &str) -> usize {
invocations(dir)
.iter()
.filter(|e| e["tool"] == tool)
.filter(|e| {
e["args"]
.as_array()
.map(|a| a.iter().any(|v| v.as_str().is_some_and(|s| s.contains(needle))))
.unwrap_or(false)
})
.count()
}
/// Dispatch table used by every `src/bin/*.rs`.
pub fn run(tool: &str) -> i32 {
let args: Vec<String> = std::env::args().skip(1).collect();
record(tool, &args);
kill_parent_if_asked(tool);
let m = manifest();
let r = match tool {
"mkarchroot" => mkarchroot(&args),
"makechrootpkg" => makechrootpkg(&args, &m),
"makepkg" => makepkg(&args, &m),
"repo-add" => repo_add(&args, &m),
"gpg" => gpg(&args),
"pacman" => Ok(0),
other => Err(format!("no shim named {other}")),
};
match r {
Ok(code) => code,
Err(e) => {
eprintln!("shim {tool}: {e}");
1
}
}
}
/// `mkarchroot <path>`: create a directory that stands in for a warm root.
pub fn mkarchroot(args: &[String]) -> Result<i32, String> {
// `mkarchroot [-C pacman.conf] [-M makepkg.conf] <root>`: the config options
// take a value, so they cannot be skipped blindly.
let mut target = None;
let mut skip = false;
for a in args {
if skip {
skip = false;
continue;
}
if matches!(a.as_str(), "-C" | "-M" | "-k") {
skip = true;
continue;
}
if !a.starts_with('-') {
target = Some(a.clone());
break;
}
}
let target = target.ok_or("mkarchroot: no target")?;
std::fs::create_dir_all(&target).map_err(|e| e.to_string())?;
// A marker so the pipeline can tell a real root from a fake one.
let _ = std::fs::write(Path::new(&target).join("SHIM-ROOT"), "fake chroot\n");
Ok(0)
}
/// `makechrootpkg -c -r <chroot> -- -f`, run with cwd = the build dir.
///
/// Emits one `.pkg.tar.zst` per package in the manifest into the current
/// directory, exactly where the real tool leaves them.
pub fn makechrootpkg(args: &[String], m: &Manifest) -> Result<i32, String> {
for l in &m.log_lines {
println!("{l}");
}
if forced_fail("makechrootpkg") || m.build == "fail" {
eprintln!("==> ERROR: A build function returned error.");
return Ok(1);
}
if m.build == "check-fail" {
eprintln!("==> ERROR: A failure occurred in check().");
return Ok(1);
}
// The pipeline always passes a chroot root; asserting it keeps the fake
// honest about the real tool's contract.
if !args.iter().any(|a| a == "-r") {
return Err("makechrootpkg: expected -r <chroot>".into());
}
let startdir = std::env::current_dir().map_err(|e| e.to_string())?;
// The real tool reads the PKGBUILD it was handed; we assert it is there so a
// broken materialize step cannot pass silently.
if !startdir.join("PKGBUILD").exists() {
let found = std::fs::read_dir(&startdir)
.map(|rd| rd.filter_map(|e| e.ok()).map(|e| e.file_name().to_string_lossy().into_owned()).collect::<Vec<_>>())
.unwrap_or_default();
return Err(format!(
"makechrootpkg: no PKGBUILD in {} (contains {found:?})",
startdir.display()
));
}
let pkgs = packages_to_emit(m, &startdir);
// Sign only when the caller asked for it, like the real tool: signing is
// `-si<key>`/`-i`, and the pipeline stopped passing it when signing moved
// hub-side to ingest. A shim that signed anyway would hide that move from
// every test in the suite.
let wants_sig = args.iter().any(|a| a.starts_with("-si") || a == "-i" || a == "--sign");
for p in &pkgs {
let path = write_package(&startdir, p, m)?;
println!("==> Creating package '{}'", path.file_name().unwrap().to_string_lossy());
if m.sig && wants_sig {
if let Ok(bytes) = std::fs::read(&path) {
let sig = path.with_extension("pkg.tar.zst.sig");
let _ = std::fs::write(&sig, fake_sig(&bytes));
}
}
}
plant_link_if_asked(&startdir);
Ok(0)
}
/// I9 test hook: drop a symlink into the srcdir pointing wherever the test names,
/// standing in for a PKGBUILD that tries to smuggle outside bytes into the
/// artifact store. The pipeline must refuse it; see `collect` in steps.rs.
fn plant_link_if_asked(startdir: &Path) {
let target = match std::env::var("AUR_SHIM_PLANT_LINK") {
Ok(t) if !t.is_empty() => t,
_ => return,
};
let link = startdir.join("planted.pkg.tar.zst");
#[cfg(unix)]
{
let _ = std::fs::remove_file(&link);
if let Err(e) = std::os::unix::fs::symlink(&target, &link) {
eprintln!("shim: could not plant {link:?} -> {target}: {e}");
}
}
}
fn packages_to_emit(m: &Manifest, startdir: &Path) -> Vec<FakePackage> {
if !m.packages.is_empty() {
return m.packages.clone();
}
// No explicit manifest: derive one package from the PKGBUILD we were given.
let text = std::fs::read_to_string(startdir.join("PKGBUILD")).unwrap_or_default();
let recipe = crate::recipe::parse_pkgbuild(&text).ok();
match recipe {
Some(r) => r
.pkgnames
.iter()
.map(|n| FakePackage {
name: n.clone(),
version: format!("{}-{}", r.pkgver, r.pkgrel),
arch: r.arch.first().cloned().unwrap_or_else(|| "x86_64".into()),
desc: r.pkgdesc.clone(),
url: r.url.clone(),
depends: crate::pkgver::dep_names(&r.depends),
makedepends: crate::pkgver::dep_names(&r.makedepends),
checkdepends: crate::pkgver::dep_names(&r.checkdepends),
provides: r.provides.clone(),
conflicts: r.conflicts.clone(),
..Default::default()
})
.collect(),
None => vec![FakePackage { name: "unknown".into(), ..Default::default() }],
}
}
/// Write a `.pkg.tar.zst` containing `.PKGINFO`, `.BUILDINFO` and any scripted
/// payload files.
pub fn write_package(dir: &Path, p: &FakePackage, m: &Manifest) -> Result<PathBuf, String> {
let (pkgver, pkgrel) = p.split_version();
let filename = format!("{}-{}-{}.pkg.tar.zst", p.name, p.version, p.arch);
let path = dir.join(&filename);
let enc = zstd::Encoder::new(std::io::BufWriter::new(
std::fs::File::create(&path).map_err(|e| e.to_string())?,
), 3)
.map_err(|e| e.to_string())?;
let mut ar = tar::Builder::new(enc);
// NOTE: the zstd frame must be finished explicitly or the archive is a
// truncated stream that nothing can read back.
let pkginfo = pkginfo(p, &pkgver, &pkgrel);
write_entry(&mut ar, ".PKGINFO", pkginfo.as_bytes())?;
let buildinfo = buildinfo(p, &pkgver, &pkgrel, m);
write_entry(&mut ar, ".BUILDINFO", buildinfo.as_bytes())?;
for f in &m.files {
write_entry(&mut ar, &format!("usr/share/{}/{f}", p.name), f.as_bytes())?;
}
// A payload file so the artifact has non-metadata bytes and a real size.
write_entry(&mut ar, &format!("usr/bin/{}", p.name), b"#!/bin/sh\necho hi\n")?;
let enc = ar.into_inner().map_err(|e| e.to_string())?;
enc.finish().map_err(|e| e.to_string())?;
Ok(path)
}
fn write_entry<W: std::io::Write>(ar: &mut tar::Builder<W>, path: &str, body: &[u8]) -> Result<(), String> {
let mut h = tar::Header::new_gnu();
h.set_size(body.len() as u64);
h.set_mode(0o644);
h.set_mtime(0);
h.set_entry_type(tar::EntryType::Regular);
ar.append_data(&mut h, path, body).map_err(|e| e.to_string())
}
fn pkginfo(p: &FakePackage, pkgver: &str, pkgrel: &str) -> String {
let mut s = String::new();
s.push_str(&format!("pkgname = {}\n", p.name));
s.push_str(&format!("pkgbase = {}\n", p.name));
s.push_str(&format!("pkgver = {pkgver}-{pkgrel}\n"));
s.push_str(&format!("pkgarch = {}\n", p.arch));
s.push_str(&format!("pkgdesc = {}\n", p.desc));
s.push_str(&format!("url = {}\n", p.url));
s.push_str("builddate = 1700000000\n");
s.push_str("packager = shim <shim@example.invalid>\n");
s.push_str("size = 42\n");
for l in &p.license {
s.push_str(&format!("license = {l}\n"));
}
for d in &p.depends {
s.push_str(&format!("depend = {d}\n"));
}
for d in &p.makedepends {
s.push_str(&format!("makedepend = {d}\n"));
}
for d in &p.checkdepends {
s.push_str(&format!("checkdepend = {d}\n"));
}
for d in &p.provides {
s.push_str(&format!("provides = {d}\n"));
}
for d in &p.conflicts {
s.push_str(&format!("conflicts = {d}\n"));
}
for b in &p.backup {
s.push_str(&format!("backup = {b}\n"));
}
s
}
/// `.BUILDINFO`: the full installed set at build time. Left unfiltered this is
/// the whole chroot, which is exactly why §10.1 intersects it with our own
/// packages before storing a world snapshot.
fn buildinfo(p: &FakePackage, pkgver: &str, pkgrel: &str, m: &Manifest) -> String {
let mut s = String::new();
s.push_str("format = 2\n");
s.push_str(&format!("pkgname = {}\n", p.name));
s.push_str(&format!("pkgbase = {}\n", p.name));
s.push_str(&format!("pkgver = {pkgver}-{pkgrel}\n"));
s.push_str(&format!("pkgarch = {}\n", p.arch));
s.push_str("packager = shim <shim@example.invalid>\n");
s.push_str("builddate = 1700000000\n");
s.push_str("buildenv = (!debug !strip)\n");
s.push_str("installed =\n");
for i in &m.installed {
s.push_str(&format!(" {} {} {} -\n", i.name, i.version, if i.arch.is_empty() { "any" } else { &i.arch }));
}
s
}
fn fake_sig(bytes: &[u8]) -> Vec<u8> {
format!("-----BEGIN FAKE PGP SIGNATURE-----\n{}\n-----END FAKE PGP SIGNATURE-----\n", hash::hex(bytes)).into_bytes()
}
/// `makepkg --printsrcinfo` / `--vercheck` (§5.2 Stage B).
pub fn makepkg(args: &[String], m: &Manifest) -> Result<i32, String> {
if args.iter().any(|a| a == "--vercheck" || a == "-V-check") {
let v = m.vercheck.clone().unwrap_or_else(|| "1.0-1".into());
println!("{v}");
return Ok(0);
}
if args.iter().any(|a| a == "--printsrcinfo" || a == "-g") {
let text = std::fs::read_to_string("PKGBUILD").unwrap_or_default();
match crate::recipe::parse_pkgbuild(&text) {
Ok(r) => {
let mut s = String::new();
if let Some(si) = r.srcinfo {
s = si;
} else {
s.push_str(&format!("pkgbase = {}\n", r.pkgbase));
s.push_str(&format!("\tpkgver = {}\n", r.pkgver));
s.push_str(&format!("\tpkgrel = {}\n", r.pkgrel));
if r.epoch != "0" {
s.push_str(&format!("\tepoch = {}\n", r.epoch));
}
for a in &r.arch {
s.push_str(&format!("\tarch = {a}\n"));
}
for d in &r.depends {
s.push_str(&format!("\tdepends = {d}\n"));
}
for src in &r.source {
s.push_str(&format!("\tsource = {src}\n"));
}
for c in &r.sha256sums {
s.push_str(&format!("\tsha256sums = {c}\n"));
}
for n in &r.pkgnames {
s.push_str(&format!("pkgname = {n}\n"));
}
}
print!("{s}");
Ok(0)
}
Err(e) => {
eprintln!("makepkg: {e}");
Ok(1)
}
}
} else {
// `makepkg -si` style: behave like a local build.
makechrootpkg(args, m)
}
}
/// `repo-add [-s -p key -R] <db.tar.{gz,zst}> <pkg...>`: rebuild the database
/// from the packages handed to it.
///
/// The real tool appends; `-R` replaces an existing entry. We rebuild the whole
/// db from the packages given, which is what our publish step does anyway (it
/// passes exactly the packages that belong in the index).
pub fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> {
// `-p <key>` and friends take a value; a naive filter would treat the key id
// as a package path.
let mut positional: Vec<&String> = Vec::new();
let mut skip = false;
for a in args {
if skip {
skip = false;
continue;
}
if matches!(a.as_str(), "-p" | "--key" | "-o" | "-e") {
skip = true;
continue;
}
if !a.starts_with('-') {
positional.push(a);
}
}
let (db_path, pkgs) = match positional.split_first() {
Some((db, rest)) => (PathBuf::from(db), rest.iter().map(|p| PathBuf::from(p.as_str())).collect::<Vec<_>>()),
None => return Err("repo-add: no database given".into()),
};
let mut ar = tar::Builder::new(Vec::new());
for pkg in &pkgs {
let bytes = std::fs::read(pkg).map_err(|e| format!("repo-add: {}: {e}", pkg.display()))?;
let pkginfo = crate::pkginfo::pkginfo_text(&bytes)?;
let (name, version, arch, extra) = pkginfo_fields(&bytes)?;
let mut entry = String::new();
entry.push_str(&format!("%FILENAME%\n{}\n\n", pkg.file_name().unwrap().to_string_lossy()));
entry.push_str(&format!("%NAME%\n{name}\n\n"));
entry.push_str(&format!("%BASE%\n{name}\n\n"));
entry.push_str(&format!("%VERSION%\n{version}\n\n"));
entry.push_str(&format!("%ARCH%\n{arch}\n\n"));
entry.push_str(&format!("%CSIZE%\n{}\n\n", bytes.len()));
entry.push_str("%DSIZE%\n42\n\n");
entry.push_str(&format!("%MD5SUM%\n{}\n\n", hash::hex(&bytes)));
entry.push_str(&format!("%SHA256SUM%\n{}\n\n", hash::hex(&bytes)));
if !extra.is_empty() {
entry.push_str(&format!("{extra}\n"));
}
let mut h = tar::Header::new_gnu();
h.set_size(entry.len() as u64);
h.set_mode(0o644);
h.set_mtime(0);
ar.append_data(&mut h, format!("{name}/DESC"), entry.as_bytes())
.map_err(|e| e.to_string())?;
let mut h2 = tar::Header::new_gnu();
h2.set_size(pkginfo.len() as u64);
h2.set_mode(0o644);
h2.set_mtime(0);
ar.append_data(&mut h2, format!("{name}/.PKGINFO"), pkginfo.as_bytes())
.map_err(|e| e.to_string())?;
}
let tar = ar.into_inner().map_err(|e| e.to_string())?;
// pacman databases are gzip'd tarballs.
let mut enc = flate2::write::GzEncoder::new(
std::fs::File::create(&db_path).map_err(|e| e.to_string())?,
flate2::Compression::default(),
);
use std::io::Write;
enc.write_all(&tar).map_err(|e| e.to_string())?;
enc.finish().map_err(|e| e.to_string())?;
println!("==> Updating repository");
Ok(0)
}
/// Pull `.PKGINFO` out of a `.pkg.tar.zst` and render the `DESC` fields a
/// pacman database carries beyond the fixed ones.
///
/// Both halves come from `crate::pkginfo`, the parser the production pipeline
/// uses (§6 M-4). The shim used to carry its own copy of the field parser, and
/// two parsers that can drift is a supply-chain-shaped foot-gun in a system
/// whose whole job is provenance: a test that passed because the shim read a
/// package one way would not have meant the pipeline read it that way.
fn pkginfo_fields(pkg_bytes: &[u8]) -> Result<(String, String, String, String), String> {
let text = crate::pkginfo::pkginfo_text(pkg_bytes)?;
let info = crate::pkginfo::parse_pkginfo(&text);
let mut extra = String::new();
{
let mut push = |tag: &str, vals: &[String]| {
if !vals.is_empty() {
extra.push_str(&format!("{tag}\n{}\n\n", vals.join("\n")));
}
};
let one = |s: &str| -> Vec<String> { if s.is_empty() { vec![] } else { vec![s.to_string()] } };
push("%DESC%", &one(&info.desc));
push("%URL%", &one(&info.url));
push("%LICENSE%", &info.license);
push("%DEPENDS%", &info.depends);
push("%OPTDEPENDS%", &info.optdepends);
push("%PROVIDES%", &info.provides);
push("%CONFLICTS%", &info.conflicts);
push("%REPLACES%", &info.replaces);
push("%GROUPS%", &info.groups);
}
Ok((info.name, info.version, info.arch, extra))
}
/// `gpg --detach-sign --output <sig> <file>`: write a deterministic stand-in
/// signature so the signing path is exercised end to end.
pub fn gpg(args: &[String]) -> Result<i32, String> {
let out = args
.iter()
.position(|a| a == "--output" || a == "-o")
.and_then(|i| args.get(i + 1))
.cloned();
let target = args.iter().rev().find(|a| !a.starts_with('-') && Some(*a) != out.as_ref());
let target = match target {
Some(t) => t,
None => return Err("gpg: nothing to sign".into()),
};
let bytes = std::fs::read(target).map_err(|e| format!("gpg: {target}: {e}"))?;
let sig = match out {
Some(o) => o,
None => format!("{target}.sig"),
};
std::fs::write(&sig, fake_sig(&bytes)).map_err(|e| e.to_string())?;
Ok(0)
}
|