//! Git queries on an already-open repository. Ref and path identities remain byte strings. use std::{sync::Arc, time::Duration}; use gitv_core::{RepoDir, git_capped, git_with_input}; use crate::cache::cached; use crate::urls::{encode, join, lossy}; /// The most output any one git command run for a page may produce. Pages render 16 at a time /// in a service capped at 640 MiB, so this keeps a huge folder or ref list in a public /// repository from running the server out of memory; past it, the page is "not found". It /// fits about 80,000 folder entries or 60,000 refs, and files shown are capped far lower. pub(crate) const PAGE_OUTPUT_LIMIT: usize = 8 << 20; /// 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}; pub(super) struct Reader { pub(super) dir: RepoDir, refs: OnceCell, } /// The newest commit on a ref: full hash, subject, author, unix time, short date. pub(super) struct Head { pub(super) oid: String, pub(super) subject: String, pub(super) author: String, pub(super) stamp: String, pub(super) date: String, } impl Head { pub(super) const FORMAT: &'static str = "--format=%H%x00%an%x00%ct%x00%cd%x00%s"; pub(super) fn parse(out: &str) -> Option { let f: Vec<&str> = out.trim_end_matches('\n').splitn(5, '\0').collect(); let [oid, author, stamp, date, subject] = <[&str; 5]>::try_from(f).ok()?; Some(Head { oid: oid.into(), subject: subject.into(), author: author.into(), stamp: stamp.into(), date: date.into(), }) } } /// The branches and tags, from one `git for-each-ref`. #[derive(Default)] struct Refs { /// Branch names, without `refs/heads/`, in git's order. heads: Vec>, /// Tag names, without `refs/tags/`, in git's order. tags: Vec>, /// The commit each full ref name names, for those that name one directly or through one /// annotated tag. commits: HashMap, String>, /// Each tag and the object it ends at after one peel, as history labels use it. tag_targets: Vec<(Vec, String)>, } impl Refs { /// Parse `refname NUL objectname NUL objecttype NUL *objectname NUL *objecttype` lines. A ref /// name can hold neither a NUL nor a newline. fn parse(out: &[u8]) -> Refs { let mut refs = Refs::default(); for line in out.split(|b| *b == b'\n').filter(|l| !l.is_empty()) { let Ok([name, oid, kind, peeled, peeled_kind]) = <[&[u8]; 5]>::try_from(line.split(|b| *b == 0).collect::>()) else { continue; }; let text = |bytes: &[u8]| String::from_utf8_lossy(bytes).into_owned(); let commit = match (kind, peeled_kind) { (b"commit", _) => Some(oid), (b"tag", b"commit") => Some(peeled), _ => None, }; if let Some(commit) = commit { refs.commits.insert(name.to_vec(), text(commit)); } if let Some(branch) = name.strip_prefix(b"refs/heads/") { refs.heads.push(branch.to_vec()); } else if let Some(tag) = name.strip_prefix(b"refs/tags/") { refs.tags.push(tag.to_vec()); let target = if peeled.is_empty() { oid } else { peeled }; refs.tag_targets.push((tag.to_vec(), text(target))); } } refs } } impl Reader { pub(super) fn new(dir: RepoDir) -> Self { Self { dir, refs: OnceCell::new() } } /// A git command's output, or `None` if it fails or passes [`PAGE_OUTPUT_LIMIT`]. pub(super) fn git_bytes>(&self, args: &[S]) -> Option> { match git_capped(&self.dir, args, PAGE_OUTPUT_LIMIT) { Ok((output, false)) => Some(output), _ => None, } } pub(super) fn git>(&self, args: &[S]) -> Option { self.git_bytes(args).map(|out| String::from_utf8_lossy(&out).into_owned()) } /// The branch HEAD names, or when that branch doesn't exist, main, master or the first branch. pub(super) fn default_ref(&self) -> Vec { let head = self.git_bytes(&["symbolic-ref", "HEAD"]).unwrap_or_default(); let heads = self.heads(); let target = head.strip_suffix(b"\n").and_then(|h| h.strip_prefix(b"refs/heads/")); let choice = target .into_iter() .chain([b"main".as_slice(), b"master"]) .find(|name| heads.iter().any(|h| h == name)) .or_else(|| heads.first().map(Vec::as_slice)); choice.map_or_else(|| b"HEAD".to_vec(), |name| self.branch_ref(name)) } /// Every branch and tag, read with one git command the first time any is needed. fn refs(&self) -> &Refs { self.refs.get_or_init(|| { let format = "--format=%(refname)%00%(objectname)%00%(objecttype)%00%(*objectname)%00%(*objecttype)"; Refs::parse(&self.git_bytes(&["for-each-ref", format, "refs/heads", "refs/tags"]).unwrap_or_default()) }) } pub(super) fn heads(&self) -> &[Vec] { &self.refs().heads } pub(super) fn tags(&self) -> &[Vec] { &self.refs().tags } /// The commit a reference names, in this order: /// /// - `refs/heads/NAME` or `refs/tags/NAME` for an existing branch or tag: the form links /// use whenever a plain name could be misread (see [`Reader::branch_ref`]); /// - a full commit id, always as an object, whatever refs are named; /// - a branch, then a tag, by exact name, so any name git allows works and none is read as /// revision syntax; /// - `HEAD`, then an abbreviated commit id, again only as an object. pub(super) fn resolve(&self, reference: &[u8]) -> Option { let is_head = |n: &[u8]| self.heads().iter().any(|h| h == n); let is_tag = |n: &[u8]| self.tags().iter().any(|h| h == n); let hex = reference.iter().all(u8::is_ascii_hexdigit); let full = if reference.strip_prefix(b"refs/heads/").is_some_and(is_head) || reference.strip_prefix(b"refs/tags/").is_some_and(is_tag) { reference.to_vec() } else if hex && matches!(reference.len(), 40 | 64) { return self.commit_object(std::str::from_utf8(reference).ok()?); } else if is_head(reference) { [b"refs/heads/".as_slice(), reference].concat() } else if is_tag(reference) { [b"refs/tags/".as_slice(), reference].concat() } else if reference == b"HEAD" { reference.to_vec() } else if hex && reference.len() >= 4 { return self.commit_object(std::str::from_utf8(reference).ok()?); } else { return None; }; // Branches and tags that name a commit (directly, or through one annotated tag) were // answered by the ref listing; anything else is peeled by git as before. if let Some(commit) = self.refs().commits.get(&full) { return Some(commit.clone()); } let spec = [full.as_slice(), b"^{commit}"].concat(); let args = ["rev-parse", "--verify", "--quiet", "--end-of-options"].map(OsStr::new); self.git(&[args.as_slice(), &[OsStr::from_bytes(&spec)]].concat()).map(|s| s.trim().into()) } /// 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 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 { if !(4..=64).contains(&id.len()) || !id.bytes().all(|b| b.is_ascii_hexdigit()) { return None; } let id = id.to_ascii_lowercase(); 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 " 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::>().as_slice() { [one] => Some(String::from_utf8_lossy(one).into_owned()), _ => None, } } /// Whether a plain name in a link would resolve to itself: it mustn't look like a full /// commit id or a qualified ref, which [`Reader::resolve`] reads first. fn plain_is_safe(name: &[u8]) -> bool { let full_id = matches!(name.len(), 40 | 64) && name.iter().all(u8::is_ascii_hexdigit); !full_id && !name.starts_with(b"refs/") && name != b"HEAD" } pub(super) fn branch_ref(&self, name: &[u8]) -> Vec { if Self::plain_is_safe(name) { name.to_vec() } else { [b"refs/heads/".as_slice(), name].concat() } } pub(super) fn tag_ref(&self, name: &[u8]) -> Vec { if Self::plain_is_safe(name) && !self.heads().iter().any(|h| h == name) { name.to_vec() } else { [b"refs/tags/".as_slice(), name].concat() } } /// The newest commit on `rev` that touched `path` (the whole tree when empty). Walking /// history for a path can be slow, so answers for a fixed commit are cached. pub(super) fn latest(&self, rev: &str, path: &[u8]) -> Option { Head::parse(&self.latest_raw(rev, path)?) } /// [`Reader::latest`] as git printed it, for callers that cache it themselves. pub(super) fn latest_raw(&self, rev: &str, path: &[u8]) -> Option { let lookup = || { let mut args: Vec<&OsStr> = ["log", "-1", "--date=format:%-d %b %Y", Head::FORMAT, rev, "--"].map(OsStr::new).to_vec(); if !path.is_empty() { args.push(OsStr::from_bytes(path)); } self.git(&args).filter(|out| !out.trim().is_empty()) }; let is_oid = rev.len() >= 40 && rev.bytes().all(|b| b.is_ascii_hexdigit()); if is_oid { Some(cached(format!("latest:{}:{rev}:{}", self.dir.path.display(), encode(path)), lookup)?.to_string()) } else { lookup() } } /// Resolve just the displayed entries. A warm page needs no history query. On a cold /// page one bounded linear walk handles recent changes, with Git's path-specific /// history simplification retained for anything older or behind a merge. pub(super) fn entry_histories(&self, commit: &str, dir: &[u8], names: &[&[u8]]) -> Vec>> { let recent = OnceCell::new(); names .iter() .map(|&name| { let path = join(dir, name); let key = format!("entry-commit:{}:{commit}:{}", self.dir.path.display(), encode(&path)); cached(key, || { if names.len() > 1 { let matches = recent.get_or_init(|| self.recent_entry_histories(commit, dir, names)); if let Some(record) = matches.as_ref().and_then(|m| m.get(name)) { return Some(record.to_string()); } } let format = format!("--format={ENTRY_FORMAT}"); let args = ["log", "-1", ENTRY_DATE, &format, commit, "--"].map(OsStr::new); self.git(&[args.as_slice(), &[OsStr::from_bytes(&path)]].concat()).filter(|out| !out.is_empty()) }) }) .collect() } fn recent_entry_histories<'a>( &self, commit: &str, dir: &[u8], names: &[&'a [u8]], ) -> Option>> { let format = format!("--format=%x00%P%x00{ENTRY_FORMAT}"); let window = format!("-{RECENT_WINDOW}"); let args = [ "log", &window, "--first-parent", "--diff-merges=off", "--root", "--no-renames", "--name-only", "-z", ENTRY_DATE, &format, commit, "--", ]; // Output past the cap is cut off; what came before it is still exact, and anything not // found in it is looked up on its own. let (bytes, _) = gitv_core::git_capped_for(&self.dir, &args, RECENT_BYTES, Duration::from_secs(1)).ok()?; Some(recent_changes(&bytes, dir, names)) } /// Commits reachable from `commit`. A commit's history never changes, so the count is cached. pub(super) fn commit_count(&self, commit: &str) -> usize { let key = format!("count:{}:{commit}", self.dir.path.display()); cached(key, || self.git(&["rev-list", "--count", commit, "--"]).map(|s| s.trim().to_string())) .and_then(|count| count.parse().ok()) .unwrap_or(0) } /// Tag names grouped by the commit (or other object) they point at, for labelling history. pub(super) fn tags_by_commit(&self) -> HashMap>> { let mut found: HashMap>> = HashMap::new(); for (name, target) in &self.refs().tag_targets { found.entry(target.clone()).or_default().push(name.clone()); } found } } /// Linear history a cold folder listing reads in one walk, newest first, before looking up /// whatever it didn't find one entry at a time. const RECENT_WINDOW: usize = 1000; /// The most of that walk's output read; a cut-off walk still answers for what it covered. const RECENT_BYTES: usize = 4 << 20; /// A record begins with an empty NUL field (impossible as a pathname), followed by /// parents, six metadata fields, then Git's newline and NUL-terminated changed paths. /// /// Records are newest first, so the first record naming an entry is its latest change. The /// walk ends at the first merge, past which first-parent order and Git's per-path history can /// disagree. Output cut off part way (at the byte cap) ends the walk where it was cut: every /// field is NUL-terminated, so a partial one is never read as a shorter name. fn recent_changes<'a>(mut data: &[u8], dir: &[u8], names: &[&'a [u8]]) -> HashMap<&'a [u8], Arc> { fn field<'b>(data: &mut &'b [u8]) -> Option<&'b [u8]> { let end = data.iter().position(|&b| b == 0)?; let value = &data[..end]; *data = &data[end + 1..]; Some(value) } let mut pending: std::collections::HashSet<_> = names.iter().copied().collect(); let mut found = HashMap::new(); let mut walk = || -> Option<()> { while !data.is_empty() && !pending.is_empty() { data = data.strip_prefix(b"\0")?; if field(&mut data)?.contains(&b' ') { break; } let start = data; for _ in 0..6 { field(&mut data)?; } let metadata = &start[..start.len() - data.len() - 1]; let record = OnceCell::new(); if let Some(paths) = data.strip_prefix(b"\n") { data = paths; while !data.is_empty() && data[0] != 0 { let path = field(&mut data)?; let relative = if dir.is_empty() { path } else { let Some(rest) = path.strip_prefix(dir).and_then(|r| r.strip_prefix(b"/")) else { continue }; rest }; let name = relative.split(|&b| b == b'/').next()?; if let Some(name) = pending.take(name) { let value = record.get_or_init(|| Arc::::from(lossy(metadata))); found.insert(name, Arc::clone(value)); } } } } Some(()) }; let _ = walk(); found } #[cfg(test)] mod tests { use super::*; #[test] fn batch_uses_newest_change_and_stops_at_the_first_merge() { let input = b"\0parent\0tip\0time\0iso\0date\0subject\0full\nmessage\0\nother/file\0docs/\xff/new\0docs/\nfile\0\0older\0previous\0time\0iso\0date\0subject\0message\0\ndocs/\xff/old\0\0one two\0merge\0time\0iso\0date\0subject\0message\0\ndocs/side\0"; let names = [b"\xff".as_slice(), b"\nfile", b"side", b"file"]; let result = recent_changes(input, b"docs", &names); assert_eq!(result.len(), 2); for name in &names[..2] { assert_eq!(&*result[name], "tip\0time\0iso\0date\0subject\0full\nmessage"); } } /// A bare repository built from a `git fast-import` stream, and its folder. fn imported(name: &str, stream: &str) -> (Reader, std::path::PathBuf) { use std::io::Write as _; let dir = std::env::temp_dir().join(format!("gitv-web-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); assert!(gitv_core::git_base().args(["init", "-q", "--bare"]).arg(&dir).status().unwrap().success()); let mut import = gitv_core::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) } /// 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) { 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 {} +0000\ndata {}\n{message}\n", 1_700_000_000 + i, message.len() ); } stream += "tag v1\nfrom refs/heads/main\ntagger A 1800000000 +0000\ndata 3\nv1\n"; imported("crowded", &stream) } #[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 one_walk_finds_entries_changed_long_ago() { // old.txt is written once, then busy.txt changes in each of 30 later commits. let mut stream = String::from( "commit refs/heads/main\ncommitter A 1700000000 +0000\ndata 6\nfirst\nM 644 inline old.txt\ndata 4\nold\n\n", ); for i in 1..=30 { let message = format!("change {i}\n"); let content = format!("{i}\n"); stream += &format!( "commit refs/heads/main\ncommitter A {} +0000\ndata {}\n{message}M 644 inline busy.txt\ndata {}\n{content}\n", 1_700_000_000 + i, message.len(), content.len() ); } let (reader, dir) = imported("walk", &stream); let tip = reader.git(&["rev-parse", "main"]).unwrap().trim().to_string(); let first = reader.git(&["rev-list", "--max-parents=0", "main"]).unwrap().trim().to_string(); let names = [b"old.txt".as_slice(), b"busy.txt"]; let found = reader.recent_entry_histories(&tip, b"", &names).unwrap(); assert!(found[b"old.txt".as_slice()].starts_with(&first), "found in the one walk"); assert!(found[b"busy.txt".as_slice()].starts_with(&tip)); let _ = std::fs::remove_dir_all(&dir); } #[test] fn a_walk_cut_off_part_way_keeps_what_it_read() { let input = b"\0p\0tip\0t\0i\0d\0s\0m\0\na.txt\0b.txt\0\0p\0older\0t\0i\0d\0s\0m\0\nc.t"; let names = [b"a.txt".as_slice(), b"b.txt", b"c.txt", b"c.t"]; let result = recent_changes(input, b"", &names); assert_eq!(result.len(), 2, "a and b from the whole record; nothing from the cut-off name"); assert!(result[b"a.txt".as_slice()].starts_with("tip")); } #[test] fn one_ref_listing_resolves_what_it_can_and_leaves_the_rest_to_git() { let out = b"refs/heads/main\0c1\0commit\0\0\n\ refs/heads/odd-\xff\0c2\0commit\0\0\n\ refs/tags/v1\0t1\0tag\0c1\0commit\n\ refs/tags/nested\0t2\0tag\0t1\0tag\n\ refs/tags/tree\0r1\0tree\0\0\n"; let refs = Refs::parse(out); assert_eq!(refs.heads, [b"main".to_vec(), b"odd-\xff".to_vec()]); assert_eq!(refs.tags, [b"v1".to_vec(), b"nested".to_vec(), b"tree".to_vec()]); assert_eq!(refs.commits[b"refs/heads/odd-\xff".as_slice()], "c2"); assert_eq!(refs.commits[b"refs/tags/v1".as_slice()], "c1", "an annotated tag peels to its commit"); assert!(!refs.commits.contains_key(b"refs/tags/nested".as_slice()), "a tag of a tag is left to git"); assert!(!refs.commits.contains_key(b"refs/tags/tree".as_slice()), "a tag of a tree is no commit"); assert_eq!(refs.tag_targets[0], (b"v1".to_vec(), "c1".to_string())); } #[test] fn control_characters_in_git_names_do_not_shift_fields() { let head = Head::parse("commit\0First\x1fLast\0timestamp\0date\0subject\x1fmore").unwrap(); assert_eq!(head.author, "First\x1fLast"); assert_eq!(head.stamp, "timestamp"); assert_eq!(head.subject, "subject\x1fmore"); } }