GITv

Find folder entries' latest changes in one longer history walk

Browse files

A cold folder listing walked only the newest 16 commits, then ran a separate git log for every entry it hadn't seen, so an older repository could start dozens of history walks per page. The walk now covers up to 1,000 linear commits (still stopping at the first merge, where per-path history can differ), and output cut off at its 4 MiB cap still answers for everything before the cut instead of being thrown away. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Author
Um9i vulgarmessiah@gmail.com
Date
22 Nov 2026, 16:15
Commit
511be5f5fc9a
Parent
48807f7

1 file changed +98−35

@@ -228,9 +228,10 @@ impl Reader {
names: &[&'a [u8]],
) -> Option<HashMap<&'a [u8], Arc<str>>> {
let format = format!("--format=%x00%P%x00{ENTRY_FORMAT}");
let window = format!("-{RECENT_WINDOW}");
let args = [
"log",
"-16",
&window,
"--first-parent",
"--diff-merges=off",
"--root",
@@ -242,11 +243,10 @@ impl Reader {
commit,
"--",
];
let (bytes, truncated) = gitv::git_capped_for(&self.dir, &args, 1 << 20, Duration::from_millis(500)).ok()?;
if truncated {
return None;
}
recent_changes(&bytes, dir, names)
// 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::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.
@@ -273,9 +273,20 @@ impl Reader {
}
}
/// 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.
fn recent_changes<'a>(mut data: &[u8], dir: &[u8], names: &[&'a [u8]]) -> Option<HashMap<&'a [u8], Arc<str>>> {
///
/// 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<str>> {
fn field<'b>(data: &mut &'b [u8]) -> Option<&'b [u8]> {
let end = data.iter().position(|&b| b == 0)?;
let value = &data[..end];
@@ -285,36 +296,40 @@ fn recent_changes<'a>(mut data: &[u8], dir: &[u8], names: &[&'a [u8]]) -> Option
let mut pending: std::collections::HashSet<_> = names.iter().copied().collect();
let mut found = HashMap::new();
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::<str>::from(lossy(metadata)));
found.insert(name, Arc::clone(value));
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::<str>::from(lossy(metadata)));
found.insert(name, Arc::clone(value));
}
}
}
}
}
Some(found)
Some(())
};
let _ = walk();
found
}
#[cfg(test)]
@@ -324,7 +339,7 @@ mod tests {
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).unwrap();
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");
@@ -403,6 +418,54 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn one_walk_finds_entries_changed_long_ago() {
use std::io::Write as _;
let dir = std::env::temp_dir().join(format!("gitv-web-walk-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
assert!(gitv::git_base().args(["init", "-q", "--bare"]).arg(&dir).status().unwrap().success());
// 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 <a@example.com> 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 <a@example.com> {} +0000\ndata {}\n{message}M 644 inline busy.txt\ndata {}\n{content}\n",
1_700_000_000 + i,
message.len(),
content.len()
);
}
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());
let reader = Reader::new(RepoDir::at(&dir).unwrap());
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 control_characters_in_git_names_do_not_shift_fields() {
let head = Head::parse("commit\0First\x1fLast\0timestamp\0date\0subject\x1fmore").unwrap();