1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
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};
pub(crate) const PAGE_OUTPUT_LIMIT: usize = 8 << 20;
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<Refs>,
}
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<Head> {
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(),
})
}
}
#[derive(Default)]
struct Refs {
heads: Vec<Vec<u8>>,
tags: Vec<Vec<u8>>,
commits: HashMap<Vec<u8>, String>,
tag_targets: Vec<(Vec<u8>, String)>,
}
impl Refs {
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, refs: OnceCell::new() }
}
pub(super) fn git_bytes<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<Vec<u8>> {
match git_capped(&self.dir, args, PAGE_OUTPUT_LIMIT) {
Ok((output, false)) => Some(output),
_ => None,
}
}
pub(super) fn git<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<String> {
self.git_bytes(args).map(|out| String::from_utf8_lossy(&out).into_owned())
}
pub(super) fn default_ref(&self) -> Vec<u8> {
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))
}
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.refs().heads
}
pub(super) fn tags(&self) -> &[Vec<u8>] {
&self.refs().tags
}
pub(super) fn resolve(&self, reference: &[u8]) -> Option<String> {
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;
};
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())
}
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 = 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()?;
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,
}
}
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<u8> {
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<u8> {
if Self::plain_is_safe(name) && !self.heads().iter().any(|h| h == name) {
name.to_vec()
} else {
[b"refs/tags/".as_slice(), name].concat()
}
}
pub(super) fn latest(&self, rev: &str, path: &[u8]) -> Option<Head> {
Head::parse(&self.latest_raw(rev, path)?)
}
pub(super) fn latest_raw(&self, rev: &str, path: &[u8]) -> Option<String> {
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()
}
}
pub(super) fn entry_histories(&self, commit: &str, dir: &[u8], names: &[&[u8]]) -> Vec<Option<Arc<str>>> {
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<HashMap<&'a [u8], Arc<str>>> {
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,
"--",
];
let (bytes, _) = gitv_core::git_capped_for(&self.dir, &args, RECENT_BYTES, Duration::from_secs(1)).ok()?;
Some(recent_changes(&bytes, dir, names))
}
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)
}
pub(super) fn tags_by_commit(&self) -> HashMap<String, Vec<Vec<u8>>> {
let mut found: HashMap<String, Vec<Vec<u8>>> = HashMap::new();
for (name, target) in &self.refs().tag_targets {
found.entry(target.clone()).or_default().push(name.clone());
}
found
}
}
const RECENT_WINDOW: usize = 1000;
const RECENT_BYTES: usize = 4 << 20;
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];
*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::<str>::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");
}
}
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)
}
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 <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";
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();
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");
let (prefix, _) = by_prefix.iter().find(|(_, g)| commits(g) >= 2).expect("two commits share a prefix");
assert_eq!(reader.commit_object(prefix), None);
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));
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() {
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 (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");
}
}