Resolve abbreviated commit ids with at most two git commands
Browse filescommit_object ran one git rev-parse per object matching the prefix, so a short ?ref= or ?id= on a large repository could start hundreds of processes for one anonymous request. It now lists the candidates once (skipped for full ids) and peels them all with one cat-file --batch-check, still reading only full ids so a ref named like an id can't redirect it. A tag and its commit sharing a prefix now resolve to that commit, and uppercase ids work. git_with_input feeds a command's stdin from its own thread under the existing deadline and output cap. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Author
- Um9i vulgarmessiah@gmail.com
- Date
- 22 Nov 2026, 15:56
- Commit
- 85ff5e54028f
- Parent
- de97a29
2 files changed +147−19
| @@ -1,8 +1,10 @@ | ||
| //! Git queries on an already-open repository. Ref and path identities remain byte strings. | ||
| use super::{cached, encode, join, lossy}; | ||
| use gitv::{RepoDir, git}; | ||
| use gitv::{RepoDir, git, git_with_input}; | ||
| use std::{sync::Arc, time::Duration}; | ||
| /// Objects an abbreviated id may match before it counts as too ambiguous to look up. | ||
| const MAX_CANDIDATES: usize = 1000; | ||
| const ENTRY_FORMAT: &str = "%H%x00%ct%x00%cI%x00%cd%x00%s%x00%B"; | ||
| const ENTRY_DATE: &str = "--date=format:%-d %b %Y, %H:%M:%S %z"; | ||
| use std::{cell::OnceCell, collections::HashMap, ffi::OsStr, os::unix::ffi::OsStrExt}; | ||
| @@ -114,23 +116,35 @@ impl Reader { | ||
| /// The commit whose id is or starts with `id`, looked up among objects only: a branch or | ||
| /// tag that happens to be named like an id can't redirect it. Annotated tag objects peel to | ||
| /// their commit. An ambiguous abbreviation finds nothing. | ||
| /// their commit. An abbreviation that fits more than one commit finds nothing. | ||
| /// | ||
| /// At most two git commands, however many objects share the prefix: one lists them (skipped | ||
| /// for a full id) and one peels them all. Both are given full ids, which git always reads as | ||
| /// objects, never as ref names. | ||
| pub(super) fn commit_object(&self, id: &str) -> Option<String> { | ||
| if !(4..=64).contains(&id.len()) || !id.bytes().all(|b| b.is_ascii_hexdigit()) { | ||
| return None; | ||
| } | ||
| let id = id.to_ascii_lowercase(); | ||
| let candidates = self.git(&["rev-parse", &format!("--disambiguate={id}")])?; | ||
| let found: Vec<String> = candidates | ||
| .lines() | ||
| .filter_map(|oid| { | ||
| // A full id: git reads 40 or 64 hex digits as an object before any ref. | ||
| let peeled = self.git(&["rev-parse", "--verify", "--quiet", &format!("{oid}^{{commit}}")])?; | ||
| Some(peeled.trim().to_string()) | ||
| }) | ||
| .collect(); | ||
| match found.as_slice() { | ||
| [one] => Some(one.clone()), | ||
| let candidates = if matches!(id.len(), 40 | 64) { | ||
| id.clone() | ||
| } else { | ||
| self.git(&["rev-parse", &format!("--disambiguate={id}")])? | ||
| }; | ||
| let queries: String = | ||
| candidates.lines().take(MAX_CANDIDATES + 1).map(|oid| format!("{oid}^{{commit}}\n")).collect(); | ||
| if queries.is_empty() || queries.lines().count() > MAX_CANDIDATES { | ||
| return None; | ||
| } | ||
| let peeled = | ||
| git_with_input(&self.dir, &["cat-file", "--batch-check=%(objectname) %(objecttype)"], queries.as_bytes()) | ||
| .ok()?; | ||
| // Anything that isn't a commit-ish answers "<query> missing"; a tag and the commit it | ||
| // points at peel to the same commit, which counts once. | ||
| let commits: std::collections::BTreeSet<&[u8]> = | ||
| peeled.split(|b| *b == b'\n').filter_map(|line| line.strip_suffix(b" commit")).collect(); | ||
| match commits.into_iter().collect::<Vec<_>>().as_slice() { | ||
| [one] => Some(String::from_utf8_lossy(one).into_owned()), | ||
| _ => None, | ||
| } | ||
| } | ||
| @@ -313,6 +327,78 @@ mod tests { | ||
| } | ||
| } | ||
| /// A bare repository with 1000 commits on main, 3000 blobs and an annotated tag on the tip, | ||
| /// enough that 4-digit prefixes collide: commit with blob, and commit with commit. | ||
| fn crowded_repository() -> (Reader, std::path::PathBuf) { | ||
| use std::io::Write as _; | ||
| let dir = std::env::temp_dir().join(format!("gitv-web-crowded-{}", std::process::id())); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| assert!(gitv::git_base().args(["init", "-q", "--bare"]).arg(&dir).status().unwrap().success()); | ||
| let mut stream = String::new(); | ||
| for i in 0..3000 { | ||
| let data = format!("blob {i}\n"); | ||
| stream += &format!("blob\ndata {}\n{data}", data.len()); | ||
| } | ||
| for i in 0..1000 { | ||
| let message = format!("commit {i}\n"); | ||
| stream += &format!( | ||
| "commit refs/heads/main\ncommitter A <a@example.com> {} +0000\ndata {}\n{message}\n", | ||
| 1_700_000_000 + i, | ||
| message.len() | ||
| ); | ||
| } | ||
| stream += "tag v1\nfrom refs/heads/main\ntagger A <a@example.com> 1800000000 +0000\ndata 3\nv1\n"; | ||
| let mut import = gitv::git_base() | ||
| .arg("--git-dir") | ||
| .arg(&dir) | ||
| .args(["fast-import", "--quiet"]) | ||
| .stdin(std::process::Stdio::piped()) | ||
| .spawn() | ||
| .unwrap(); | ||
| import.stdin.take().unwrap().write_all(stream.as_bytes()).unwrap(); | ||
| assert!(import.wait().unwrap().success()); | ||
| (Reader::new(RepoDir::at(&dir).unwrap()), dir) | ||
| } | ||
| #[test] | ||
| fn abbreviated_ids_find_commits_among_other_objects() { | ||
| let (reader, dir) = crowded_repository(); | ||
| let listing = | ||
| reader.git(&["cat-file", "--batch-all-objects", "--batch-check=%(objectname) %(objecttype)"]).unwrap(); | ||
| let mut by_prefix: HashMap<&str, Vec<(&str, &str)>> = HashMap::new(); | ||
| for line in listing.lines() { | ||
| let (oid, kind) = line.split_once(' ').unwrap(); | ||
| by_prefix.entry(&oid[..4]).or_default().push((oid, kind)); | ||
| } | ||
| let commits = |group: &[(&str, &str)]| group.iter().filter(|(_, k)| *k == "commit").count(); | ||
| // One commit sharing its prefix with a blob: the commit is found. | ||
| let (prefix, group) = by_prefix | ||
| .iter() | ||
| .find(|(_, g)| commits(g) == 1 && g.iter().any(|(_, k)| *k == "blob")) | ||
| .expect("a commit and a blob share a prefix"); | ||
| let commit = group.iter().find(|(_, k)| *k == "commit").unwrap().0; | ||
| assert_eq!(reader.commit_object(prefix).as_deref(), Some(commit)); | ||
| assert_eq!(reader.commit_object(&prefix.to_uppercase()).as_deref(), Some(commit), "case doesn't matter"); | ||
| // Two commits sharing a prefix: ambiguous, so nothing. | ||
| let (prefix, _) = by_prefix.iter().find(|(_, g)| commits(g) >= 2).expect("two commits share a prefix"); | ||
| assert_eq!(reader.commit_object(prefix), None); | ||
| // A blob alone is no commit; a full id is looked up directly. | ||
| let (blob, _) = by_prefix.values().flatten().find(|(_, k)| *k == "blob").unwrap(); | ||
| assert_eq!(reader.commit_object(blob), None); | ||
| assert_eq!(reader.commit_object(commit).as_deref(), Some(commit)); | ||
| // An annotated tag peels to its commit, by full or abbreviated id. | ||
| let tip = reader.git(&["rev-parse", "main"]).unwrap().trim().to_string(); | ||
| let tag = reader.git(&["rev-parse", "v1"]).unwrap().trim().to_string(); | ||
| assert_ne!(tag, tip); | ||
| assert_eq!(reader.commit_object(&tag).as_deref(), Some(tip.as_str())); | ||
| assert_eq!(reader.commit_object(&tag[..12]).as_deref(), Some(tip.as_str())); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn control_characters_in_git_names_do_not_shift_fields() { | ||
| let head = Head::parse("commit\0First\x1fLast\0timestamp\0date\0subject\x1fmore").unwrap(); | ||
+48−6
| @@ -183,6 +183,14 @@ pub fn git<S: AsRef<OsStr>>(git_dir: &RepoDir, args: &[S]) -> Result<Vec<u8>, St | ||
| } | ||
| } | ||
| /// Like [`git`], with `input` written to the command's stdin, as for `cat-file --batch-check`. | ||
| pub fn git_with_input<S: AsRef<OsStr>>(git_dir: &RepoDir, args: &[S], input: &[u8]) -> Result<Vec<u8>, String> { | ||
| match run_git(git_dir, args, Some(input), GIT_OUTPUT_LIMIT, GIT_TIMEOUT)? { | ||
| (output, false) => Ok(output), | ||
| (_, true) => Err("git output too large".into()), | ||
| } | ||
| } | ||
| /// Like [`git`], but output beyond `cap` bytes stops the command and comes back truncated, with | ||
| /// `true` to say so, rather than as an error. | ||
| pub fn git_capped<S: AsRef<OsStr>>(git_dir: &RepoDir, args: &[S], cap: usize) -> Result<(Vec<u8>, bool), String> { | ||
| @@ -195,19 +203,40 @@ pub fn git_capped_for<S: AsRef<OsStr>>( | ||
| args: &[S], | ||
| cap: usize, | ||
| timeout: Duration, | ||
| ) -> Result<(Vec<u8>, bool), String> { | ||
| run_git(git_dir, args, None, cap, timeout) | ||
| } | ||
| fn run_git<S: AsRef<OsStr>>( | ||
| git_dir: &RepoDir, | ||
| args: &[S], | ||
| input: Option<&[u8]>, | ||
| cap: usize, | ||
| timeout: Duration, | ||
| ) -> Result<(Vec<u8>, bool), String> { | ||
| let deadline = Instant::now() + timeout.min(GIT_TIMEOUT); | ||
| let deadline = git_dir.deadline.map_or(deadline, |limit| limit.min(deadline)); | ||
| if Instant::now() >= deadline { | ||
| return Err("page time budget exhausted".into()); | ||
| } | ||
| let mut child = git_command(git_dir) | ||
| .args(args) | ||
| .stdout(Stdio::piped()) | ||
| .stderr(Stdio::null()) | ||
| .spawn() | ||
| .map_err(|e| format!("cannot run git: {e}"))?; | ||
| let mut command = git_command(git_dir); | ||
| command.args(args).stdout(Stdio::piped()).stderr(Stdio::null()); | ||
| if input.is_some() { | ||
| command.stdin(Stdio::piped()); | ||
| } | ||
| let mut child = command.spawn().map_err(|e| format!("cannot run git: {e}"))?; | ||
| let mut stdout = child.stdout.take().ok_or("git has no stdout")?; | ||
| // Written from its own thread, so git can't block on a full stdout while we block on a full | ||
| // stdin. A killed git fails the write (SIGPIPE is ignored in Rust programs), ending the thread. | ||
| let writer = match (input, child.stdin.take()) { | ||
| (Some(input), Some(mut stdin)) => { | ||
| let input = input.to_vec(); | ||
| Some(thread::spawn(move || { | ||
| let _ = std::io::Write::write_all(&mut stdin, &input); | ||
| })) | ||
| } | ||
| _ => None, | ||
| }; | ||
| let child = Arc::new(Mutex::new(child)); | ||
| let kill = |child: &Mutex<Child>| { | ||
| // The child is never reaped while the lock is held, so this can't hit a reused pid. | ||
| @@ -248,6 +277,9 @@ pub fn git_capped_for<S: AsRef<OsStr>>( | ||
| }; | ||
| let _ = finished.send(()); | ||
| let _ = watchdog.join(); | ||
| if let Some(writer) = writer { | ||
| let _ = writer.join(); | ||
| } | ||
| read.map_err(|e| format!("cannot read git output: {e}"))?; | ||
| let status = status?; | ||
| if overflow { | ||
| @@ -470,6 +502,16 @@ mod tests { | ||
| let _ = fs::remove_dir_all(&dir.path); | ||
| } | ||
| #[test] | ||
| fn input_reaches_git_even_when_it_outgrows_a_pipe() { | ||
| let (dir, oid) = repo_with_blob("input", 10); | ||
| // Far more queries than a pipe buffers, so writing and reading must overlap. | ||
| let queries = format!("{oid}\n").repeat(20_000); | ||
| let out = git_with_input(&dir, &["cat-file", "--batch-check"], queries.as_bytes()).unwrap(); | ||
| assert_eq!(out, format!("{oid} blob 10\n").repeat(20_000).into_bytes()); | ||
| let _ = fs::remove_dir_all(&dir.path); | ||
| } | ||
| #[test] | ||
| fn an_open_repository_stays_bound_to_its_directory() { | ||
| // Open one repository, then swap another into its path: git must still see the first. | ||