diff options
| -rw-r--r-- | src/git.rs | 75 | ||||
| -rw-r--r-- | src/watch/mirror.rs | 34 | ||||
| -rw-r--r-- | tests/detect.rs | 45 |
3 files changed, 142 insertions, 12 deletions
@@ -1,5 +1,6 @@ +use std::collections::BTreeMap; use std::path::Path; -use std::process::{Command, Output}; +use std::process::{Command, Output, Stdio}; use crate::error::{Error, Result}; @@ -144,6 +145,78 @@ pub fn read_blob(mirror: &Path, commit: &str, path: &str) -> Result<Vec<u8>> { Ok(out.stdout) } +pub fn cat_file_batch(mirror: &Path, oids: &[String]) -> Result<BTreeMap<String, Vec<u8>>> { + let mut out = BTreeMap::new(); + if oids.is_empty() { + return Ok(out); + } + let mut child = Command::new("git") + .current_dir(mirror) + .env("GIT_TERMINAL_PROMPT", "0") + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("LC_ALL", "C") + .args(["cat-file", "--batch"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| Error::git(format!("git cat-file --batch: {e}")))?; + + // The ids go in on their own thread: git streams blobs back as it reads the + // list, so a tree big enough to fill the pipe buffer would deadlock a + // write-everything-then-read-anything version here. + let mut stdin = child.stdin.take().expect("piped stdin"); + let input = oids.join("\n") + "\n"; + let writer = std::thread::spawn(move || { + use std::io::Write; + let _ = stdin.write_all(input.as_bytes()); + }); + + use std::io::{BufRead, BufReader, Read}; + let mut stderr = child.stderr.take().expect("piped stderr"); + let mut stdout = BufReader::new(child.stdout.take().expect("piped stdout")); + loop { + let mut header = String::new(); + if stdout.read_line(&mut header)? == 0 { + break; + } + let mut fields = header.trim_end_matches('\n').split(' '); + let id = fields.next().unwrap_or_default().to_string(); + match (fields.next(), fields.next().and_then(|s| s.parse().ok())) { + (Some("missing"), _) => continue, + (Some("blob"), Some(size)) => { + let mut body = vec![0u8; size]; + stdout.read_exact(&mut body)?; + // `--batch` puts an LF after every body, even an empty one. + let mut newline = [0u8; 1]; + stdout.read_exact(&mut newline)?; + out.insert(id, body); + } + _ => { + return Err(Error::git(format!( + "unreadable cat-file header {:?}", + header.trim_end() + ))) + } + } + } + + let _ = writer.join(); + let status = child.wait().map_err(|e| Error::git(e.to_string()))?; + // A missing object is a line in the output, not a non-zero exit; a non-zero + // exit means the process itself failed, which is not the caller's problem to + // distinguish from an absent blob. + if !status.success() { + let mut detail = Vec::new(); + stderr.read_to_end(&mut detail)?; + return Err(Error::git(format!( + "git cat-file --batch exited {status}: {}", + String::from_utf8_lossy(&detail).trim() + ))); + } + Ok(out) +} + pub fn materialize(mirror: &Path, commit: &str, dest: &Path) -> Result<()> { std::fs::create_dir_all(dest)?; let out = Command::new("git") diff --git a/src/watch/mirror.rs b/src/watch/mirror.rs index 89c175d..6616bc1 100644 --- a/src/watch/mirror.rs +++ b/src/watch/mirror.rs @@ -67,19 +67,33 @@ impl Tree { } pub fn read_tree(mirror: &Path, commit: &str) -> Result<Tree> { - if !git::has_commit(mirror, commit) { - return Err(Error::fail_closed(format!( - "commit {commit} is missing from the local mirror; history was rewritten" - ))); - } - let blobs = git::ls_tree(mirror, commit)?; + // 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<String> = blobs.iter().map(|(_, sha)| sha.clone()).collect(); + let contents = git::cat_file_batch(mirror, &oids)?; let mut files = BTreeMap::new(); - for (path, _) in &blobs { - let bytes = git::read_blob(mirror, commit, path)?; - if bytes.len() > 4 * 1024 * 1024 || !looks_textual(&bytes) { + for (path, sha) in &blobs { + let bytes = contents + .get(sha) + .ok_or_else(|| Error::not_found(format!("{path} not in mirror")))?; + if bytes.len() > 4 * 1024 * 1024 || !looks_textual(bytes) { continue; } - files.insert(path.clone(), String::from_utf8_lossy(&bytes).into_owned()); + files.insert(path.clone(), String::from_utf8_lossy(bytes).into_owned()); } Ok(Tree { blobs, files }) } diff --git a/tests/detect.rs b/tests/detect.rs index 86d1315..ef57121 100644 --- a/tests/detect.rs +++ b/tests/detect.rs @@ -5,7 +5,7 @@ use common::{git_add_commit, make_git_repo, params, Env, P}; use aur_build::db::{self, model::*, ReleaseRow}; use aur_build::review::{approve, candidates}; use aur_build::watch::detect::{check_pkgbase, Outcome}; -use aur_build::watch::mirror::{sync_mirror, Sync}; +use aur_build::watch::mirror::{read_tree, sync_mirror, Sync}; fn aur(env: &Env, name: &str) -> std::path::PathBuf { env.path(&format!("aur/{name}.git")) @@ -403,3 +403,46 @@ fn notices_are_not_duplicated_by_repeated_polling() { ); let _ = P::I(0); } + +#[test] +fn read_tree_returns_every_blob_from_one_batch_read() { + let env = Env::new(); + env.subscribe("foo"); + make_git_repo( + &aur(&env, "foo"), + &[ + ("PKGBUILD", &common::pkgbuild("foo", "1.0", "1", "")), + ("empty.txt", ""), + ("blob.bin", "\u{0}not text"), + ], + "initial", + ); + let url = format!("file://{}", aur(&env, "foo").display()); + sync_mirror(&env.cfg, &env.db, "foo", &url).unwrap(); + let mirror = env.cfg.mirror_path("foo"); + let head = aur_build::git::head(&mirror).unwrap(); + let tree = read_tree(&mirror, &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::<Vec<_>>() + ); +} + +#[test] +fn read_tree_fails_closed_when_the_commit_is_gone_from_the_mirror() { + let env = Env::new(); + env.subscribe("foo"); + seed(&env, "foo", "1.0", "1", ""); + let url = format!("file://{}", aur(&env, "foo").display()); + sync_mirror(&env.cfg, &env.db, "foo", &url).unwrap(); + let mirror = env.cfg.mirror_path("foo"); + + for gone in ["0123456789012345678901234567890123456789", "deadbeef"] { + let err = read_tree(&mirror, gone).unwrap_err().to_string(); + assert!(err.contains("missing from the local mirror"), "{gone}: {err}"); + } +} |
