diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/bin/gpg.rs | 6 | ||||
| -rw-r--r-- | src/bin/makechrootpkg.rs | 6 | ||||
| -rw-r--r-- | src/bin/makepkg.rs | 6 | ||||
| -rw-r--r-- | src/bin/mkarchroot.rs | 6 | ||||
| -rw-r--r-- | src/bin/pacman.rs | 6 | ||||
| -rw-r--r-- | src/bin/repo-add.rs | 6 | ||||
| -rw-r--r-- | src/config.rs | 21 | ||||
| -rw-r--r-- | src/lib.rs | 1 | ||||
| -rw-r--r-- | src/shims/mod.rs | 641 |
9 files changed, 693 insertions, 6 deletions
diff --git a/src/bin/gpg.rs b/src/bin/gpg.rs index 1c84fe2..e9df5e3 100644 --- a/src/bin/gpg.rs +++ b/src/bin/gpg.rs @@ -1 +1,5 @@ -fn main() { eprintln!("shim: gpg (not implemented)"); std::process::exit(70); } +//! Toolchain shim: `gpg` (§16a). See `aur_build::shims`. + +fn main() { + std::process::exit(aur_build::shims::run("gpg")); +} diff --git a/src/bin/makechrootpkg.rs b/src/bin/makechrootpkg.rs index 4043161..00569fb 100644 --- a/src/bin/makechrootpkg.rs +++ b/src/bin/makechrootpkg.rs @@ -1 +1,5 @@ -fn main() { eprintln!("shim: makechrootpkg (not implemented)"); std::process::exit(70); } +//! Toolchain shim: `makechrootpkg` (§16a). See `aur_build::shims`. + +fn main() { + std::process::exit(aur_build::shims::run("makechrootpkg")); +} diff --git a/src/bin/makepkg.rs b/src/bin/makepkg.rs index 9b3411b..1c5cd7f 100644 --- a/src/bin/makepkg.rs +++ b/src/bin/makepkg.rs @@ -1 +1,5 @@ -fn main() { eprintln!("shim: makepkg (not implemented)"); std::process::exit(70); } +//! Toolchain shim: `makepkg` (§16a). See `aur_build::shims`. + +fn main() { + std::process::exit(aur_build::shims::run("makepkg")); +} diff --git a/src/bin/mkarchroot.rs b/src/bin/mkarchroot.rs index f7c12e8..a4be6eb 100644 --- a/src/bin/mkarchroot.rs +++ b/src/bin/mkarchroot.rs @@ -1 +1,5 @@ -fn main() { eprintln!("shim: mkarchroot (not implemented)"); std::process::exit(70); } +//! Toolchain shim: `mkarchroot` (§16a). See `aur_build::shims`. + +fn main() { + std::process::exit(aur_build::shims::run("mkarchroot")); +} diff --git a/src/bin/pacman.rs b/src/bin/pacman.rs index bdcb13b..5f7a357 100644 --- a/src/bin/pacman.rs +++ b/src/bin/pacman.rs @@ -1 +1,5 @@ -fn main() { eprintln!("shim: pacman (not implemented)"); std::process::exit(70); } +//! Toolchain shim: `pacman` (§16a). See `aur_build::shims`. + +fn main() { + std::process::exit(aur_build::shims::run("pacman")); +} diff --git a/src/bin/repo-add.rs b/src/bin/repo-add.rs index 87abfd2..6714de6 100644 --- a/src/bin/repo-add.rs +++ b/src/bin/repo-add.rs @@ -1 +1,5 @@ -fn main() { eprintln!("shim: repo-add (not implemented)"); std::process::exit(70); } +//! Toolchain shim: `repo-add` (§16a). See `aur_build::shims`. + +fn main() { + std::process::exit(aur_build::shims::run("repo-add")); +} diff --git a/src/config.rs b/src/config.rs index 44b110c..05f9a74 100644 --- a/src/config.rs +++ b/src/config.rs @@ -46,6 +46,10 @@ pub struct Config { /// Directory prepended to PATH for child processes. The test harness puts /// the toolchain shims here (§16a). pub path_prepend: Option<PathBuf>, + /// Fixture manifest the shims should obey, exported as `AUR_SHIM_MANIFEST`. + pub shim_manifest: Option<PathBuf>, + /// Where shims record their invocations, exported as `AUR_SHIM_DIR`. + pub shim_dir: Option<PathBuf>, } impl Default for Config { @@ -67,6 +71,8 @@ impl Default for Config { gpg_bin: "gpg".into(), build_user: String::new(), path_prepend: None, + shim_manifest: None, + shim_dir: None, } } } @@ -96,6 +102,21 @@ impl Config { Ok(()) } + /// Environment for a child process: PATH with the shims in front, plus the + /// shim protocol variables (§16a). + pub fn child_env(&self, cmd: &mut std::process::Command) { + if let Some(dir) = &self.path_prepend { + let path = std::env::var("PATH").unwrap_or_default(); + cmd.env("PATH", format!("{}:{path}", dir.display())); + } + if let Some(m) = &self.shim_manifest { + cmd.env("AUR_SHIM_MANIFEST", m); + } + if let Some(d) = &self.shim_dir { + cmd.env("AUR_SHIM_DIR", d); + } + } + /// Create the directory tree the server needs. Idempotent. pub fn ensure_dirs(&self) -> anyhow::Result<()> { for d in [ @@ -14,6 +14,7 @@ pub mod hash; pub mod pkgver; pub mod recipe; pub mod review; +pub mod shims; pub mod time; pub mod watch; diff --git a/src/shims/mod.rs b/src/shims/mod.rs new file mode 100644 index 0000000..32ae7c9 --- /dev/null +++ b/src/shims/mod.rs @@ -0,0 +1,641 @@ +//! 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()); + } +} + +/// 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); + 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> -- -si<key> -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); + for p in &pkgs { + let path = write_package(&startdir, p, m)?; + println!("==> Creating package '{}'", path.file_name().unwrap().to_string_lossy()); + if m.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)); + } + } + } + Ok(0) +} + +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 = read_pkginfo(&bytes)?; + let (name, version, arch, extra) = parse_pkginfo(&pkginfo); + 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` (§10.1: plain text in a tar, no +/// libalpm needed). +pub fn read_pkginfo(pkg_bytes: &[u8]) -> Result<String, String> { + let dec = zstd::Decoder::new(std::io::Cursor::new(pkg_bytes)).map_err(|e| e.to_string())?; + let mut ar = tar::Archive::new(dec); + for e in ar.entries().map_err(|e| e.to_string())? { + let mut e = e.map_err(|e| e.to_string())?; + let name = e.path_bytes().to_vec(); + if name.ends_with(b".PKGINFO") { + use std::io::Read; + let mut s = String::new(); + e.read_to_string(&mut s).map_err(|e| e.to_string())?; + return Ok(s); + } + } + Err("no .PKGINFO in package".into()) +} + +pub fn read_buildinfo(pkg_bytes: &[u8]) -> Result<String, String> { + let dec = zstd::Decoder::new(std::io::Cursor::new(pkg_bytes)).map_err(|e| e.to_string())?; + let mut ar = tar::Archive::new(dec); + for e in ar.entries().map_err(|e| e.to_string())? { + let mut e = e.map_err(|e| e.to_string())?; + let name = e.path_bytes().to_vec(); + if name.ends_with(b".BUILDINFO") { + use std::io::Read; + let mut s = String::new(); + e.read_to_string(&mut s).map_err(|e| e.to_string())?; + return Ok(s); + } + } + Err("no .BUILDINFO in package".into()) +} + +fn parse_pkginfo(s: &str) -> (String, String, String, String) { + let mut name = String::new(); + let mut version = String::new(); + let mut arch = String::new(); + let mut groups = Vec::new(); + let mut deps = Vec::new(); + let mut optdeps = Vec::new(); + let mut provides = Vec::new(); + let mut conflicts = Vec::new(); + let mut replaces = Vec::new(); + let mut license = Vec::new(); + let mut desc = String::new(); + let mut url = String::new(); + for line in s.lines() { + let (k, v) = match line.split_once('=') { + Some((k, v)) => (k.trim(), v.trim()), + None => continue, + }; + match k { + "pkgname" => name = v.to_string(), + "pkgver" => version = v.to_string(), + "pkgarch" => arch = v.to_string(), + "pkgdesc" => desc = v.to_string(), + "url" => url = v.to_string(), + "license" => license.push(v.to_string()), + "depend" => deps.push(v.to_string()), + "optdepend" => optdeps.push(v.to_string()), + "checkdepend" => {} + "makedepend" => {} + "provides" => provides.push(v.to_string()), + "conflict" => conflicts.push(v.to_string()), + "replace" => replaces.push(v.to_string()), + "group" => groups.push(v.to_string()), + _ => {} + } + } + let mut extra = String::new(); + let mut push = |tag: &str, vals: &Vec<String>| { + if !vals.is_empty() { + extra.push_str(&format!("{tag}\n{}\n\n", vals.join("\n"))); + } + }; + push("%DESC%", &desc_vec(&desc)); + push("%URL%", &url_vec(&url)); + push("%LICENSE%", &license); + push("%DEPENDS%", &deps); + push("%OPTDEPENDS%", &optdeps); + push("%PROVIDES%", &provides); + push("%CONFLICTS%", &conflicts); + push("%REPLACES%", &replaces); + push("%GROUPS%", &groups); + (name, version, arch, extra) +} + +fn desc_vec(s: &str) -> Vec<String> { + if s.is_empty() { vec![] } else { vec![s.to_string()] } +} +fn url_vec(s: &str) -> Vec<String> { + if s.is_empty() { vec![] } else { vec![s.to_string()] } +} + +/// `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) +} |
