Read branches and tags with one git command per page
Browse filesBranches and tags were listed by two for-each-ref calls, resolving a branch or tag ran rev-parse, and history pages listed tags a third time for their labels. One for-each-ref now lists both with the commit each names, so branch and tag pages resolve without rev-parse and history labels need no extra call: by inspection, a warm folder page runs three git commands instead of five. Tags of tags and refs that don't name a commit are still peeled by git. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Author
- Um9i vulgarmessiah@gmail.com
- Date
- 22 Nov 2026, 16:18
- Commit
- 91e1c783521a
- Parent
- f5068ab
1 file changed +81−21
| @@ -15,8 +15,7 @@ use std::{cell::OnceCell, collections::HashMap, ffi::OsStr, os::unix::ffi::OsStr | ||
| pub(super) struct Reader { | ||
| pub(super) dir: RepoDir, | ||
| heads: OnceCell<Vec<Vec<u8>>>, | ||
| tags: OnceCell<Vec<Vec<u8>>>, | ||
| refs: OnceCell<Refs>, | ||
| } | ||
| /// The newest commit on a ref: full hash, subject, author, unix time, short date. | ||
| @@ -43,9 +42,55 @@ impl Head { | ||
| } | ||
| } | ||
| /// 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<Vec<u8>>, | ||
| /// Tag names, without `refs/tags/`, in git's order. | ||
| tags: Vec<Vec<u8>>, | ||
| /// The commit each full ref name names, for those that name one directly or through one | ||
| /// annotated tag. | ||
| commits: HashMap<Vec<u8>, String>, | ||
| /// Each tag and the object it ends at after one peel, as history labels use it. | ||
| tag_targets: Vec<(Vec<u8>, 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::<Vec<_>>()) | ||
| 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, heads: OnceCell::new(), tags: OnceCell::new() } | ||
| Self { dir, refs: OnceCell::new() } | ||
| } | ||
| pub(super) fn git_bytes<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<Vec<u8>> { | ||
| git(&self.dir, args).ok() | ||
| @@ -68,20 +113,19 @@ impl Reader { | ||
| choice.map_or_else(|| b"HEAD".to_vec(), |name| self.branch_ref(name)) | ||
| } | ||
| fn list_refs(&self, namespace: &str) -> Vec<Vec<u8>> { | ||
| self.git_bytes(&["for-each-ref", "--format=%(refname:lstrip=2)", namespace]) | ||
| .unwrap_or_default() | ||
| .split(|b| *b == b'\n') | ||
| .filter(|r| !r.is_empty()) | ||
| .map(<[u8]>::to_vec) | ||
| .collect() | ||
| /// 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<u8>] { | ||
| self.heads.get_or_init(|| self.list_refs("refs/heads")) | ||
| &self.refs().heads | ||
| } | ||
| pub(super) fn tags(&self) -> &[Vec<u8>] { | ||
| self.tags.get_or_init(|| self.list_refs("refs/tags")) | ||
| &self.refs().tags | ||
| } | ||
| /// The commit a reference names, in this order: | ||
| @@ -113,6 +157,11 @@ impl Reader { | ||
| } 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()) | ||
| @@ -257,17 +306,11 @@ impl Reader { | ||
| .unwrap_or(0) | ||
| } | ||
| /// Tag names grouped by the commit they point at, for labelling history. | ||
| /// Tag names grouped by the commit (or other object) they point at, for labelling history. | ||
| pub(super) fn tags_by_commit(&self) -> HashMap<String, Vec<Vec<u8>>> { | ||
| let mut found: HashMap<String, Vec<Vec<u8>>> = HashMap::new(); | ||
| let out = | ||
| self.git_bytes(&["for-each-ref", "--format=%(objectname) %(*objectname) %(refname:lstrip=2)", "refs/tags"]); | ||
| for line in out.unwrap_or_default().split(|b| *b == b'\n') { | ||
| let mut fields = line.splitn(3, |b| *b == b' '); | ||
| if let (Some(direct), Some(peeled), Some(name)) = (fields.next(), fields.next(), fields.next()) { | ||
| let commit = if peeled.is_empty() { direct } else { peeled }; | ||
| found.entry(lossy(commit).into_owned()).or_default().push(name.to_vec()); | ||
| } | ||
| for (name, target) in &self.refs().tag_targets { | ||
| found.entry(target.clone()).or_default().push(name.clone()); | ||
| } | ||
| found | ||
| } | ||
| @@ -466,6 +509,23 @@ mod tests { | ||
| 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(); | ||