use std::collections::BTreeMap; use std::path::Path; use crate::config::Config; use crate::db::{self, Db}; use crate::error::{Error, Missing, Result}; use crate::git; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Sync { Gone, Unchanged { head: String }, Fetched { head: String, previous: Option }, Cloned { head: String }, } /// Detection calls it to move the mirror; the test that pins it drives a real sync. /// /// Module-internal in a production build, `pub` only under `test-support`: /// one body behind two visibility declarations, exactly one of which compiles. #[cfg(feature = "test-support")] pub fn sync_mirror(cfg: &Config, db: &Db, name: &str, url: &str) -> Result { sync_mirror_impl(cfg, db, name, url) } #[cfg(not(feature = "test-support"))] pub(crate) fn sync_mirror(cfg: &Config, db: &Db, name: &str, url: &str) -> Result { sync_mirror_impl(cfg, db, name, url) } fn sync_mirror_impl(cfg: &Config, db: &Db, name: &str, url: &str) -> Result { let mirror = cfg.mirror_path(name); let known_head = db::get_pkgbase(db, name)?.and_then(|p| p.aur_head.clone()); if !mirror.exists() { git::clone(url, &mirror)?; let head = git::head(&mirror)?; record(db, name, &head, &mirror)?; return Ok(Sync::Cloned { head }); } let Some(remote) = git::ls_remote_head(url)? else { return Ok(Sync::Gone) }; let local = git::head(&mirror).ok(); if let Some(l) = &local { if *l == remote { return Ok(Sync::Unchanged { head: remote }); } } let head = git::fetch_head(&mirror)?; record(db, name, &head, &mirror)?; Ok(Sync::Fetched { head, previous: known_head }) } fn record(db: &Db, name: &str, head: &str, mirror: &Path) -> Result<()> { let pb = db::get_pkgbase(db, name)?.ok_or_else(|| Error::not_found(Missing::Pkgbase(name.to_string())))?; db::set_aur_head(&db.writer, pb.id, head, &mirror.display().to_string()) } #[derive(Debug, Clone)] pub(crate) struct Tree { pub blobs: Vec<(String, String)>, pub files: BTreeMap, } impl Tree { pub fn recipe_hash(&self) -> String { crate::hash::recipe_hash(&self.blobs) } pub(crate) fn json_list(&self) -> String { serde_json::to_string(&self.blobs).unwrap_or_else(|_| "[]".into()) } } pub(crate) fn read_tree(mirror: &Path, commit: &str) -> Result { // One `ls-tree` and one `cat-file --batch` for the whole tree, so the number // of files a recipe ships does not decide how many processes a read costs. // A commit that is gone from the mirror surfaces here, from `ls-tree`, rather // than from a separate `cat-file -e` probe first. let blobs = match git::ls_tree(mirror, commit) { Ok(blobs) => blobs, Err(e) => { let text = e.to_string().to_lowercase(); if text.contains("not a tree object") || text.contains("not a valid object name") { return Err(Error::fail_closed(format!( "commit {commit} is missing from the local mirror; history was rewritten" ))); } return Err(e); } }; let oids: Vec = blobs.iter().map(|(_, sha)| sha.clone()).collect(); let contents = git::cat_file_batch(mirror, &oids)?; let mut files = BTreeMap::new(); for (path, sha) in &blobs { let bytes = contents.get(sha).ok_or_else(|| Error::not_found(Missing::MirrorPath(path.to_string())))?; if bytes.len() > 4 * 1024 * 1024 || !looks_textual(bytes) { continue; } files.insert(path.clone(), String::from_utf8_lossy(bytes).into_owned()); } Ok(Tree { blobs, files }) } fn looks_textual(b: &[u8]) -> bool { !b[..b.len().min(512)].contains(&0) } pub(crate) fn read_file(mirror: &Path, commit: &str, path: &str) -> Result> { git::read_blob(mirror, commit, path) } #[cfg(test)] mod tests { use super::*; /// A throwaway repo with these files committed, and its tip. /// /// Deliberately minimal: `read_tree` only ever needs a directory git will /// answer for, so the test does not stand up a mirror, a database or a /// config to ask it a question about one tree. fn repo(files: &[(&str, &[u8])]) -> (std::path::PathBuf, String) { let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); let dir = std::env::temp_dir().join(format!("aur-read-tree-{}-{}", std::process::id(), nonce)); std::fs::create_dir_all(&dir).unwrap(); let git = |args: &[&str]| { let out = std::process::Command::new("git") .arg("-C") .arg(&dir) .args(args) .env("GIT_CONFIG_NOSYSTEM", "1") .env("HOME", &dir) .output() .unwrap(); assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr)); }; git(&["init", "-q", "-b", "master"]); git(&["config", "user.email", "test@example.invalid"]); git(&["config", "user.name", "test"]); for (name, body) in files { std::fs::write(dir.join(name), body).unwrap(); } git(&["add", "-A"]); git(&["commit", "-q", "-m", "initial"]); let head = std::fs::read_to_string(dir.join(".git/refs/heads/master")).unwrap(); (dir, head.trim().to_string()) } #[test] fn read_tree_returns_every_blob_from_one_batch_read() { let (dir, head) = repo(&[ ( "PKGBUILD", b"pkgbase=foo pkgver=1.0 pkgrel=1 ", ), ("empty.txt", b""), ("blob.bin", b"\x00not text"), ]); let tree = read_tree(&dir, &head).unwrap(); assert!(tree.files["PKGBUILD"].contains("pkgver=1.0")); assert_eq!(tree.files["empty.txt"], "", "an empty blob is a file, not a miss"); assert!( !tree.files.contains_key("blob.bin"), "a NUL in the first block means it is not text: {:?}", tree.files.keys().collect::>() ); assert!(tree.blobs.iter().any(|(p, _)| p == "blob.bin"), "binary blobs are still listed"); std::fs::remove_dir_all(&dir).ok(); } #[test] fn read_tree_fails_closed_when_the_commit_is_gone_from_the_mirror() { let (dir, _head) = repo(&[( "PKGBUILD", b"pkgbase=foo ", )]); for gone in ["0123456789012345678901234567890123456789", "deadbeef"] { let err = read_tree(&dir, gone).unwrap_err().to_string(); assert!(err.contains("missing from the local mirror"), "{gone}: {err}"); } std::fs::remove_dir_all(&dir).ok(); } }