steid

@jamesgill /

steid/src/infrastructure/git_query.rs
Rust119.1 KBCode·Blame·History·Raw
1//! Reading repository contents through the `git` binary.
2//!
3//! One process per question, per the Milestone 5 amendment to
4//! [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md): ~11–12ms of
5//! that is `execve`, and the upgrade to a kept-alive `cat-file --batch` is an adapter
6//! change behind this unchanged port.
7//!
8//! # Telling "not there" from "broken"
9//!
10//! git reports both with a non-zero exit, and at different call sites with *different*
11//! non-zero exits: `rev-parse --verify --quiet` says 1 for an unknown ref but 128 for a
12//! missing repository, while `ls-tree` pointed at a blob says 128 for what is, to a
13//! visitor, a 404. Keying off exit codes therefore either turns a typo'd URL into a 500
14//! or buries a corrupt repository behind a "not found".
15//!
16//! So every existence question here goes through one command that does not use its exit
17//! status to answer: `git cat-file --batch-check` writes `<spec> missing` on stdout and
18//! **exits 0** for anything it cannot resolve — an unknown ref, an absent path, a path
19//! traversing through a blob, a submodule's commit that lives in another repository.
20//! That gives a single rule for this whole module:
21//!
22//! **A non-zero exit from git is always an error.** "Not found" is a value read off
23//! stdout, never an exit code. Everything else — git missing from `PATH`, a repository
24//! directory that is gone, an unreadable object store — surfaces as [`GitQueryError`]
25//! carrying git's own words.
26//!
27//! The listing and content commands are only ever reached *after* `--batch-check` has
28//! confirmed the object and its type, and are handed the resolved object id rather than
29//! the user's revision, so their failure modes are genuinely faults.
30//!
31//! **Two commands are exempt**, and only those two: `git grep` and `git merge-base`,
32//! whose exit 1 git's own manual promises as "matched nothing" and "no common ancestor".
33//! Both go through [`run_allowing`], which is the only place a non-zero exit is ever
34//! accepted, and each names the status it accepts at the call site.
35
36use std::{
37 ffi::OsStr,
38 path::{Path, PathBuf},
39 process::{Output, Stdio},
40 time::{Duration, SystemTime, UNIX_EPOCH},
41};
42
43use tokio::io::{AsyncReadExt, AsyncWriteExt};
44
45use crate::{
46 application::{
47 blame::{Blame, parse_blame},
48 port::{Blob, GitQuery, GitQueryError, RawDiff},
49 search::parse_grep_output,
50 },
51 domain::{
52 BranchRow, CommitDetail, CommitSummary, EntryKind, GitRef, GrepHit, ObjectId, OrgName,
53 RefKind, RefName, RepoName, RepoPath, TagRow, TagSummary, TreeEntry,
54 },
55 infrastructure::git::git_command,
56};
57
58/// The words `cat-file --batch-check` ends a line with when it did not resolve a spec.
59///
60/// `missing` covers the common cases; `ambiguous` is an abbreviated id matching more
61/// than one object, and `dangling` and `notdir` appear when following a `^{}` or a path
62/// through something that cannot hold one. None of them is a failure — they are the
63/// answer "no such thing here".
64const NOT_FOUND_MARKERS: [&str; 4] = ["missing", "ambiguous", "dangling", "notdir"];
65
66/// Repository contents, read from bare repositories under a data directory.
67#[derive(Debug, Clone)]
68pub struct DiskGitQuery {
69 data_dir: PathBuf,
70}
71
72impl DiskGitQuery {
73 pub fn new(data_dir: impl Into<PathBuf>) -> Self {
74 Self {
75 data_dir: data_dir.into(),
76 }
77 }
78
79 /// Where a repository lives, matching `DiskGitStorage`'s layout.
80 pub(crate) fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf {
81 self.data_dir
82 .join(handle.as_str())
83 .join(format!("{name}.git"))
84 }
85}
86
87impl GitQuery for DiskGitQuery {
88 async fn default_branch(
89 &self,
90 handle: &OrgName,
91 name: &RepoName,
92 ) -> Result<Option<RefName>, GitQueryError> {
93 let repo = self.repo_path(handle, name);
94
95 // An empty repository's HEAD names a branch that does not exist yet, so
96 // `symbolic-ref` happily answers `main` for a repository with nothing in it.
97 // Whether HEAD *resolves* is the actual question, and it is asked first.
98 let Some(head) = object_info(&repo, "HEAD").await? else {
99 return Ok(None);
100 };
101
102 let branch = run(&repo, [OsStr::new("symbolic-ref"), OsStr::new("HEAD")]).await;
103
104 match branch {
105 Ok(output) => {
106 let full = String::from_utf8_lossy(&output.stdout).trim().to_owned();
107 // `refs/heads/main` rather than `--short`, because `--short` shortens
108 // only as far as is unambiguous and would hand back `heads/main` for a
109 // repository that also has a tag called `main`.
110 let short = full.strip_prefix("refs/heads/").unwrap_or(&full);
111
112 Ok(Some(RefName::from_trusted(short)))
113 }
114 // A detached HEAD is not a state Steid creates, but a repository pushed into
115 // from elsewhere can be in it. The commit is still browsable, so name it
116 // rather than claiming the repository is empty — which is what `Ok(None)`
117 // would mean to a page.
118 Err(_) => Ok(Some(RefName::from_trusted(head.id.as_str()))),
119 }
120 }
121
122 async fn resolve(
123 &self,
124 handle: &OrgName,
125 name: &RepoName,
126 rev: &RefName,
127 ) -> Result<Option<ObjectId>, GitQueryError> {
128 let repo = self.repo_path(handle, name);
129
130 // `^{commit}` peels an annotated tag to what it points at, and refuses a
131 // revision that names a tree or a blob — a browse page wants a commit, and
132 // returning a tree id here would fail confusingly two calls later.
133 let spec = format!("{}^{{commit}}", rev.as_str());
134
135 Ok(object_info(&repo, &spec).await?.map(|info| info.id))
136 }
137
138 async fn list_tree(
139 &self,
140 handle: &OrgName,
141 name: &RepoName,
142 rev: &RefName,
143 path: &RepoPath,
144 ) -> Result<Option<Vec<TreeEntry>>, GitQueryError> {
145 let repo = self.repo_path(handle, name);
146
147 let Some(info) = object_info(&repo, &tree_spec(rev, path)).await? else {
148 return Ok(None);
149 };
150
151 // A file is not a directory. Asking `ls-tree` anyway is a fatal error, which is
152 // exactly the confusion this check exists to avoid.
153 if info.kind != ObjectKind::Tree {
154 return Ok(None);
155 }
156
157 // `-z` because a filename may contain a newline, and `--long` for blob sizes.
158 // The already-resolved tree id is passed rather than the user's revision, so
159 // nothing here has to think about what git's revision parser might make of it.
160 let output = run(
161 &repo,
162 [
163 OsStr::new("ls-tree"),
164 OsStr::new("-z"),
165 OsStr::new("--long"),
166 OsStr::new(info.id.as_str()),
167 ],
168 )
169 .await?;
170
171 parse_tree(&output.stdout).map(Some)
172 }
173
174 async fn read_blob(
175 &self,
176 handle: &OrgName,
177 name: &RepoName,
178 rev: &RefName,
179 path: &RepoPath,
180 max_bytes: u64,
181 ) -> Result<Option<Blob>, GitQueryError> {
182 let repo = self.repo_path(handle, name);
183
184 // The root is a tree, and `{rev}:` is how git spells it — but a caller asking to
185 // read the root is asking for a file that is not there.
186 if path.is_root() {
187 return Ok(None);
188 }
189
190 let Some(info) = object_info(&repo, &tree_spec(rev, path)).await? else {
191 return Ok(None);
192 };
193
194 // Symlinks are blobs whose content is the target path, and are read as such:
195 // showing where a link points is more use than a blank page. Trees and
196 // submodules are not files.
197 if info.kind != ObjectKind::Blob {
198 return Ok(None);
199 }
200
201 // The size comes from the object header, so an oversized file is never read.
202 // Doing this the other way round — read, then measure — is how one URL becomes
203 // an out-of-memory kill.
204 let content = if info.size > max_bytes {
205 None
206 } else {
207 let output = run(
208 &repo,
209 [
210 OsStr::new("cat-file"),
211 OsStr::new("blob"),
212 OsStr::new(info.id.as_str()),
213 ],
214 )
215 .await?;
216
217 Some(output.stdout)
218 };
219
220 Ok(Some(Blob {
221 id: info.id,
222 size: info.size,
223 content,
224 }))
225 }
226
227 async fn log(
228 &self,
229 handle: &OrgName,
230 name: &RepoName,
231 rev: &RefName,
232 limit: usize,
233 ) -> Result<Vec<CommitSummary>, GitQueryError> {
234 let repo = self.repo_path(handle, name);
235
236 // `git log` on a repository with no commits is a fatal error, and so is a log of
237 // a branch that does not exist. Resolving first turns both into the empty list
238 // the port's signature promises, without having to read meaning into a stderr
239 // string that is localised and free to change between git versions.
240 let Some(commit) = self.resolve(handle, name, rev).await? else {
241 return Ok(Vec::new());
242 };
243
244 if limit == 0 {
245 return Ok(Vec::new());
246 }
247
248 // Every separator is a NUL: `-z` between commits, `%x00` between fields. A
249 // commit message contains newlines as a matter of course, and a name can contain
250 // almost anything, so splitting on lines or whitespace would misread real
251 // history rather than exotic history.
252 let count = format!("--max-count={limit}");
253
254 let output = run(
255 &repo,
256 [
257 OsStr::new("log"),
258 OsStr::new("-z"),
259 OsStr::new(&count),
260 OsStr::new(LOG_FORMAT),
261 OsStr::new(commit.as_str()),
262 ],
263 )
264 .await?;
265
266 parse_log(&output.stdout)
267 }
268
269 async fn list_refs(
270 &self,
271 handle: &OrgName,
272 name: &RepoName,
273 ) -> Result<Vec<GitRef>, GitQueryError> {
274 let repo = self.repo_path(handle, name);
275
276 // One fork, ~14ms — see the port's note. `for-each-ref` is asked for both
277 // namespaces at once rather than once each, because the cost here is the
278 // process, not the question.
279 //
280 // Every field separator is a NUL, for the same reason `log` uses one: a tag name
281 // is close to arbitrary text once git's own restrictions are met, and splitting
282 // on whitespace would misread a real name. The patterns are literals, so unlike
283 // a revision from a URL there is nothing here that could be read as a flag.
284 let output = run(
285 &repo,
286 [
287 OsStr::new("for-each-ref"),
288 OsStr::new(REF_FORMAT),
289 OsStr::new("refs/heads/"),
290 OsStr::new("refs/tags/"),
291 ],
292 )
293 .await?;
294
295 Ok(parse_refs(&output.stdout))
296 }
297
298 async fn count_commits(
299 &self,
300 handle: &OrgName,
301 name: &RepoName,
302 rev: &RefName,
303 ) -> Result<u64, GitQueryError> {
304 let repo = self.repo_path(handle, name);
305
306 // Resolved first, for the same reason `log` resolves first: `rev-list` on an
307 // empty repository or an unknown branch is a fatal error, and the port promises
308 // a count rather than a failure. **That makes this two processes, not one** —
309 // the price of keeping the module's rule that a non-zero exit is always a real
310 // fault. Handing the resolved id to `rev-list` also means nothing from a URL
311 // reaches git's revision parser here.
312 let Some(commit) = self.resolve(handle, name, rev).await? else {
313 return Ok(0);
314 };
315
316 let output = run(
317 &repo,
318 [
319 OsStr::new("rev-list"),
320 OsStr::new("--count"),
321 OsStr::new(commit.as_str()),
322 ],
323 )
324 .await?;
325
326 let count = String::from_utf8_lossy(&output.stdout);
327 let count = count.trim();
328
329 count.parse().map_err(|_| {
330 GitQueryError::new(format!(
331 "git counted commits as {count:?}, which is not a number"
332 ))
333 })
334 }
335
336 async fn latest_tag(
337 &self,
338 handle: &OrgName,
339 name: &RepoName,
340 ) -> Result<Option<TagSummary>, GitQueryError> {
341 let repo = self.repo_path(handle, name);
342
343 // `--count=1` after `--sort` is the whole of the work: git does the ordering,
344 // so this is one process regardless of how many tags a repository carries.
345 // Every argument is a literal — nothing from a URL reaches this call.
346 let output = run(
347 &repo,
348 [
349 OsStr::new("for-each-ref"),
350 OsStr::new("--sort=-creatordate"),
351 OsStr::new("--count=1"),
352 OsStr::new(TAG_FORMAT),
353 OsStr::new("refs/tags/"),
354 ],
355 )
356 .await?;
357
358 Ok(parse_latest_tag(&output.stdout))
359 }
360
361 async fn branches(
362 &self,
363 handle: &OrgName,
364 name: &RepoName,
365 ) -> Result<Vec<BranchRow>, GitQueryError> {
366 let repo = self.repo_path(handle, name);
367
368 // One process for the whole branches page. The sort is git's because it is
369 // free there and would otherwise be a second pass in Rust over the same rows,
370 // and `%(HEAD)` is what saves the page a `symbolic-ref` for the default branch.
371 // Every argument is a literal — nothing from a URL reaches this call.
372 let output = run(
373 &repo,
374 [
375 OsStr::new("for-each-ref"),
376 OsStr::new("--sort=-committerdate"),
377 OsStr::new(BRANCH_FORMAT),
378 OsStr::new("refs/heads/"),
379 ],
380 )
381 .await?;
382
383 parse_branches(&output.stdout)
384 }
385
386 async fn tags(&self, handle: &OrgName, name: &RepoName) -> Result<Vec<TagRow>, GitQueryError> {
387 let repo = self.repo_path(handle, name);
388
389 let output = run(
390 &repo,
391 [
392 OsStr::new("for-each-ref"),
393 OsStr::new("--sort=-creatordate"),
394 OsStr::new(TAG_ROW_FORMAT),
395 OsStr::new("refs/tags/"),
396 ],
397 )
398 .await?;
399
400 parse_tags(&output.stdout)
401 }
402
403 async fn grep(
404 &self,
405 handle: &OrgName,
406 name: &RepoName,
407 commit: &ObjectId,
408 query: &str,
409 limit: usize,
410 ) -> Result<Vec<GrepHit>, GitQueryError> {
411 let repo = self.repo_path(handle, name);
412
413 // **One of the two commands here whose exit status is an answer** — the other
414 // is `merge_base`. `git grep` exits 1 when it found nothing, which is not a
415 // failure. Everything else in this module keeps the rule that a non-zero exit
416 // is a fault; the exception is spelled out in the call rather than hidden in
417 // the helper.
418 //
419 // `-F` fixed strings, `-I` skips binary files, `-n --column` locate the match,
420 // and `-z` makes the output parseable — see `parse_grep_output`. The query is
421 // passed after `-e`, so a query starting with `-` is a search rather than a
422 // flag, and the commit is one git resolved rather than anything from a URL.
423 let output = run_allowing(
424 &repo,
425 [
426 OsStr::new("grep"),
427 OsStr::new("-I"),
428 OsStr::new("-n"),
429 OsStr::new("-z"),
430 OsStr::new("-F"),
431 OsStr::new("--column"),
432 OsStr::new("--no-color"),
433 OsStr::new("-e"),
434 OsStr::new(query),
435 OsStr::new(commit.as_str()),
436 OsStr::new("--"),
437 ],
438 &[NO_MATCHES],
439 )
440 .await?;
441
442 Ok(parse_grep_output(&output.stdout, commit, limit))
443 }
444
445 async fn commit(
446 &self,
447 handle: &OrgName,
448 name: &RepoName,
449 rev: &RefName,
450 ) -> Result<Option<CommitDetail>, GitQueryError> {
451 let repo = self.repo_path(handle, name);
452
453 // Resolved first, as everywhere else in this module: `git log` is fatal on a
454 // revision that names nothing, and `resolve` already peels an annotated tag and
455 // refuses a tree or a blob — so what reaches `log` is an object id known to be
456 // a commit, and a non-zero exit below really is a fault.
457 let Some(id) = self.resolve(handle, name, rev).await? else {
458 return Ok(None);
459 };
460
461 let output = run(
462 &repo,
463 [
464 OsStr::new("log"),
465 OsStr::new("--max-count=1"),
466 OsStr::new(COMMIT_FORMAT),
467 OsStr::new(id.as_str()),
468 ],
469 )
470 .await?;
471
472 parse_commit(&output.stdout).map(Some)
473 }
474
475 async fn diff(
476 &self,
477 handle: &OrgName,
478 name: &RepoName,
479 base: Option<&ObjectId>,
480 head: &ObjectId,
481 max_bytes: u64,
482 ) -> Result<RawDiff, GitQueryError> {
483 let repo = self.repo_path(handle, name);
484
485 // `diff-tree` rather than `diff`, for both shapes: it is the plumbing command,
486 // it takes tree-ish arguments rather than revision expressions, and it does not
487 // consult a working tree that a bare repository does not have.
488 //
489 // The flags, each load-bearing:
490 // --no-commit-id `-p` would otherwise print the commit's id as a first line
491 // -p the patch itself
492 // -M rename detection, so a moved file is one entry, not two
493 // --numstat the per-file counts, written *before* the patch — which is
494 // what makes them survive the byte cap below
495 // --no-color the caller renders; git must not send escape sequences
496 // --root a first commit is diffed against nothing rather than
497 // skipped, which is the only way to see what it introduced
498 let mut args: Vec<&OsStr> = vec![
499 OsStr::new("diff-tree"),
500 OsStr::new("--no-commit-id"),
501 OsStr::new("-p"),
502 OsStr::new("-M"),
503 OsStr::new("--numstat"),
504 OsStr::new("--no-color"),
505 ];
506
507 match base {
508 Some(base) => {
509 args.push(OsStr::new(base.as_str()));
510 }
511 None => args.push(OsStr::new("--root")),
512 }
513
514 args.push(OsStr::new(head.as_str()));
515
516 let (stdout, truncated) = run_capped(&repo, args, max_bytes).await?;
517 let (numstat, patch) = split_numstat(&stdout);
518
519 Ok(RawDiff {
520 numstat: numstat.to_vec(),
521 patch: patch.to_vec(),
522 truncated,
523 })
524 }
525
526 async fn merge_base(
527 &self,
528 handle: &OrgName,
529 name: &RepoName,
530 base: &ObjectId,
531 head: &ObjectId,
532 ) -> Result<Option<ObjectId>, GitQueryError> {
533 let repo = self.repo_path(handle, name);
534
535 // **The other exception to this module's rule that a non-zero exit is a
536 // fault**, `grep` being the first. `git merge-base` documents exit 1 as "no
537 // merge base found" and reserves 128 for real errors, so the two are
538 // distinguishable here in a way they are not for `rev-parse` — which is why the
539 // rule exists at all. Two histories with no common ancestor is a thing a compare
540 // page must be able to say, and the arguments are resolved object ids, so there
541 // is nothing else exit 1 can mean.
542 let output = run_allowing(
543 &repo,
544 [
545 OsStr::new("merge-base"),
546 OsStr::new(base.as_str()),
547 OsStr::new(head.as_str()),
548 ],
549 &[NO_COMMON_ANCESTOR],
550 )
551 .await?;
552
553 let id = String::from_utf8_lossy(&output.stdout);
554 let id = id.trim();
555
556 if id.is_empty() {
557 return Ok(None);
558 }
559
560 Ok(Some(ObjectId::new(id).map_err(|error| {
561 GitQueryError::new(format!("git named a bad merge base: {error}"))
562 })?))
563 }
564
565 async fn log_between(
566 &self,
567 handle: &OrgName,
568 name: &RepoName,
569 base: Option<&ObjectId>,
570 head: &ObjectId,
571 limit: usize,
572 ) -> Result<Vec<CommitSummary>, GitQueryError> {
573 let repo = self.repo_path(handle, name);
574
575 if limit == 0 {
576 return Ok(Vec::new());
577 }
578
579 // Both ends are already object ids, so the range is built here rather than
580 // taken from a URL — `..` is the one piece of revision syntax this module
581 // writes itself, and `RefName` refuses it precisely so that nothing else can.
582 let range = match base {
583 Some(base) => format!("{}..{}", base.as_str(), head.as_str()),
584 None => head.as_str().to_owned(),
585 };
586 let count = format!("--max-count={limit}");
587
588 let output = run(
589 &repo,
590 [
591 OsStr::new("log"),
592 OsStr::new("-z"),
593 OsStr::new(&count),
594 OsStr::new(LOG_FORMAT),
595 OsStr::new(&range),
596 ],
597 )
598 .await?;
599
600 parse_log(&output.stdout)
601 }
602
603 async fn blame(
604 &self,
605 handle: &OrgName,
606 name: &RepoName,
607 rev: &RefName,
608 path: &RepoPath,
609 ) -> Result<Option<Blame>, GitQueryError> {
610 let repo = self.repo_path(handle, name);
611
612 // `git blame` is fatal on an unknown revision *and* on a path that is not in it,
613 // so one `--batch-check` on `{rev}:{path}` settles both before the expensive
614 // command runs — the module's rule that a non-zero exit is a real fault only
615 // holds because of checks like this one.
616 let Some(info) = object_info(&repo, &tree_spec(rev, path)).await? else {
617 return Ok(None);
618 };
619
620 // A directory has no lines. Blaming one is another fatal error.
621 if info.kind != ObjectKind::Blob {
622 return Ok(None);
623 }
624
625 // The revision is named rather than the blob id: blame walks *history*, and a
626 // blob knows nothing about which commits reached it. `--` separates the revision
627 // from the path so neither can be read as the other, and `RefName` and
628 // `RepoPath` have already refused a leading hyphen.
629 let output = run(
630 &repo,
631 [
632 OsStr::new("blame"),
633 OsStr::new("--porcelain"),
634 OsStr::new(rev.as_str()),
635 OsStr::new("--"),
636 OsStr::new(path.as_str()),
637 ],
638 )
639 .await?;
640
641 Ok(Some(parse_blame(&output.stdout)))
642 }
643
644 async fn ref_snapshot(
645 &self,
646 handle: &OrgName,
647 name: &RepoName,
648 ) -> Result<Vec<(RefName, ObjectId)>, GitQueryError> {
649 let repo = self.repo_path(handle, name);
650
651 // The whole of `refs/` in one process. Unlike `list_refs`, which asks for the
652 // two namespaces a switcher shows, this is diffed around a push and a ref that
653 // was not asked about is a ref whose change goes unrecorded. The pattern is a
654 // literal; nothing from a URL reaches this call.
655 let output = run(
656 &repo,
657 [
658 OsStr::new("for-each-ref"),
659 OsStr::new(SNAPSHOT_FORMAT),
660 OsStr::new("refs/"),
661 ],
662 )
663 .await?;
664
665 Ok(parse_ref_snapshot(&output.stdout))
666 }
667}
668
669/// What `cat-file --batch-check` said about one object.
670#[derive(Debug, Clone, PartialEq, Eq)]
671struct ObjectInfo {
672 id: ObjectId,
673 kind: ObjectKind,
674 size: u64,
675}
676
677/// A git object's type, as its header spells it.
678///
679/// Distinct from [`EntryKind`], which is about what a tree entry *means* — the object
680/// store cannot tell a symlink from a file, because both are blobs.
681#[derive(Debug, Clone, Copy, PartialEq, Eq)]
682enum ObjectKind {
683 Blob,
684 Tree,
685 Commit,
686 Tag,
687}
688
689impl ObjectKind {
690 fn from_str(value: &str) -> Option<Self> {
691 match value {
692 "blob" => Some(Self::Blob),
693 "tree" => Some(Self::Tree),
694 "commit" => Some(Self::Commit),
695 "tag" => Some(Self::Tag),
696 _ => None,
697 }
698 }
699}
700
701/// How git addresses a path inside a revision: `{rev}:{path}`, and `{rev}:` for the root.
702fn tree_spec(rev: &RefName, path: &RepoPath) -> String {
703 format!("{}:{}", rev.as_str(), path.as_str())
704}
705
706/// Asks git what one revision-and-path resolves to, or `None` if it resolves to nothing.
707///
708/// The spec goes over stdin rather than in an argument, so no revision or path can ever
709/// be read as a flag regardless of what validation upstream does or stops doing.
710async fn object_info(repo: &Path, spec: &str) -> Result<Option<ObjectInfo>, GitQueryError> {
711 let mut command = git_command();
712 command
713 .arg("-C")
714 .arg(repo)
715 .arg("cat-file")
716 .arg("--batch-check")
717 .stdin(Stdio::piped())
718 .stdout(Stdio::piped())
719 .stderr(Stdio::piped());
720
721 let mut child = command
722 .spawn()
723 .map_err(|error| GitQueryError::new(format!("could not run git: {error}")))?;
724
725 let mut stdin = child.stdin.take().expect("stdin was piped");
726
727 // One short line, far below a pipe's buffer, so writing before waiting cannot
728 // deadlock. Dropping stdin is what ends the batch — git would otherwise wait for
729 // another spec forever.
730 stdin
731 .write_all(format!("{spec}\n").as_bytes())
732 .await
733 .map_err(|error| {
734 GitQueryError::new(format!("could not ask git about {spec:?}: {error}"))
735 })?;
736 drop(stdin);
737
738 let output = child
739 .wait_with_output()
740 .await
741 .map_err(|error| GitQueryError::new(format!("could not wait for git: {error}")))?;
742
743 // Per the module note: a non-zero exit here is never "not found".
744 if !output.status.success() {
745 return Err(GitQueryError::new(format!(
746 "git exited with {} looking up {spec:?}: {}",
747 output.status,
748 String::from_utf8_lossy(&output.stderr).trim()
749 )));
750 }
751
752 let line = String::from_utf8_lossy(&output.stdout);
753 let line = line.trim_end_matches('\n');
754
755 // The marker is checked before the field count, because a not-found line echoes the
756 // spec back — and a spec naming a file with spaces in it has no fixed field count.
757 if line
758 .rsplit(' ')
759 .next()
760 .is_some_and(|last| NOT_FOUND_MARKERS.contains(&last))
761 {
762 return Ok(None);
763 }
764
765 let fields: Vec<&str> = line.split_whitespace().collect();
766 let [id, kind, size] = fields[..] else {
767 return Err(GitQueryError::new(format!(
768 "git described {spec:?} in a shape we do not understand: {line:?}"
769 )));
770 };
771
772 Ok(Some(ObjectInfo {
773 // Validated rather than trusted. git's ids are trustworthy, but this is a parse
774 // of text whose layout we have assumed, and an id is about to appear in a URL —
775 // a misread field should stop here rather than surface as a broken link. The
776 // cost is a length and hex check next to a process spawn.
777 id: ObjectId::new(id)
778 .map_err(|error| GitQueryError::new(format!("git named a bad object id: {error}")))?,
779 kind: ObjectKind::from_str(kind).ok_or_else(|| {
780 GitQueryError::new(format!("git reported an unknown object type {kind:?}"))
781 })?,
782 size: size.parse().map_err(|_| {
783 GitQueryError::new(format!("git reported an unreadable object size {size:?}"))
784 })?,
785 }))
786}
787
788/// Parses `ls-tree -z --long` output.
789///
790/// Each record is `<mode> SP <type> SP <id> SP <size> TAB <name>`, NUL-terminated, where
791/// the size is space-padded and `-` for anything that is not a blob. The name is
792/// everything after the first tab and is *raw bytes* — which is why the split happens
793/// before any attempt to read it as text.
794fn parse_tree(stdout: &[u8]) -> Result<Vec<TreeEntry>, GitQueryError> {
795 let mut entries = Vec::new();
796
797 for record in stdout.split(|byte| *byte == 0) {
798 if record.is_empty() {
799 continue;
800 }
801
802 let Some(tab) = record.iter().position(|byte| *byte == b'\t') else {
803 return Err(GitQueryError::new(
804 "git listed a tree entry with no name separator",
805 ));
806 };
807
808 let (meta, name) = record.split_at(tab);
809 let name = &name[1..];
810
811 let meta = std::str::from_utf8(meta).map_err(|_| {
812 GitQueryError::new("git listed a tree entry whose metadata is not text")
813 })?;
814
815 let fields: Vec<&str> = meta.split_whitespace().collect();
816 let [mode, _type, id, size] = fields[..] else {
817 return Err(GitQueryError::new(format!(
818 "git listed a tree entry in a shape we do not understand: {meta:?}"
819 )));
820 };
821
822 entries.push(TreeEntry {
823 // Lossy, because `TreeEntry::name` is a `String` and a filename is not
824 // required to be UTF-8. A replacement character renders; refusing to list
825 // the whole directory because one file has an odd name does not.
826 name: String::from_utf8_lossy(name).into_owned(),
827 kind: EntryKind::from_mode(mode)
828 .map_err(|error| GitQueryError::new(format!("git listed {name:?}: {error}")))?,
829 id: ObjectId::new(id).map_err(|error| {
830 GitQueryError::new(format!("git named a bad object id: {error}"))
831 })?,
832 // `-` for a tree or a submodule, which have no size a listing can show.
833 size: size.parse().ok(),
834 });
835 }
836
837 // Unsorted on purpose: ordering is `TreeEntry::ordering_key`'s decision, made once
838 // in the application rather than differently in each adapter.
839 Ok(entries)
840}
841
842/// Parses the NUL-separated `log` stream into four-field records.
843fn parse_log(stdout: &[u8]) -> Result<Vec<CommitSummary>, GitQueryError> {
844 // `-z` terminates the last record too, so the split leaves a trailing empty field
845 // that is not a commit.
846 let fields: Vec<&[u8]> = stdout
847 .split(|byte| *byte == 0)
848 .filter(|field| !field.is_empty())
849 .collect();
850
851 let mut commits = Vec::with_capacity(fields.len() / 4);
852
853 for record in fields.chunks(4) {
854 let [id, committed_at, author_name, summary] = record[..] else {
855 return Err(GitQueryError::new(
856 "git logged a commit with missing fields",
857 ));
858 };
859
860 let id = String::from_utf8_lossy(id);
861 let committed_at = String::from_utf8_lossy(committed_at);
862 let committed_at: i64 = committed_at.trim().parse().map_err(|_| {
863 GitQueryError::new(format!(
864 "git logged an unreadable commit time {committed_at:?}"
865 ))
866 })?;
867
868 commits.push(CommitSummary {
869 id: ObjectId::new(id.trim()).map_err(|error| {
870 GitQueryError::new(format!("git named a bad object id: {error}"))
871 })?,
872 // `%s` is git's subject: the first paragraph, joined into one line. Trimmed
873 // to the first line anyway, because that invariant is git's rather than
874 // something this parser should assume.
875 summary: String::from_utf8_lossy(summary)
876 .lines()
877 .next()
878 .unwrap_or_default()
879 .to_owned(),
880 author_name: String::from_utf8_lossy(author_name).into_owned(),
881 committed_at: unix_time(committed_at),
882 });
883 }
884
885 Ok(commits)
886}
887
888/// A unix timestamp as a `SystemTime`, including the negative ones.
889///
890/// A commit dated before 1970 is either a lie or an import from something older than
891/// git, and both exist in real repositories. `UNIX_EPOCH + Duration` would panic on the
892/// subtraction it cannot do.
893fn unix_time(seconds: i64) -> SystemTime {
894 match u64::try_from(seconds) {
895 Ok(seconds) => UNIX_EPOCH + Duration::from_secs(seconds),
896 Err(_) => UNIX_EPOCH - Duration::from_secs(seconds.unsigned_abs()),
897 }
898}
899
900/// What `for-each-ref` prints per ref: the full name and the object it names,
901/// NUL-separated and NUL-terminated.
902///
903/// The kind is *not* asked for. `%(objecttype)` says `commit` for both a branch and a
904/// lightweight tag, so the namespace in the name is the only thing that answers which
905/// one a visitor asked for.
906const REF_FORMAT: &str = "--format=%(refname)%00";
907
908/// What a snapshot asks for: the full name and the object the ref itself names.
909///
910/// `%(objectname)` rather than `%(*objectname)`, so an annotated tag reports the tag
911/// object. What a push changed is the *ref*, and re-tagging the same commit with a new
912/// annotation is a change even though the peeled ids match.
913const SNAPSHOT_FORMAT: &str = "--format=%(refname)%00%(objectname)%00";
914
915/// Parses a snapshot's NUL-separated pairs.
916///
917/// Same shape as [`parse_refs`], two fields instead of one, and the same rule about a
918/// ref that Steid's own [`RefName`] refuses: left out rather than carried. A push event
919/// naming a ref no page can address is a row nothing can do anything with.
920fn parse_ref_snapshot(stdout: &[u8]) -> Vec<(RefName, ObjectId)> {
921 let fields = ref_fields(stdout);
922 let mut snapshot = Vec::with_capacity(fields.len() / 2);
923
924 for pair in fields.chunks_exact(2) {
925 // git ends each record with a newline the format cannot suppress, so it arrives
926 // at the front of the next record's first field. A ref name contains neither a
927 // newline nor a space, so trimming cannot eat part of one.
928 let Ok(full) = std::str::from_utf8(pair[0].trim_ascii()) else {
929 continue;
930 };
931 let Ok(id) = std::str::from_utf8(pair[1].trim_ascii()) else {
932 continue;
933 };
934
935 let (Ok(name), Ok(id)) = (RefName::new(full), ObjectId::new(id)) else {
936 continue;
937 };
938
939 snapshot.push((name, id));
940 }
941
942 snapshot
943}
944
945/// Parses `for-each-ref`'s NUL-separated output into branches and tags.
946///
947/// Each record is `<full refname> NUL`, and git ends every record with a newline of its
948/// own that the format cannot suppress — so the newline arrives at the *front* of the
949/// next record's first field and is trimmed off. A ref name can contain neither a
950/// newline nor a space, so trimming cannot eat part of a name.
951fn parse_refs(stdout: &[u8]) -> Vec<GitRef> {
952 let mut refs = Vec::new();
953
954 for record in stdout.split(|byte| *byte == 0) {
955 let record = record.trim_ascii();
956
957 if record.is_empty() {
958 continue;
959 }
960
961 // Lossy would be wrong here: a name that is not UTF-8 cannot be put in a URL,
962 // and offering a link that cannot work is worse than leaving the ref out of the
963 // switcher. It is still browsable by object id.
964 let Ok(full) = std::str::from_utf8(record) else {
965 continue;
966 };
967
968 let (kind, short) = if let Some(short) = full.strip_prefix("refs/heads/") {
969 (RefKind::Branch, short)
970 } else if let Some(short) = full.strip_prefix("refs/tags/") {
971 (RefKind::Tag, short)
972 } else {
973 // Only the two namespaces were asked for, so this cannot happen — and if a
974 // future pattern is added and this is forgotten, skipping is the safe half
975 // of the mistake.
976 continue;
977 };
978
979 // Validated rather than trusted: this name is about to become a URL, and
980 // `RefName` is what decides a name is safe to hand back to git. A ref git
981 // accepts but Steid's rules do not is left out rather than linked to.
982 let Ok(name) = RefName::new(short) else {
983 continue;
984 };
985
986 refs.push(GitRef { name, kind });
987 }
988
989 refs
990}
991
992/// What the latest-tag query asks for: the full ref name and its creation time.
993///
994/// `creatordate` rather than `taggerdate`, which is empty for a lightweight tag, or
995/// `committerdate`, which is empty for an annotated one. `creatordate` is git's own
996/// "whichever of those this ref has".
997const TAG_FORMAT: &str = "--format=%(refname)%00%(creatordate:unix)%00";
998
999/// Parses the one record [`TAG_FORMAT`] produces, or `None` for a repository with no
1000/// tags.
1001///
1002/// Anything unreadable is `None` rather than an error: this decorates a page with a
1003/// fact, and a tag whose name is not UTF-8 or whose date git spelled unexpectedly is a
1004/// reason to say nothing, not to fail the repository's landing page.
1005fn parse_latest_tag(stdout: &[u8]) -> Option<TagSummary> {
1006 let fields: Vec<&[u8]> = stdout
1007 .split(|byte| *byte == 0)
1008 .map(<[u8]>::trim_ascii)
1009 .filter(|field| !field.is_empty())
1010 .collect();
1011
1012 let [name, created_at] = fields[..] else {
1013 return None;
1014 };
1015
1016 let short = std::str::from_utf8(name).ok()?.strip_prefix("refs/tags/")?;
1017 let created_at: i64 = std::str::from_utf8(created_at).ok()?.parse().ok()?;
1018
1019 Some(TagSummary {
1020 // Validated rather than trusted, exactly as `parse_refs` does: the name is
1021 // about to become a link.
1022 name: RefName::new(short).ok()?,
1023 created_at: unix_time(created_at),
1024 })
1025}
1026
1027/// What the branches page asks for, per branch.
1028///
1029/// `%(HEAD)` is git's own marker for the branch `HEAD` points at — `*` for it and a
1030/// space for everything else. It is asked for here rather than resolved separately
1031/// because a second process to learn one bit is the cost 0006 is about.
1032///
1033/// `%(objectname)` is the tip commit itself: a branch, unlike a tag, never points at
1034/// anything else.
1035const BRANCH_FORMAT: &str = "--format=%(refname)%00%(HEAD)%00%(objectname)%00%(committerdate:unix)%00%(contents:subject)%00";
1036
1037/// What the tags page asks for, per tag.
1038///
1039/// `%(objecttype)` is `tag` for an annotated tag and `commit` for a lightweight one,
1040/// which is the only reliable way to tell them apart. `%(*objectname)` is the peeled
1041/// object and is empty for a lightweight tag, so the commit is "the peeled one if there
1042/// is one". `%(contents:subject)` is the *tag's* message for an annotated tag and the
1043/// *commit's* for a lightweight one — so it is read only when the type says `tag`,
1044/// otherwise a lightweight tag would appear to carry a message it does not have.
1045const TAG_ROW_FORMAT: &str = "--format=%(refname)%00%(objecttype)%00%(objectname)%00%(*objectname)%00%(creatordate:unix)%00%(contents:subject)%00";
1046
1047/// Splits `for-each-ref` output into its NUL-terminated fields.
1048///
1049/// Every field ends with a NUL and git adds a newline after each record that the format
1050/// cannot suppress, so the split yields exactly one field per `%00` plus a trailing
1051/// remainder holding that last newline — dropped here.
1052///
1053/// **Empty fields are kept.** A lightweight tag has no peeled object, and filtering
1054/// empties the way [`parse_latest_tag`] can afford to would shift every later field of
1055/// that record onto the wrong name.
1056fn ref_fields(stdout: &[u8]) -> Vec<&[u8]> {
1057 let mut fields: Vec<&[u8]> = stdout.split(|byte| *byte == 0).collect();
1058 fields.pop();
1059 fields
1060}
1061
1062/// The first line of git's subject, or `None` when there is nothing to show.
1063///
1064/// `%(contents:subject)` is already one line, but that is git's invariant rather than
1065/// something this parser should assume — the same reason [`parse_log`] trims `%s`.
1066fn subject(field: &[u8]) -> Option<String> {
1067 let line = String::from_utf8_lossy(field)
1068 .lines()
1069 .next()
1070 .unwrap_or_default()
1071 .trim()
1072 .to_owned();
1073
1074 (!line.is_empty()).then_some(line)
1075}
1076
1077/// Parses [`BRANCH_FORMAT`] into rows, in the order git sorted them.
1078///
1079/// A record whose name or commit id Steid cannot use is skipped rather than failing the
1080/// page, exactly as [`parse_refs`] skips one: a branch that cannot be linked to is a
1081/// reason to leave a row out, not to refuse the whole list. A record with the wrong
1082/// number of fields is different — that is git saying something this code does not
1083/// understand, and it is an error.
1084fn parse_branches(stdout: &[u8]) -> Result<Vec<BranchRow>, GitQueryError> {
1085 let fields = ref_fields(stdout);
1086 let mut rows = Vec::with_capacity(fields.len() / 5);
1087
1088 for record in fields.chunks(5) {
1089 let [name, head, commit, committed_at, summary] = record[..] else {
1090 return Err(GitQueryError::new(
1091 "git listed a branch with missing fields",
1092 ));
1093 };
1094
1095 // git's trailing newline arrives in front of the next record's first field.
1096 // A ref name can contain neither a newline nor a space, so trimming cannot eat
1097 // part of one.
1098 let Some(name) = short_ref(name.trim_ascii(), "refs/heads/") else {
1099 continue;
1100 };
1101
1102 let Ok(commit) = ObjectId::new(String::from_utf8_lossy(commit).trim()) else {
1103 continue;
1104 };
1105
1106 let committed_at = String::from_utf8_lossy(committed_at);
1107 let Ok(committed_at) = committed_at.trim().parse::<i64>() else {
1108 continue;
1109 };
1110
1111 rows.push(BranchRow {
1112 name,
1113 // `*` for the branch HEAD names, a space for the rest.
1114 is_default: head.trim_ascii() == b"*",
1115 commit,
1116 summary: subject(summary).unwrap_or_default(),
1117 committed_at: unix_time(committed_at),
1118 });
1119 }
1120
1121 Ok(rows)
1122}
1123
1124/// Parses [`TAG_ROW_FORMAT`] into rows, in the order git sorted them.
1125///
1126/// Skips and errors on the same terms as [`parse_branches`].
1127fn parse_tags(stdout: &[u8]) -> Result<Vec<TagRow>, GitQueryError> {
1128 let fields = ref_fields(stdout);
1129 let mut rows = Vec::with_capacity(fields.len() / 6);
1130
1131 for record in fields.chunks(6) {
1132 let [name, kind, object, peeled, created_at, message] = record[..] else {
1133 return Err(GitQueryError::new("git listed a tag with missing fields"));
1134 };
1135
1136 let Some(name) = short_ref(name.trim_ascii(), "refs/tags/") else {
1137 continue;
1138 };
1139
1140 // An annotated tag's `objectname` is the tag object, so the thing worth linking
1141 // to is the peeled one. A lightweight tag has no peel and already names its
1142 // commit.
1143 let annotated = kind.trim_ascii() == b"tag";
1144 let id = if peeled.trim_ascii().is_empty() {
1145 object
1146 } else {
1147 peeled
1148 };
1149
1150 let Ok(commit) = ObjectId::new(String::from_utf8_lossy(id).trim()) else {
1151 continue;
1152 };
1153
1154 let created_at = String::from_utf8_lossy(created_at);
1155 let Ok(created_at) = created_at.trim().parse::<i64>() else {
1156 continue;
1157 };
1158
1159 rows.push(TagRow {
1160 name,
1161 commit,
1162 // Only an annotated tag has a message of its own; for a lightweight one
1163 // this field is the commit's subject, which belongs to the commit.
1164 message: annotated.then(|| subject(message)).flatten(),
1165 annotated,
1166 created_at: unix_time(created_at),
1167 });
1168 }
1169
1170 Ok(rows)
1171}
1172
1173/// A full ref name reduced to the short form Steid puts in a URL, or `None` when it is
1174/// outside the namespace asked for or is not a name Steid will hand back to git.
1175///
1176/// Validated rather than trusted for the reason [`parse_refs`] gives: this name is
1177/// about to become a link.
1178fn short_ref(full: &[u8], namespace: &str) -> Option<RefName> {
1179 let full = std::str::from_utf8(full).ok()?;
1180 RefName::new(full.strip_prefix(namespace)?).ok()
1181}
1182
1183/// Runs a git command inside a repository and fails on a non-zero exit.
1184///
1185/// Only ever used for commands whose subject has already been confirmed to exist, so a
1186/// failure really is a failure. Built from [`git_command`] so the host isolation 0006
1187/// insists on cannot drift out of this module.
1188/// How long one read-side `git` process may run before it is killed.
1189///
1190/// Every read here is a subprocess on a request path, and nothing bounded it before
1191/// blame and grep arrived — either can run for a long time on a large repository, and
1192/// a request that never finishes holds a worker for as long as the client waits.
1193/// Twenty seconds is far above any read a page should make and far below "hung".
1194const GIT_TIMEOUT: Duration = Duration::from_secs(20);
1195
1196async fn run<I, S>(repo: &Path, args: I) -> Result<Output, GitQueryError>
1197where
1198 I: IntoIterator<Item = S>,
1199 S: AsRef<OsStr>,
1200{
1201 run_within(repo, args, GIT_TIMEOUT).await
1202}
1203
1204// The two exit statuses this module reads as answers rather than as faults. Both are 1
1205// and they are separate constants on purpose: what makes each of them legible is the
1206// question it answers, not the number. See [`run_allowing`], which is the only way
1207// either reaches a command.
1208
1209/// What `git grep` exits with when it matched nothing.
1210const NO_MATCHES: i32 = 1;
1211
1212/// What `git merge-base` exits with for two commits that share no ancestor — documented
1213/// as an answer, with 128 reserved for real errors.
1214const NO_COMMON_ANCESTOR: i32 = 1;
1215
1216/// [`run`] for a command whose exit status is partly an answer.
1217///
1218/// Exists for `git grep` and `git merge-base` alone — grep's 1 is "matched nothing" and
1219/// merge-base's 1 is "no common ancestor", both promised by git's manual. Every other
1220/// command here is asked about something `cat-file --batch-check` has already confirmed
1221/// exists, which is what makes the module's "a non-zero exit is always a fault" rule
1222/// hold. These two are asked questions whose answer can legitimately be "there is
1223/// none".
1224async fn run_allowing<I, S>(repo: &Path, args: I, allowed: &[i32]) -> Result<Output, GitQueryError>
1225where
1226 I: IntoIterator<Item = S>,
1227 S: AsRef<OsStr>,
1228{
1229 run_within_allowing(repo, args, GIT_TIMEOUT, allowed).await
1230}
1231
1232/// [`run`] with an explicit limit, so the timeout path can be tested without waiting
1233/// twenty seconds for it.
1234async fn run_within<I, S>(repo: &Path, args: I, limit: Duration) -> Result<Output, GitQueryError>
1235where
1236 I: IntoIterator<Item = S>,
1237 S: AsRef<OsStr>,
1238{
1239 run_within_allowing(repo, args, limit, &[]).await
1240}
1241
1242/// The whole of running git: isolation, the timeout, and the status rule.
1243async fn run_within_allowing<I, S>(
1244 repo: &Path,
1245 args: I,
1246 limit: Duration,
1247 allowed: &[i32],
1248) -> Result<Output, GitQueryError>
1249where
1250 I: IntoIterator<Item = S>,
1251 S: AsRef<OsStr>,
1252{
1253 let mut command = git_command();
1254 command
1255 .arg("-C")
1256 .arg(repo)
1257 .args(args)
1258 .stdin(Stdio::null())
1259 // Dropping the future on timeout must take the process with it, or a killed
1260 // request leaves git running to completion for nobody.
1261 .kill_on_drop(true);
1262
1263 let output = match tokio::time::timeout(limit, command.output()).await {
1264 Ok(result) => {
1265 result.map_err(|error| GitQueryError::new(format!("could not run git: {error}")))?
1266 }
1267 Err(_elapsed) => return Err(GitQueryError::timed_out(limit)),
1268 };
1269
1270 let expected = output
1271 .status
1272 .code()
1273 .is_some_and(|code| allowed.contains(&code));
1274
1275 if !output.status.success() && !expected {
1276 return Err(GitQueryError::new(format!(
1277 "git exited with {}: {}",
1278 output.status,
1279 String::from_utf8_lossy(&output.stderr).trim()
1280 )));
1281 }
1282
1283 Ok(output)
1284}
1285
1286/// Runs a git command and reads at most `max_bytes` of its output.
1287///
1288/// [`run`] collects everything git writes, which is right for a tree listing and wrong
1289/// for a patch: a single commit can legitimately carry hundreds of megabytes of diff,
1290/// and a page must not be able to pull that into memory. So this one reads through a
1291/// pipe and stops, killing the process rather than draining it — an abandoned `git
1292/// diff-tree` writing into a closed pipe is exactly what SIGPIPE is for.
1293///
1294/// Returns the bytes and whether the cap was hit. **The exit status is only checked
1295/// when it was not**: a process killed part-way through has a status that says so, and
1296/// treating that as a failure would turn every oversized diff into a 500.
1297async fn run_capped<I, S>(
1298 repo: &Path,
1299 args: I,
1300 max_bytes: u64,
1301) -> Result<(Vec<u8>, bool), GitQueryError>
1302where
1303 I: IntoIterator<Item = S>,
1304 S: AsRef<OsStr>,
1305{
1306 let mut command = git_command();
1307 command
1308 .arg("-C")
1309 .arg(repo)
1310 .args(args)
1311 .stdin(Stdio::null())
1312 .stdout(Stdio::piped())
1313 .stderr(Stdio::piped())
1314 .kill_on_drop(true);
1315
1316 let read = async {
1317 let mut child = command
1318 .spawn()
1319 .map_err(|error| GitQueryError::new(format!("could not run git: {error}")))?;
1320
1321 let mut stdout = child.stdout.take().expect("stdout was piped");
1322 let mut bytes = Vec::new();
1323
1324 // One byte past the cap, so hitting it exactly is not mistaken for exceeding
1325 // it. The surplus byte is dropped below.
1326 let limit = max_bytes.saturating_add(1);
1327
1328 (&mut stdout)
1329 .take(limit)
1330 .read_to_end(&mut bytes)
1331 .await
1332 .map_err(|error| GitQueryError::new(format!("could not read from git: {error}")))?;
1333
1334 if bytes.len() as u64 > max_bytes {
1335 bytes.truncate(max_bytes as usize);
1336 // Nothing waits for the exit status: git is still writing, and the whole
1337 // point is not to read the rest. `kill_on_drop` reaps it.
1338 let _ = child.start_kill();
1339
1340 return Ok((bytes, true));
1341 }
1342
1343 // stdout is already drained, so this collects stderr and the status. stderr is
1344 // git's own diagnostics — small by construction, and only read on failure.
1345 let output = child
1346 .wait_with_output()
1347 .await
1348 .map_err(|error| GitQueryError::new(format!("could not wait for git: {error}")))?;
1349
1350 if !output.status.success() {
1351 return Err(GitQueryError::new(format!(
1352 "git exited with {}: {}",
1353 output.status,
1354 String::from_utf8_lossy(&output.stderr).trim()
1355 )));
1356 }
1357
1358 Ok((bytes, false))
1359 };
1360
1361 match tokio::time::timeout(GIT_TIMEOUT, read).await {
1362 Ok(result) => result,
1363 Err(_elapsed) => Err(GitQueryError::timed_out(GIT_TIMEOUT)),
1364 }
1365}
1366
1367/// What a log record carries: id, commit time, author name, subject.
1368///
1369/// Every separator is a NUL, and `-z` separates the records themselves. A commit
1370/// message contains newlines as a matter of course and a name can contain almost
1371/// anything, so splitting on lines or whitespace would misread real history rather than
1372/// exotic history.
1373const LOG_FORMAT: &str = "--format=%H%x00%ct%x00%an%x00%s";
1374
1375/// What a commit page needs, in one record: id, tree, parents, author, committer,
1376/// subject, body.
1377///
1378/// NUL-separated for [`LOG_FORMAT`]'s reason, and the body is deliberately **last** —
1379/// it is the one field that can contain anything at all, so parsing takes ten
1380/// separators and treats whatever remains as the body rather than counting fields from
1381/// both ends.
1382///
1383/// `%P` is the parents, space-separated: an empty string for a root commit, two ids for
1384/// a merge.
1385const COMMIT_FORMAT: &str =
1386 "--format=%H%x00%T%x00%P%x00%an%x00%ae%x00%at%x00%cn%x00%ce%x00%ct%x00%s%x00%b";
1387
1388/// Parses the single record [`COMMIT_FORMAT`] produces.
1389fn parse_commit(stdout: &[u8]) -> Result<CommitDetail, GitQueryError> {
1390 // `splitn` rather than `split`: the body is the eleventh field and may contain
1391 // anything, including — in a message written by a tool rather than a person — a NUL
1392 // of its own. Everything after the tenth separator is the body.
1393 let fields: Vec<&[u8]> = stdout.splitn(11, |byte| *byte == 0).collect();
1394
1395 let [
1396 id,
1397 tree,
1398 parents,
1399 author_name,
1400 author_email,
1401 authored_at,
1402 committer_name,
1403 committer_email,
1404 committed_at,
1405 summary,
1406 body,
1407 ] = fields[..]
1408 else {
1409 return Err(GitQueryError::new(
1410 "git described a commit in a shape we do not understand",
1411 ));
1412 };
1413
1414 let text = |bytes: &[u8]| String::from_utf8_lossy(bytes).into_owned();
1415 let object = |bytes: &[u8]| {
1416 ObjectId::new(String::from_utf8_lossy(bytes).trim())
1417 .map_err(|error| GitQueryError::new(format!("git named a bad object id: {error}")))
1418 };
1419 let seconds = |bytes: &[u8]| {
1420 let value = String::from_utf8_lossy(bytes);
1421 value.trim().parse::<i64>().map(unix_time).map_err(|_| {
1422 GitQueryError::new(format!(
1423 "git dated a commit as {:?}",
1424 value.trim().to_owned()
1425 ))
1426 })
1427 };
1428
1429 Ok(CommitDetail {
1430 id: object(id)?,
1431 tree: object(tree)?,
1432 parents: String::from_utf8_lossy(parents)
1433 .split_whitespace()
1434 .map(|parent| {
1435 ObjectId::new(parent).map_err(|error| {
1436 GitQueryError::new(format!("git named a bad parent id: {error}"))
1437 })
1438 })
1439 .collect::<Result<Vec<_>, _>>()?,
1440 // `%s` is git's subject; trimmed to one line anyway, because that is git's
1441 // invariant rather than something this parser should assume.
1442 summary: text(summary).lines().next().unwrap_or_default().to_owned(),
1443 // git ends the formatted record with a newline of its own, which lands on the
1444 // body because the body is last. Trailing whitespace is not part of a message.
1445 body: text(body).trim_end().to_owned(),
1446 author_name: text(author_name),
1447 author_email: text(author_email),
1448 authored_at: seconds(authored_at)?,
1449 committer_name: text(committer_name),
1450 committer_email: text(committer_email),
1451 committed_at: seconds(committed_at)?,
1452 })
1453}
1454
1455/// Splits `--numstat -p` output into its two halves.
1456///
1457/// git writes every `--numstat` line first and then the patch, so the boundary is the
1458/// first `diff --git ` line — a marker no numstat line can produce, since one always
1459/// begins with a count or the `-` that stands for a binary file. The blank line git
1460/// puts between the two is not relied on.
1461///
1462/// A patch that is entirely absent — a commit that changed nothing, or a read cut short
1463/// before the patch began — leaves the second half empty, which is a state the caller
1464/// already has to handle.
1465fn split_numstat(stdout: &[u8]) -> (&[u8], &[u8]) {
1466 const MARKER: &[u8] = b"diff --git ";
1467
1468 if stdout.starts_with(MARKER) {
1469 return (&[], stdout);
1470 }
1471
1472 for (index, byte) in stdout.iter().enumerate() {
1473 if *byte == b'\n' && stdout[index + 1..].starts_with(MARKER) {
1474 return stdout.split_at(index + 1);
1475 }
1476 }
1477
1478 (stdout, &[])
1479}
1480
1481#[cfg(test)]
1482mod tests {
1483 use std::collections::HashMap;
1484
1485 use tempfile::TempDir;
1486
1487 use super::*;
1488 use crate::domain::EntryKind;
1489
1490 /// Fixed so a timestamp assertion is exact rather than approximate.
1491 const FIRST_COMMIT: i64 = 1_700_000_000;
1492 const SECOND_COMMIT: i64 = 1_700_000_100;
1493 const THIRD_COMMIT: i64 = 1_700_000_200;
1494
1495 /// A subject with the punctuation a naive parser splits on, followed by a body — so
1496 /// a test can prove the body does not leak into the summary.
1497 const ODD_MESSAGE: &str =
1498 "third: 'quotes', \"doubles\" | pipes\n\nbody line one\nbody line two";
1499
1500 const BINARY: &[u8] = &[0x00, 0x01, 0xff, 0xfe, 0x80];
1501
1502 fn handle() -> OrgName {
1503 OrgName::new("jamesgill").expect("valid handle")
1504 }
1505
1506 fn repo_name() -> RepoName {
1507 RepoName::new("steid").expect("valid repository name")
1508 }
1509
1510 fn rev(value: &str) -> RefName {
1511 RefName::new(value).expect("valid revision")
1512 }
1513
1514 fn path(value: &str) -> RepoPath {
1515 RepoPath::new(value).expect("valid path")
1516 }
1517
1518 /// Runs git in a fixture, isolated from the host's configuration the same way the
1519 /// adapter is — otherwise a developer's `commit.gpgsign` or `init.defaultBranch`
1520 /// decides whether the suite passes.
1521 fn git(dir: &Path, when: i64, args: &[&str]) {
1522 let date = format!("@{when} +0000");
1523
1524 let output = std::process::Command::new("git")
1525 .arg("-C")
1526 .arg(dir)
1527 .args(args)
1528 .env("GIT_CONFIG_GLOBAL", "/dev/null")
1529 .env("GIT_CONFIG_SYSTEM", "/dev/null")
1530 .env("GIT_AUTHOR_NAME", "Ada Lovelace")
1531 .env("GIT_AUTHOR_EMAIL", "ada@example.com")
1532 .env("GIT_COMMITTER_NAME", "Ada Lovelace")
1533 .env("GIT_COMMITTER_EMAIL", "ada@example.com")
1534 .env("GIT_AUTHOR_DATE", &date)
1535 .env("GIT_COMMITTER_DATE", &date)
1536 .output()
1537 .expect("git should be on PATH");
1538
1539 assert!(
1540 output.status.success(),
1541 "git {args:?} failed: {}",
1542 String::from_utf8_lossy(&output.stderr)
1543 );
1544 }
1545
1546 /// A data directory holding one empty bare repository, exactly as Steid creates it.
1547 ///
1548 /// The `TempDir` is returned because dropping it deletes the fixture.
1549 fn empty() -> (TempDir, DiskGitQuery) {
1550 let dir = TempDir::new().expect("temp dir");
1551 let query = DiskGitQuery::new(dir.path());
1552 let repo = query.repo_path(&handle(), &repo_name());
1553
1554 std::fs::create_dir_all(repo.parent().expect("has a parent")).expect("create handle dir");
1555 git(
1556 dir.path(),
1557 FIRST_COMMIT,
1558 &[
1559 "init",
1560 "--bare",
1561 "--quiet",
1562 "--template=",
1563 "--initial-branch=main",
1564 "--",
1565 repo.to_str().expect("utf-8 fixture path"),
1566 ],
1567 );
1568
1569 (dir, query)
1570 }
1571
1572 /// The empty repository with three commits pushed into it, the way a real one fills
1573 /// up — a working copy and a push, rather than plumbing straight into the object
1574 /// store.
1575 fn populated() -> (TempDir, DiskGitQuery) {
1576 let (dir, query) = empty();
1577 let repo = query.repo_path(&handle(), &repo_name());
1578 let work = dir.path().join("work");
1579
1580 std::fs::create_dir_all(work.join("src/deep")).expect("create work tree");
1581 git(&work, FIRST_COMMIT, &["init", "--quiet", "-b", "main"]);
1582
1583 std::fs::write(work.join("README.md"), b"hello\n").expect("write");
1584 std::fs::write(work.join("with space.txt"), b"spaced\n").expect("write");
1585 std::fs::write(work.join("bin.dat"), BINARY).expect("write");
1586 std::fs::write(work.join("big.txt"), vec![b'x'; 100]).expect("write");
1587 std::fs::write(work.join("src/deep/file.rs"), b"fn main() {}\n").expect("write");
1588 std::os::unix::fs::symlink("README.md", work.join("link")).expect("symlink");
1589
1590 git(&work, FIRST_COMMIT, &["add", "-A"]);
1591 git(&work, FIRST_COMMIT, &["commit", "--quiet", "-m", "first"]);
1592
1593 std::fs::write(work.join("README.md"), b"hello again\n").expect("write");
1594 git(&work, SECOND_COMMIT, &["add", "-A"]);
1595 git(&work, SECOND_COMMIT, &["commit", "--quiet", "-m", "second"]);
1596
1597 git(
1598 &work,
1599 THIRD_COMMIT,
1600 &["commit", "--quiet", "--allow-empty", "-m", ODD_MESSAGE],
1601 );
1602
1603 git(
1604 &work,
1605 THIRD_COMMIT,
1606 &[
1607 "push",
1608 "--quiet",
1609 repo.to_str().expect("utf-8 fixture path"),
1610 "main",
1611 ],
1612 );
1613
1614 (dir, query)
1615 }
1616
1617 /// A listing keyed by name, so an assertion does not depend on an order the port
1618 /// explicitly does not promise.
1619 fn by_name(entries: Vec<TreeEntry>) -> HashMap<String, TreeEntry> {
1620 entries
1621 .into_iter()
1622 .map(|entry| (entry.name.clone(), entry))
1623 .collect()
1624 }
1625
1626 // --- ref snapshots ---------------------------------------------------------
1627
1628 /// The snapshot as a map, so an assertion does not depend on git's ordering.
1629 async fn snapshot(query: &DiskGitQuery) -> HashMap<String, String> {
1630 query
1631 .ref_snapshot(&handle(), &repo_name())
1632 .await
1633 .expect("should read")
1634 .into_iter()
1635 .map(|(name, id)| (name.as_str().to_owned(), id.as_str().to_owned()))
1636 .collect()
1637 }
1638
1639 #[tokio::test]
1640 async fn an_empty_repository_snapshots_to_nothing() {
1641 // Nothing pushed yet is not a failure — the first push diffs against this.
1642 let (_dir, query) = empty();
1643
1644 assert!(snapshot(&query).await.is_empty());
1645 }
1646
1647 #[tokio::test]
1648 async fn a_snapshot_names_refs_in_full_and_by_the_object_the_ref_itself_holds() {
1649 // An annotated tag reports the *tag object*, not the commit it peels to: what a
1650 // push changes is the ref, and re-annotating the same commit is a change.
1651 let (dir, query) = populated();
1652 let repo = query.repo_path(&handle(), &repo_name());
1653 let work = dir.path().join("work");
1654
1655 git(&work, THIRD_COMMIT, &["tag", "-a", "v0.1.0", "-m", "first"]);
1656 git(&work, THIRD_COMMIT, &["branch", "feat/x"]);
1657 git(
1658 &work,
1659 THIRD_COMMIT,
1660 &[
1661 "push",
1662 "--quiet",
1663 repo.to_str().expect("utf-8 fixture path"),
1664 "feat/x",
1665 "v0.1.0",
1666 ],
1667 );
1668
1669 let snapshot = snapshot(&query).await;
1670 let main = query
1671 .resolve(&handle(), &repo_name(), &rev("main"))
1672 .await
1673 .expect("should read")
1674 .expect("main resolves");
1675
1676 assert_eq!(snapshot.len(), 3);
1677 assert_eq!(snapshot.get("refs/heads/main"), Some(&main.to_string()));
1678 assert_eq!(snapshot.get("refs/heads/feat/x"), Some(&main.to_string()));
1679 assert_ne!(
1680 snapshot.get("refs/tags/v0.1.0"),
1681 Some(&main.to_string()),
1682 "an annotated tag is its own object"
1683 );
1684 }
1685
1686 #[tokio::test]
1687 async fn a_snapshot_taken_twice_around_a_push_shows_what_moved() {
1688 // The sequence the push path actually performs, end to end.
1689 let (dir, query) = populated();
1690 let repo = query.repo_path(&handle(), &repo_name());
1691 let work = dir.path().join("work");
1692
1693 let before = snapshot(&query).await;
1694
1695 std::fs::write(work.join("README.md"), b"hello once more\n").expect("write");
1696 git(&work, THIRD_COMMIT, &["add", "-A"]);
1697 git(&work, THIRD_COMMIT, &["commit", "--quiet", "-m", "fourth"]);
1698 git(
1699 &work,
1700 THIRD_COMMIT,
1701 &[
1702 "push",
1703 "--quiet",
1704 repo.to_str().expect("utf-8 fixture path"),
1705 "main",
1706 ],
1707 );
1708
1709 let after = snapshot(&query).await;
1710
1711 assert_eq!(before.len(), 1);
1712 assert_eq!(after.len(), 1);
1713 assert_ne!(before.get("refs/heads/main"), after.get("refs/heads/main"));
1714 }
1715
1716 // --- grep ------------------------------------------------------------------
1717
1718 async fn hits(query: &str, limit: usize) -> Vec<GrepHit> {
1719 let (_dir, query_port) = populated();
1720 let commit = query_port
1721 .resolve(&handle(), &repo_name(), &rev("main"))
1722 .await
1723 .expect("should read")
1724 .expect("main resolves");
1725
1726 query_port
1727 .grep(&handle(), &repo_name(), &commit, query, limit)
1728 .await
1729 .expect("should grep")
1730 }
1731
1732 #[tokio::test]
1733 async fn a_search_finds_the_line_it_matched() {
1734 let found = hits("fn main", 10).await;
1735
1736 assert_eq!(found.len(), 1);
1737 assert_eq!(found[0].path.as_str(), "src/deep/file.rs");
1738 assert_eq!(found[0].line, 1);
1739 assert_eq!(found[0].text, "fn main() {}");
1740 }
1741
1742 #[tokio::test]
1743 async fn a_search_that_matches_nothing_is_not_a_failure() {
1744 // `git grep` exits 1 here, which every other command in this module would treat
1745 // as a fault. This is the one exception, and this test is what pins it.
1746 assert_eq!(hits("nothing matches this", 10).await, Vec::new());
1747 }
1748
1749 #[tokio::test]
1750 async fn a_binary_file_is_never_reported() {
1751 // `bin.dat` contains 0x00 0x01 0xff 0xfe 0x80, so a byte-wise search would hit
1752 // it. `-I` is what keeps unreadable matches off the page.
1753 let found = hits("\u{fffd}", 10).await;
1754
1755 assert!(
1756 found.iter().all(|hit| hit.path.as_str() != "bin.dat"),
1757 "a binary file should never appear in results"
1758 );
1759 }
1760
1761 #[tokio::test]
1762 async fn a_search_is_a_fixed_string_not_a_pattern() {
1763 // `.` would match every line if this were a regular expression.
1764 assert_eq!(hits("hello.again", 10).await, Vec::new());
1765 }
1766
1767 #[tokio::test]
1768 async fn the_limit_bounds_what_comes_back() {
1769 // Every file in the fixture contains an `e` somewhere, so this is more than one
1770 // match without depending on how many.
1771 assert_eq!(hits("e", 2).await.len(), 2);
1772 }
1773
1774 // --- an empty repository ---------------------------------------------------
1775
1776 #[tokio::test]
1777 async fn an_empty_repository_has_no_default_branch() {
1778 // The distinction the port exists for: HEAD names `main`, but `main` has no
1779 // commits, so "nothing pushed yet" rather than a branch a page can browse.
1780 let (_dir, query) = empty();
1781
1782 assert_eq!(
1783 query
1784 .default_branch(&handle(), &repo_name())
1785 .await
1786 .expect("should read"),
1787 None
1788 );
1789 }
1790
1791 #[tokio::test]
1792 async fn nothing_resolves_in_an_empty_repository() {
1793 let (_dir, query) = empty();
1794
1795 for revision in ["main", "HEAD", "v1.0"] {
1796 assert_eq!(
1797 query
1798 .resolve(&handle(), &repo_name(), &rev(revision))
1799 .await
1800 .expect("should read"),
1801 None,
1802 "{revision} should not resolve"
1803 );
1804 }
1805 }
1806
1807 #[tokio::test]
1808 async fn an_empty_repository_lists_nothing_and_reads_nothing() {
1809 let (_dir, query) = empty();
1810
1811 assert_eq!(
1812 query
1813 .list_tree(&handle(), &repo_name(), &rev("main"), &RepoPath::root())
1814 .await
1815 .expect("should read"),
1816 None
1817 );
1818 assert_eq!(
1819 query
1820 .read_blob(
1821 &handle(),
1822 &repo_name(),
1823 &rev("main"),
1824 &path("README.md"),
1825 1024
1826 )
1827 .await
1828 .expect("should read"),
1829 None
1830 );
1831 }
1832
1833 #[tokio::test]
1834 async fn an_empty_repository_has_an_empty_log() {
1835 // `git log` is a fatal error here, and an empty list is what the port promises.
1836 let (_dir, query) = empty();
1837
1838 assert_eq!(
1839 query
1840 .log(&handle(), &repo_name(), &rev("main"), 10)
1841 .await
1842 .expect("should read"),
1843 Vec::new()
1844 );
1845 }
1846
1847 // --- a missing repository is a failure, not a 404 ---------------------------
1848
1849 #[tokio::test]
1850 async fn a_repository_that_is_not_on_disk_is_an_error() {
1851 // A record with no directory is a fault to investigate, not a "no such branch".
1852 // Answering `Ok(None)` here would hide it behind a plausible-looking 404.
1853 let (_dir, query) = empty();
1854 let missing = RepoName::new("never-created").expect("valid repository name");
1855
1856 assert!(query.default_branch(&handle(), &missing).await.is_err());
1857 assert!(
1858 query
1859 .resolve(&handle(), &missing, &rev("main"))
1860 .await
1861 .is_err()
1862 );
1863 assert!(
1864 query
1865 .list_tree(&handle(), &missing, &rev("main"), &RepoPath::root())
1866 .await
1867 .is_err()
1868 );
1869 assert!(
1870 query
1871 .log(&handle(), &missing, &rev("main"), 10)
1872 .await
1873 .is_err()
1874 );
1875 }
1876
1877 // --- default_branch and resolve --------------------------------------------
1878
1879 #[tokio::test]
1880 async fn a_repository_with_commits_reports_its_default_branch() {
1881 let (_dir, query) = populated();
1882
1883 assert_eq!(
1884 query
1885 .default_branch(&handle(), &repo_name())
1886 .await
1887 .expect("should read"),
1888 Some(RefName::from_trusted("main"))
1889 );
1890 }
1891
1892 #[tokio::test]
1893 async fn a_branch_and_head_resolve_to_the_same_commit() {
1894 let (_dir, query) = populated();
1895
1896 let main = query
1897 .resolve(&handle(), &repo_name(), &rev("main"))
1898 .await
1899 .expect("should read")
1900 .expect("main should resolve");
1901 let head = query
1902 .resolve(&handle(), &repo_name(), &rev("HEAD"))
1903 .await
1904 .expect("should read");
1905
1906 assert_eq!(head, Some(main));
1907 }
1908
1909 #[tokio::test]
1910 async fn a_commit_id_resolves_to_itself() {
1911 let (_dir, query) = populated();
1912
1913 let main = query
1914 .resolve(&handle(), &repo_name(), &rev("main"))
1915 .await
1916 .expect("should read")
1917 .expect("main should resolve");
1918
1919 assert_eq!(
1920 query
1921 .resolve(&handle(), &repo_name(), &rev(main.as_str()))
1922 .await
1923 .expect("should read"),
1924 Some(main)
1925 );
1926 }
1927
1928 #[tokio::test]
1929 async fn an_unknown_revision_resolves_to_nothing() {
1930 let (_dir, query) = populated();
1931
1932 assert_eq!(
1933 query
1934 .resolve(&handle(), &repo_name(), &rev("no-such-branch"))
1935 .await
1936 .expect("looking up a missing branch is not a failure"),
1937 None
1938 );
1939 }
1940
1941 // --- list_tree --------------------------------------------------------------
1942
1943 #[tokio::test]
1944 async fn the_root_lists_every_top_level_entry() {
1945 let (_dir, query) = populated();
1946
1947 let entries = by_name(
1948 query
1949 .list_tree(&handle(), &repo_name(), &rev("main"), &RepoPath::root())
1950 .await
1951 .expect("should read")
1952 .expect("the root is a directory"),
1953 );
1954
1955 let mut names: Vec<&str> = entries.keys().map(String::as_str).collect();
1956 names.sort_unstable();
1957 assert_eq!(
1958 names,
1959 vec![
1960 "README.md",
1961 "big.txt",
1962 "bin.dat",
1963 "link",
1964 "src",
1965 "with space.txt"
1966 ]
1967 );
1968 assert_eq!(entries["src"].kind, EntryKind::Tree);
1969 assert_eq!(entries["README.md"].kind, EntryKind::Blob);
1970 assert_eq!(
1971 entries["link"].kind,
1972 EntryKind::Symlink,
1973 "a symlink is its own kind, not a file"
1974 );
1975 }
1976
1977 #[tokio::test]
1978 async fn a_listing_carries_blob_sizes_but_not_tree_sizes() {
1979 let (_dir, query) = populated();
1980
1981 let entries = by_name(
1982 query
1983 .list_tree(&handle(), &repo_name(), &rev("main"), &RepoPath::root())
1984 .await
1985 .expect("should read")
1986 .expect("the root is a directory"),
1987 );
1988
1989 assert_eq!(entries["big.txt"].size, Some(100));
1990 assert_eq!(
1991 entries["src"].size, None,
1992 "a directory has no size a listing can show"
1993 );
1994 }
1995
1996 #[tokio::test]
1997 async fn a_filename_containing_a_space_survives_the_listing() {
1998 // The reason `-z` is not optional: split on whitespace and this name becomes two.
1999 let (_dir, query) = populated();
2000
2001 let entries = by_name(
2002 query
2003 .list_tree(&handle(), &repo_name(), &rev("main"), &RepoPath::root())
2004 .await
2005 .expect("should read")
2006 .expect("the root is a directory"),
2007 );
2008
2009 assert_eq!(entries["with space.txt"].kind, EntryKind::Blob);
2010 assert_eq!(entries["with space.txt"].size, Some(7));
2011 }
2012
2013 #[tokio::test]
2014 async fn a_nested_directory_lists_only_its_own_entries() {
2015 let (_dir, query) = populated();
2016
2017 let entries = query
2018 .list_tree(&handle(), &repo_name(), &rev("main"), &path("src"))
2019 .await
2020 .expect("should read")
2021 .expect("src is a directory");
2022
2023 assert_eq!(entries.len(), 1);
2024 assert_eq!(entries[0].name, "deep", "names are entry names, not paths");
2025 assert_eq!(entries[0].kind, EntryKind::Tree);
2026
2027 let deeper = query
2028 .list_tree(&handle(), &repo_name(), &rev("main"), &path("src/deep"))
2029 .await
2030 .expect("should read")
2031 .expect("src/deep is a directory");
2032
2033 assert_eq!(deeper.len(), 1);
2034 assert_eq!(deeper[0].name, "file.rs");
2035 }
2036
2037 #[tokio::test]
2038 async fn listing_a_file_as_a_directory_finds_nothing() {
2039 // git calls this a fatal error; to a visitor it is a wrong URL.
2040 let (_dir, query) = populated();
2041
2042 assert_eq!(
2043 query
2044 .list_tree(&handle(), &repo_name(), &rev("main"), &path("README.md"))
2045 .await
2046 .expect("a file is not a failure"),
2047 None
2048 );
2049 }
2050
2051 #[tokio::test]
2052 async fn listing_a_path_that_is_not_there_finds_nothing() {
2053 let (_dir, query) = populated();
2054
2055 for missing in ["nope", "src/nope", "README.md/nope"] {
2056 assert_eq!(
2057 query
2058 .list_tree(&handle(), &repo_name(), &rev("main"), &path(missing))
2059 .await
2060 .expect("should read"),
2061 None,
2062 "{missing} should not be found"
2063 );
2064 }
2065 }
2066
2067 #[tokio::test]
2068 async fn listing_at_an_unknown_revision_finds_nothing() {
2069 let (_dir, query) = populated();
2070
2071 assert_eq!(
2072 query
2073 .list_tree(
2074 &handle(),
2075 &repo_name(),
2076 &rev("no-such-branch"),
2077 &RepoPath::root()
2078 )
2079 .await
2080 .expect("should read"),
2081 None
2082 );
2083 }
2084
2085 #[tokio::test]
2086 async fn a_listing_reflects_the_revision_it_was_asked_for() {
2087 // Proves the revision is actually used rather than HEAD being read every time.
2088 let (_dir, query) = populated();
2089
2090 let first = query
2091 .log(&handle(), &repo_name(), &rev("main"), 10)
2092 .await
2093 .expect("should read")
2094 .last()
2095 .expect("three commits")
2096 .id
2097 .clone();
2098
2099 let old = query
2100 .read_blob(
2101 &handle(),
2102 &repo_name(),
2103 &rev(first.as_str()),
2104 &path("README.md"),
2105 1024,
2106 )
2107 .await
2108 .expect("should read")
2109 .expect("README existed in the first commit");
2110
2111 assert_eq!(old.content.as_deref(), Some(b"hello\n".as_slice()));
2112 }
2113
2114 // --- read_blob --------------------------------------------------------------
2115
2116 #[tokio::test]
2117 async fn a_file_is_read_with_its_size_and_content() {
2118 let (_dir, query) = populated();
2119
2120 let blob = query
2121 .read_blob(
2122 &handle(),
2123 &repo_name(),
2124 &rev("main"),
2125 &path("README.md"),
2126 1024,
2127 )
2128 .await
2129 .expect("should read")
2130 .expect("README.md is a file");
2131
2132 assert_eq!(blob.size, 12);
2133 assert_eq!(blob.content.as_deref(), Some(b"hello again\n".as_slice()));
2134 }
2135
2136 #[tokio::test]
2137 async fn a_binary_file_survives_intact() {
2138 // Nothing in this adapter may assume UTF-8: a lossy conversion here would swap
2139 // bytes for replacement characters and quietly corrupt every download.
2140 let (_dir, query) = populated();
2141
2142 let blob = query
2143 .read_blob(
2144 &handle(),
2145 &repo_name(),
2146 &rev("main"),
2147 &path("bin.dat"),
2148 1024,
2149 )
2150 .await
2151 .expect("should read")
2152 .expect("bin.dat is a file");
2153
2154 assert_eq!(blob.size, BINARY.len() as u64);
2155 assert_eq!(blob.content.as_deref(), Some(BINARY));
2156 }
2157
2158 #[tokio::test]
2159 async fn a_file_over_the_cap_reports_its_size_without_its_content() {
2160 let (_dir, query) = populated();
2161
2162 let blob = query
2163 .read_blob(&handle(), &repo_name(), &rev("main"), &path("big.txt"), 10)
2164 .await
2165 .expect("should read")
2166 .expect("big.txt is a file");
2167
2168 assert_eq!(blob.size, 100, "the page still says how big it is");
2169 assert_eq!(blob.content, None);
2170 }
2171
2172 #[tokio::test]
2173 async fn a_file_exactly_at_the_cap_is_still_read() {
2174 let (_dir, query) = populated();
2175
2176 let blob = query
2177 .read_blob(&handle(), &repo_name(), &rev("main"), &path("big.txt"), 100)
2178 .await
2179 .expect("should read")
2180 .expect("big.txt is a file");
2181
2182 assert_eq!(blob.content.map(|content| content.len()), Some(100));
2183 }
2184
2185 #[tokio::test]
2186 async fn a_file_with_a_space_in_its_name_can_be_read() {
2187 let (_dir, query) = populated();
2188
2189 let blob = query
2190 .read_blob(
2191 &handle(),
2192 &repo_name(),
2193 &rev("main"),
2194 &path("with space.txt"),
2195 1024,
2196 )
2197 .await
2198 .expect("should read")
2199 .expect("the file is there");
2200
2201 assert_eq!(blob.content.as_deref(), Some(b"spaced\n".as_slice()));
2202 }
2203
2204 #[tokio::test]
2205 async fn reading_a_directory_as_a_file_finds_nothing() {
2206 let (_dir, query) = populated();
2207
2208 for directory in ["src", "src/deep", ""] {
2209 assert_eq!(
2210 query
2211 .read_blob(
2212 &handle(),
2213 &repo_name(),
2214 &rev("main"),
2215 &path(directory),
2216 1024
2217 )
2218 .await
2219 .expect("a directory is not a failure"),
2220 None,
2221 "{directory:?} is a directory"
2222 );
2223 }
2224 }
2225
2226 #[tokio::test]
2227 async fn reading_a_path_that_is_not_there_finds_nothing() {
2228 let (_dir, query) = populated();
2229
2230 for missing in ["nope.txt", "src/nope.txt", "README.md/nope"] {
2231 assert_eq!(
2232 query
2233 .read_blob(&handle(), &repo_name(), &rev("main"), &path(missing), 1024)
2234 .await
2235 .expect("should read"),
2236 None,
2237 "{missing} should not be found"
2238 );
2239 }
2240 }
2241
2242 #[tokio::test]
2243 async fn a_blobs_id_matches_the_listing() {
2244 // Two commands, one object: if they disagree, one of the two parsers is wrong.
2245 let (_dir, query) = populated();
2246
2247 let entries = by_name(
2248 query
2249 .list_tree(&handle(), &repo_name(), &rev("main"), &RepoPath::root())
2250 .await
2251 .expect("should read")
2252 .expect("the root is a directory"),
2253 );
2254 let blob = query
2255 .read_blob(
2256 &handle(),
2257 &repo_name(),
2258 &rev("main"),
2259 &path("README.md"),
2260 1024,
2261 )
2262 .await
2263 .expect("should read")
2264 .expect("README.md is a file");
2265
2266 assert_eq!(blob.id, entries["README.md"].id);
2267 assert_eq!(Some(blob.size), entries["README.md"].size);
2268 }
2269
2270 #[tokio::test]
2271 async fn a_symlink_reads_as_its_target_path() {
2272 // The object store cannot tell a symlink from a file — both are blobs — and its
2273 // content is the path it points at. Showing that is more use than a blank page,
2274 // so this is a deliberate choice rather than an oversight.
2275 let (_dir, query) = populated();
2276
2277 let blob = query
2278 .read_blob(&handle(), &repo_name(), &rev("main"), &path("link"), 1024)
2279 .await
2280 .expect("should read")
2281 .expect("a symlink is readable");
2282
2283 assert_eq!(blob.content.as_deref(), Some(b"README.md".as_slice()));
2284 }
2285
2286 // --- log ---------------------------------------------------------------------
2287
2288 #[tokio::test]
2289 async fn the_log_is_newest_first() {
2290 let (_dir, query) = populated();
2291
2292 let commits = query
2293 .log(&handle(), &repo_name(), &rev("main"), 10)
2294 .await
2295 .expect("should read");
2296
2297 assert_eq!(commits.len(), 3);
2298 assert_eq!(
2299 commits
2300 .iter()
2301 .map(|commit| commit.summary.as_str())
2302 .collect::<Vec<_>>(),
2303 vec!["third: 'quotes', \"doubles\" | pipes", "second", "first"]
2304 );
2305 }
2306
2307 #[tokio::test]
2308 async fn the_log_stops_at_the_limit() {
2309 let (_dir, query) = populated();
2310
2311 let commits = query
2312 .log(&handle(), &repo_name(), &rev("main"), 2)
2313 .await
2314 .expect("should read");
2315
2316 assert_eq!(commits.len(), 2);
2317 assert_eq!(commits[0].summary, "third: 'quotes', \"doubles\" | pipes");
2318
2319 assert!(
2320 query
2321 .log(&handle(), &repo_name(), &rev("main"), 0)
2322 .await
2323 .expect("should read")
2324 .is_empty()
2325 );
2326 }
2327
2328 #[tokio::test]
2329 async fn a_commit_message_body_does_not_leak_into_the_summary() {
2330 // The message has a blank line and two body lines. A parser that split the
2331 // stream on newlines would report "body line one" as a separate commit.
2332 let (_dir, query) = populated();
2333
2334 let commits = query
2335 .log(&handle(), &repo_name(), &rev("main"), 10)
2336 .await
2337 .expect("should read");
2338
2339 assert_eq!(commits.len(), 3, "three commits, not five");
2340 assert!(
2341 !commits[0].summary.contains("body line"),
2342 "got: {:?}",
2343 commits[0].summary
2344 );
2345 }
2346
2347 #[tokio::test]
2348 async fn a_log_entry_carries_its_author_and_time() {
2349 let (_dir, query) = populated();
2350
2351 let commits = query
2352 .log(&handle(), &repo_name(), &rev("main"), 10)
2353 .await
2354 .expect("should read");
2355
2356 assert_eq!(commits[0].author_name, "Ada Lovelace");
2357 assert_eq!(
2358 commits[0].committed_at,
2359 UNIX_EPOCH + Duration::from_secs(THIRD_COMMIT as u64)
2360 );
2361 assert_eq!(
2362 commits[2].committed_at,
2363 UNIX_EPOCH + Duration::from_secs(FIRST_COMMIT as u64)
2364 );
2365 }
2366
2367 #[tokio::test]
2368 async fn a_log_entry_id_is_the_commit_the_revision_resolves_to() {
2369 let (_dir, query) = populated();
2370
2371 let head = query
2372 .resolve(&handle(), &repo_name(), &rev("main"))
2373 .await
2374 .expect("should read")
2375 .expect("main resolves");
2376 let commits = query
2377 .log(&handle(), &repo_name(), &rev("main"), 1)
2378 .await
2379 .expect("should read");
2380
2381 assert_eq!(commits[0].id, head);
2382 }
2383
2384 #[tokio::test]
2385 async fn the_log_of_an_unknown_revision_is_empty_rather_than_a_failure() {
2386 let (_dir, query) = populated();
2387
2388 assert_eq!(
2389 query
2390 .log(&handle(), &repo_name(), &rev("no-such-branch"), 10)
2391 .await
2392 .expect("an unknown branch is not a failure"),
2393 Vec::new()
2394 );
2395 }
2396
2397 #[tokio::test]
2398 async fn a_log_can_start_from_an_older_commit() {
2399 let (_dir, query) = populated();
2400
2401 let all = query
2402 .log(&handle(), &repo_name(), &rev("main"), 10)
2403 .await
2404 .expect("should read");
2405 let from_second = query
2406 .log(&handle(), &repo_name(), &rev(all[1].id.as_str()), 10)
2407 .await
2408 .expect("should read");
2409
2410 assert_eq!(from_second.len(), 2, "history behind the second commit");
2411 assert_eq!(from_second[0].id, all[1].id);
2412 }
2413
2414 // --- list_refs ---------------------------------------------------------------
2415
2416 /// The populated repository with a second branch and two tags pushed into it — one
2417 /// lightweight, one annotated, because they are different objects and the switcher
2418 /// must not care.
2419 fn with_refs() -> (TempDir, DiskGitQuery) {
2420 let (dir, query) = populated();
2421 let repo = query.repo_path(&handle(), &repo_name());
2422 let work = dir.path().join("work");
2423 let target = repo.to_str().expect("utf-8 fixture path").to_owned();
2424
2425 // A slash in the name, because that is what makes a ref name interesting: it is
2426 // the case the `/-/` separator in the URL exists for.
2427 git(&work, THIRD_COMMIT, &["branch", "feature/login"]);
2428 git(&work, THIRD_COMMIT, &["tag", "v1.0"]);
2429 git(
2430 &work,
2431 THIRD_COMMIT,
2432 &["tag", "-a", "v2.0", "-m", "second release"],
2433 );
2434 git(
2435 &work,
2436 THIRD_COMMIT,
2437 &["push", "--quiet", &target, "feature/login"],
2438 );
2439 git(&work, THIRD_COMMIT, &["push", "--quiet", &target, "--tags"]);
2440
2441 (dir, query)
2442 }
2443
2444 fn named(refs: &[GitRef], kind: RefKind) -> Vec<String> {
2445 let mut names: Vec<String> = refs
2446 .iter()
2447 .filter(|git_ref| git_ref.kind == kind)
2448 .map(|git_ref| git_ref.name.to_string())
2449 .collect();
2450
2451 // The port promises no order, so a test that asserted one would be asserting
2452 // something the adapter is free to change.
2453 names.sort();
2454 names
2455 }
2456
2457 #[tokio::test]
2458 async fn branches_and_tags_are_listed_and_told_apart() {
2459 let (_dir, query) = with_refs();
2460
2461 let refs = query
2462 .list_refs(&handle(), &repo_name())
2463 .await
2464 .expect("should read");
2465
2466 assert_eq!(
2467 named(&refs, RefKind::Branch),
2468 vec!["feature/login".to_owned(), "main".to_owned()]
2469 );
2470 // An annotated tag points at a tag object rather than a commit, and a
2471 // lightweight one points straight at the commit. Both are tags.
2472 assert_eq!(
2473 named(&refs, RefKind::Tag),
2474 vec!["v1.0".to_owned(), "v2.0".to_owned()]
2475 );
2476 }
2477
2478 #[tokio::test]
2479 async fn a_repository_with_one_branch_lists_just_it() {
2480 let (_dir, query) = populated();
2481
2482 let refs = query
2483 .list_refs(&handle(), &repo_name())
2484 .await
2485 .expect("should read");
2486
2487 assert_eq!(refs.len(), 1);
2488 assert_eq!(refs[0].name.as_str(), "main");
2489 assert_eq!(refs[0].kind, RefKind::Branch);
2490 }
2491
2492 #[tokio::test]
2493 async fn an_empty_repository_lists_no_refs() {
2494 // HEAD names `main`, but no ref exists, so there is nothing to switch to. An
2495 // empty list rather than an error: nothing pushed yet is not a failure.
2496 let (_dir, query) = empty();
2497
2498 assert_eq!(
2499 query
2500 .list_refs(&handle(), &repo_name())
2501 .await
2502 .expect("should read"),
2503 Vec::new()
2504 );
2505 }
2506
2507 #[tokio::test]
2508 async fn listing_refs_of_a_repository_that_is_not_on_disk_is_an_error() {
2509 let (_dir, query) = empty();
2510 let missing = RepoName::new("never-created").expect("valid repository name");
2511
2512 assert!(query.list_refs(&handle(), &missing).await.is_err());
2513 }
2514
2515 #[test]
2516 fn refs_are_parsed_from_nul_terminated_records() {
2517 // git ends each record with a newline the format cannot suppress, so it arrives
2518 // in front of the next record's name. Anything outside the two namespaces is
2519 // dropped rather than guessed at.
2520 let stdout = b"refs/heads/main\0\nrefs/tags/v1.0\0\nrefs/pull/7/head\0\n";
2521 let refs = parse_refs(stdout);
2522
2523 assert_eq!(refs.len(), 2);
2524 assert_eq!(refs[0].name.as_str(), "main");
2525 assert_eq!(refs[0].kind, RefKind::Branch);
2526 assert_eq!(refs[1].name.as_str(), "v1.0");
2527 assert_eq!(refs[1].kind, RefKind::Tag);
2528 }
2529
2530 #[test]
2531 fn nothing_is_parsed_from_an_empty_listing() {
2532 assert!(parse_refs(b"").is_empty());
2533 }
2534
2535 // --- count_commits ------------------------------------------------------------
2536
2537 #[tokio::test]
2538 async fn commits_are_counted_from_the_revision_asked_about() {
2539 let (_dir, query) = populated();
2540
2541 assert_eq!(
2542 query
2543 .count_commits(&handle(), &repo_name(), &rev("main"))
2544 .await
2545 .expect("should count"),
2546 3
2547 );
2548 }
2549
2550 #[tokio::test]
2551 async fn a_revision_with_no_commits_counts_zero_rather_than_failing() {
2552 // Both spellings of "nothing here": an empty repository, and a branch that is
2553 // not there. `rev-list` is fatal for each, and a page asking how big a
2554 // repository is wants a number.
2555 let (_dir, empty_query) = empty();
2556 assert_eq!(
2557 empty_query
2558 .count_commits(&handle(), &repo_name(), &rev("main"))
2559 .await
2560 .expect("should count"),
2561 0
2562 );
2563
2564 let (_dir, query) = populated();
2565 assert_eq!(
2566 query
2567 .count_commits(&handle(), &repo_name(), &rev("no-such-branch"))
2568 .await
2569 .expect("should count"),
2570 0
2571 );
2572 }
2573
2574 #[tokio::test]
2575 async fn counting_a_repository_that_is_not_on_disk_is_an_error() {
2576 // Same rule as everywhere else here: absent from disk is a fault, not a zero.
2577 let (_dir, query) = empty();
2578 let missing = RepoName::new("gone").expect("valid repository name");
2579
2580 assert!(
2581 query
2582 .count_commits(&handle(), &missing, &rev("main"))
2583 .await
2584 .is_err()
2585 );
2586 }
2587
2588 // --- latest_tag ---------------------------------------------------------------
2589
2590 /// The populated repository with two annotated tags whose dates disagree with their
2591 /// names, so a test can tell "newest" from "last alphabetically".
2592 fn with_dated_tags() -> (TempDir, DiskGitQuery) {
2593 let (dir, query) = populated();
2594 let repo = query.repo_path(&handle(), &repo_name());
2595 let work = dir.path().join("work");
2596 let target = repo.to_str().expect("utf-8 fixture path").to_owned();
2597
2598 git(&work, FIRST_COMMIT, &["tag", "-a", "v1.0", "-m", "first"]);
2599 // Made later but named lower: sorting by name would pick `v1.0`.
2600 git(
2601 &work,
2602 THIRD_COMMIT,
2603 &["tag", "-a", "v0.9", "-m", "backport"],
2604 );
2605 git(&work, THIRD_COMMIT, &["push", "--quiet", &target, "--tags"]);
2606
2607 (dir, query)
2608 }
2609
2610 #[tokio::test]
2611 async fn the_latest_tag_is_the_newest_one_not_the_last_one_alphabetically() {
2612 let (_dir, query) = with_dated_tags();
2613
2614 let tag = query
2615 .latest_tag(&handle(), &repo_name())
2616 .await
2617 .expect("should read")
2618 .expect("a tag");
2619
2620 assert_eq!(tag.name.as_str(), "v0.9");
2621 assert_eq!(tag.created_at, unix_time(THIRD_COMMIT));
2622 }
2623
2624 #[tokio::test]
2625 async fn a_lightweight_tag_is_dated_by_the_commit_it_points_at() {
2626 // It has no date of its own, and `creatordate` is what fills that in.
2627 let (dir, query) = populated();
2628 let repo = query.repo_path(&handle(), &repo_name());
2629 let work = dir.path().join("work");
2630 let target = repo.to_str().expect("utf-8 fixture path").to_owned();
2631
2632 git(&work, THIRD_COMMIT, &["tag", "v1.0"]);
2633 git(&work, THIRD_COMMIT, &["push", "--quiet", &target, "--tags"]);
2634
2635 let tag = query
2636 .latest_tag(&handle(), &repo_name())
2637 .await
2638 .expect("should read")
2639 .expect("a tag");
2640
2641 assert_eq!(tag.name.as_str(), "v1.0");
2642 assert_eq!(tag.created_at, unix_time(THIRD_COMMIT));
2643 }
2644
2645 #[tokio::test]
2646 async fn a_repository_with_no_tags_has_no_latest_tag() {
2647 let (_dir, query) = populated();
2648 assert_eq!(
2649 query
2650 .latest_tag(&handle(), &repo_name())
2651 .await
2652 .expect("should read"),
2653 None
2654 );
2655
2656 let (_dir, empty_query) = empty();
2657 assert_eq!(
2658 empty_query
2659 .latest_tag(&handle(), &repo_name())
2660 .await
2661 .expect("should read"),
2662 None
2663 );
2664 }
2665
2666 #[test]
2667 fn a_tag_record_is_parsed_past_the_trailing_newline() {
2668 // `for-each-ref` ends every record with a newline the format cannot suppress,
2669 // exactly as it does for `parse_refs`.
2670 let tag = parse_latest_tag(b"refs/tags/v1.0\x001700000000\x00\n").expect("a tag");
2671
2672 assert_eq!(tag.name.as_str(), "v1.0");
2673 assert_eq!(tag.created_at, unix_time(1_700_000_000));
2674 }
2675
2676 #[test]
2677 fn nothing_is_parsed_from_an_empty_tag_listing() {
2678 assert_eq!(parse_latest_tag(b""), None);
2679 // A ref outside the tags namespace is not a tag, whatever asked for it.
2680 assert_eq!(
2681 parse_latest_tag(b"refs/heads/main\x001700000000\x00\n"),
2682 None
2683 );
2684 }
2685
2686 // --- branches and tags ---------------------------------------------------------
2687
2688 /// The populated repository with two more branches, each left at an older commit so
2689 /// the three tips carry three different dates — otherwise "newest first" is not
2690 /// something a test can see.
2691 fn with_branches() -> (TempDir, DiskGitQuery) {
2692 let (dir, query) = populated();
2693 let repo = query.repo_path(&handle(), &repo_name());
2694 let work = dir.path().join("work");
2695 let target = repo.to_str().expect("utf-8 fixture path").to_owned();
2696
2697 git(&work, THIRD_COMMIT, &["branch", "stale", "main~2"]);
2698 // A slash in the name, because that is the case the `/-/` separator exists for.
2699 git(&work, THIRD_COMMIT, &["branch", "feature/login", "main~1"]);
2700 git(
2701 &work,
2702 THIRD_COMMIT,
2703 &["push", "--quiet", &target, "stale", "feature/login"],
2704 );
2705
2706 (dir, query)
2707 }
2708
2709 /// The populated repository with one lightweight tag and two annotated ones, made
2710 /// on three different dates so ordering and the annotated/lightweight split can be
2711 /// asserted together.
2712 fn with_mixed_tags() -> (TempDir, DiskGitQuery) {
2713 let (dir, query) = populated();
2714 let repo = query.repo_path(&handle(), &repo_name());
2715 let work = dir.path().join("work");
2716 let target = repo.to_str().expect("utf-8 fixture path").to_owned();
2717
2718 // Lightweight: no object of its own, so its date is the commit's.
2719 git(&work, FIRST_COMMIT, &["tag", "v0.5", "main~2"]);
2720 git(
2721 &work,
2722 SECOND_COMMIT,
2723 &["tag", "-a", "v1.0", "-m", "first release"],
2724 );
2725 git(
2726 &work,
2727 THIRD_COMMIT,
2728 &["tag", "-a", "v2.0", "-m", "second release\n\nnotes below"],
2729 );
2730 git(&work, THIRD_COMMIT, &["push", "--quiet", &target, "--tags"]);
2731
2732 (dir, query)
2733 }
2734
2735 #[tokio::test]
2736 async fn branches_are_newest_first_with_the_default_marked() {
2737 let (_dir, query) = with_branches();
2738
2739 let rows = query
2740 .branches(&handle(), &repo_name())
2741 .await
2742 .expect("should read");
2743
2744 assert_eq!(
2745 rows.iter().map(|row| row.name.as_str()).collect::<Vec<_>>(),
2746 vec!["main", "feature/login", "stale"]
2747 );
2748 // `%(HEAD)` marks exactly one branch, and it is the one a bare repository's
2749 // HEAD names — which is what the page pins to the top.
2750 assert_eq!(
2751 rows.iter()
2752 .filter(|row| row.is_default)
2753 .map(|row| row.name.as_str())
2754 .collect::<Vec<_>>(),
2755 vec!["main"]
2756 );
2757 }
2758
2759 #[tokio::test]
2760 async fn a_branch_row_carries_its_tip_commit() {
2761 let (_dir, query) = with_branches();
2762
2763 let rows = query
2764 .branches(&handle(), &repo_name())
2765 .await
2766 .expect("should read");
2767
2768 let main = rows.first().expect("main is first");
2769
2770 // The subject only, from a message whose body would leak into it if the format
2771 // were read line-wise.
2772 assert_eq!(main.summary, "third: 'quotes', \"doubles\" | pipes");
2773 assert_eq!(main.committed_at, unix_time(THIRD_COMMIT));
2774 assert_eq!(main.commit.as_str().len(), 40);
2775
2776 let stale = rows.last().expect("stale is last");
2777 assert_eq!(stale.summary, "first");
2778 assert_eq!(stale.committed_at, unix_time(FIRST_COMMIT));
2779 }
2780
2781 #[tokio::test]
2782 async fn an_empty_repository_has_no_branches() {
2783 // The same answer `list_refs` gives, and for the same reason: nothing pushed
2784 // yet is not a failure. It is also how the page knows to show the push snippet.
2785 let (_dir, query) = empty();
2786
2787 assert_eq!(
2788 query
2789 .branches(&handle(), &repo_name())
2790 .await
2791 .expect("should read"),
2792 Vec::new()
2793 );
2794 }
2795
2796 #[tokio::test]
2797 async fn tags_are_newest_first_and_only_annotated_ones_carry_a_message() {
2798 let (_dir, query) = with_mixed_tags();
2799
2800 let rows = query
2801 .tags(&handle(), &repo_name())
2802 .await
2803 .expect("should read");
2804
2805 assert_eq!(
2806 rows.iter().map(|row| row.name.as_str()).collect::<Vec<_>>(),
2807 vec!["v2.0", "v1.0", "v0.5"]
2808 );
2809
2810 let newest = &rows[0];
2811 assert!(newest.annotated);
2812 // The subject of the tag's own message, not its body.
2813 assert_eq!(newest.message.as_deref(), Some("second release"));
2814 assert_eq!(newest.created_at, unix_time(THIRD_COMMIT));
2815
2816 let lightweight = &rows[2];
2817 assert!(!lightweight.annotated);
2818 // A lightweight tag has no message of its own; the commit's subject is the
2819 // commit's, and reporting it would invent one.
2820 assert_eq!(lightweight.message, None);
2821 assert_eq!(lightweight.created_at, unix_time(FIRST_COMMIT));
2822 }
2823
2824 #[tokio::test]
2825 async fn an_annotated_tag_reports_the_commit_it_peels_to() {
2826 // Its `objectname` is the tag object, which is not what a visitor browses.
2827 let (_dir, query) = with_mixed_tags();
2828
2829 let tip = query
2830 .branches(&handle(), &repo_name())
2831 .await
2832 .expect("should read")
2833 .into_iter()
2834 .find(|row| row.name.as_str() == "main")
2835 .expect("main");
2836
2837 let annotated = query
2838 .tags(&handle(), &repo_name())
2839 .await
2840 .expect("should read")
2841 .into_iter()
2842 .find(|row| row.name.as_str() == "v1.0")
2843 .expect("v1.0");
2844
2845 assert_eq!(annotated.commit, tip.commit);
2846 }
2847
2848 #[tokio::test]
2849 async fn a_repository_with_no_tags_lists_none() {
2850 let (_dir, query) = populated();
2851 assert_eq!(
2852 query
2853 .tags(&handle(), &repo_name())
2854 .await
2855 .expect("should read"),
2856 Vec::new()
2857 );
2858
2859 let (_dir, empty_query) = empty();
2860 assert_eq!(
2861 empty_query
2862 .tags(&handle(), &repo_name())
2863 .await
2864 .expect("should read"),
2865 Vec::new()
2866 );
2867 }
2868
2869 #[tokio::test]
2870 async fn listing_rows_of_a_repository_that_is_not_on_disk_is_an_error() {
2871 let (_dir, query) = empty();
2872 let missing = RepoName::new("never-created").expect("valid repository name");
2873
2874 assert!(query.branches(&handle(), &missing).await.is_err());
2875 assert!(query.tags(&handle(), &missing).await.is_err());
2876 }
2877
2878 #[test]
2879 fn branch_records_survive_the_newline_git_puts_between_them() {
2880 let rows = parse_branches(
2881 b"refs/heads/main\x00*\x00aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\x001700000000\x00first\x00\nrefs/heads/side\x00 \x00bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\x001700000100\x00second\x00\n",
2882 )
2883 .expect("should parse");
2884
2885 assert_eq!(rows.len(), 2);
2886 assert!(rows[0].is_default);
2887 assert_eq!(rows[0].summary, "first");
2888 // The newline in front of `refs/heads/side` is git's record separator, not part
2889 // of the name.
2890 assert_eq!(rows[1].name.as_str(), "side");
2891 assert!(!rows[1].is_default);
2892 assert_eq!(rows[1].committed_at, unix_time(1_700_000_100));
2893 }
2894
2895 #[test]
2896 fn a_lightweight_tags_empty_peel_does_not_shift_the_fields_after_it() {
2897 // The reason `ref_fields` keeps empty fields: filtering them would read this
2898 // record's date as its commit id.
2899 let rows = parse_tags(
2900 b"refs/tags/v1.0\x00commit\x00aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\x00\x001700000000\x00a commit subject\x00\n",
2901 )
2902 .expect("should parse");
2903
2904 assert_eq!(rows.len(), 1);
2905 assert_eq!(rows[0].name.as_str(), "v1.0");
2906 assert_eq!(rows[0].commit.as_str(), "a".repeat(40));
2907 assert!(!rows[0].annotated);
2908 assert_eq!(rows[0].message, None);
2909 assert_eq!(rows[0].created_at, unix_time(1_700_000_000));
2910 }
2911
2912 #[test]
2913 fn nothing_is_parsed_from_an_empty_row_listing() {
2914 assert_eq!(parse_branches(b"").expect("should parse"), Vec::new());
2915 assert_eq!(parse_tags(b"").expect("should parse"), Vec::new());
2916 }
2917
2918 #[test]
2919 fn a_record_with_the_wrong_number_of_fields_is_a_fault() {
2920 // Skipping a ref Steid cannot link to is right; misreading git's output is not.
2921 assert!(parse_branches(b"refs/heads/main\x00*\x00\n").is_err());
2922 }
2923
2924 // --- helpers ------------------------------------------------------------------
2925
2926 #[tokio::test]
2927 async fn repo_path_lands_under_the_data_directory() {
2928 let query = DiskGitQuery::new("/data");
2929
2930 assert_eq!(
2931 query.repo_path(&handle(), &repo_name()),
2932 PathBuf::from("/data/jamesgill/steid.git")
2933 );
2934 }
2935
2936 #[test]
2937 fn a_pre_epoch_commit_time_does_not_panic() {
2938 // git will hand back a negative `%ct` for an imported history, and
2939 // `UNIX_EPOCH + Duration` cannot represent it.
2940 assert!(unix_time(-1) < UNIX_EPOCH);
2941 assert_eq!(unix_time(0), UNIX_EPOCH);
2942 }
2943
2944 #[tokio::test]
2945 async fn a_read_that_exceeds_its_limit_is_a_timeout_not_a_fault() {
2946 let (_dir, repo) = fixture_repo_for_timeout().await;
2947 let error = run_within(&repo, ["rev-parse", "HEAD"], Duration::ZERO)
2948 .await
2949 .expect_err("a zero limit cannot be met");
2950 assert!(error.is_timeout(), "{error}");
2951 }
2952
2953 /// A bare repository with nothing in it: `rev-parse` failing is not the point, the
2954 /// process being cut off before it can answer is.
2955 async fn fixture_repo_for_timeout() -> (TempDir, std::path::PathBuf) {
2956 let dir = TempDir::new().unwrap();
2957 let repo = dir.path().join("t.git");
2958 let status = git_command()
2959 .args(["init", "--bare", "-q"])
2960 .arg(&repo)
2961 .status()
2962 .await
2963 .unwrap();
2964 assert!(status.success());
2965 (dir, repo)
2966 }
2967
2968 // --- commits, diffs and comparisons ----------------------------------------
2969
2970 /// A repository with the shapes a diff parser has to survive: a rename, a binary
2971 /// file, a file added, a file deleted — plus a second branch and an unrelated
2972 /// history, which is what compare needs.
2973 fn with_history() -> (TempDir, DiskGitQuery) {
2974 let (dir, query) = empty();
2975 let repo = query.repo_path(&handle(), &repo_name());
2976 let work = dir.path().join("work");
2977
2978 std::fs::create_dir_all(work.join("src")).expect("create work tree");
2979 git(&work, FIRST_COMMIT, &["init", "--quiet", "-b", "main"]);
2980
2981 std::fs::write(work.join("src/a.txt"), b"aaa\nbbb\nccc\nddd\neee\n").expect("write");
2982 std::fs::write(work.join("gone.txt"), b"going\n").expect("write");
2983 std::fs::write(work.join("logo.bin"), BINARY).expect("write");
2984 git(&work, FIRST_COMMIT, &["add", "-A"]);
2985 git(&work, FIRST_COMMIT, &["commit", "--quiet", "-m", "first"]);
2986
2987 // A rename git will only find with `-M`: the content is 83% the same.
2988 std::fs::rename(work.join("src/a.txt"), work.join("src/b.txt")).expect("rename");
2989 std::fs::write(work.join("src/b.txt"), b"aaa\nbbb\nccc\nddd\neee\nfff\n").expect("write");
2990 std::fs::remove_file(work.join("gone.txt")).expect("remove");
2991 std::fs::write(work.join("logo.bin"), [0x00, 0x02, 0xff]).expect("write");
2992 std::fs::write(work.join("new.txt"), b"new\n").expect("write");
2993 git(&work, SECOND_COMMIT, &["add", "-A"]);
2994 git(
2995 &work,
2996 SECOND_COMMIT,
2997 &["commit", "--quiet", "-m", "second\n\nwhy it was done"],
2998 );
2999
3000 // A branch ahead of main, for compare.
3001 git(&work, THIRD_COMMIT, &["checkout", "--quiet", "-b", "next"]);
3002 std::fs::write(work.join("new.txt"), b"new\nand more\n").expect("write");
3003 git(&work, THIRD_COMMIT, &["add", "-A"]);
3004 git(&work, THIRD_COMMIT, &["commit", "--quiet", "-m", "third"]);
3005
3006 // A history sharing no ancestor with either, which a compare page must be able
3007 // to report rather than fail on.
3008 git(
3009 &work,
3010 THIRD_COMMIT,
3011 &["checkout", "--quiet", "--orphan", "unrelated"],
3012 );
3013 git(&work, THIRD_COMMIT, &["rm", "-rq", "--cached", "."]);
3014 std::fs::write(work.join("z.txt"), b"z\n").expect("write");
3015 git(&work, THIRD_COMMIT, &["add", "z.txt"]);
3016 git(
3017 &work,
3018 THIRD_COMMIT,
3019 &["commit", "--quiet", "-m", "unrelated"],
3020 );
3021
3022 git(
3023 &work,
3024 THIRD_COMMIT,
3025 &[
3026 "push",
3027 "--quiet",
3028 repo.to_str().expect("utf-8 fixture path"),
3029 "main",
3030 "next",
3031 "unrelated",
3032 ],
3033 );
3034
3035 (dir, query)
3036 }
3037
3038 /// The commit a revision names, for a test that needs the id rather than the name.
3039 async fn commit_id(query: &DiskGitQuery, name: &str) -> ObjectId {
3040 query
3041 .resolve(&handle(), &repo_name(), &rev(name))
3042 .await
3043 .expect("should resolve")
3044 .expect("a commit")
3045 }
3046
3047 #[tokio::test]
3048 async fn a_commit_carries_its_message_its_people_and_its_parent() {
3049 let (_dir, query) = with_history();
3050
3051 let commit = query
3052 .commit(&handle(), &repo_name(), &rev("main"))
3053 .await
3054 .expect("should read")
3055 .expect("a commit");
3056
3057 assert_eq!(commit.summary, "second");
3058 // The body is everything after the blank line, and the trailing newline git
3059 // adds to the record is not part of it.
3060 assert_eq!(commit.body, "why it was done");
3061 assert_eq!(commit.author_name, "Ada Lovelace");
3062 assert_eq!(commit.author_email, "ada@example.com");
3063 assert_eq!(commit.committed_at, unix_time(SECOND_COMMIT));
3064 assert_eq!(commit.parents.len(), 1);
3065 assert!(!commit.is_root());
3066 assert!(!commit.has_distinct_committer());
3067 }
3068
3069 #[tokio::test]
3070 async fn a_first_commit_has_no_parent() {
3071 let (_dir, query) = with_history();
3072
3073 let head = query
3074 .commit(&handle(), &repo_name(), &rev("main"))
3075 .await
3076 .expect("should read")
3077 .expect("a commit");
3078 let parent = RefName::from_trusted(head.parents[0].as_str());
3079
3080 let root = query
3081 .commit(&handle(), &repo_name(), &parent)
3082 .await
3083 .expect("should read")
3084 .expect("a commit");
3085
3086 assert_eq!(root.summary, "first");
3087 assert!(root.is_root());
3088 }
3089
3090 #[tokio::test]
3091 async fn an_abbreviated_id_names_the_same_commit_as_the_branch() {
3092 // What a URL carries when someone clicks a shortened sha in the log.
3093 let (_dir, query) = with_history();
3094
3095 let head = query
3096 .commit(&handle(), &repo_name(), &rev("main"))
3097 .await
3098 .expect("should read")
3099 .expect("a commit");
3100
3101 let short = query
3102 .commit(
3103 &handle(),
3104 &repo_name(),
3105 &RefName::from_trusted(head.id.short()),
3106 )
3107 .await
3108 .expect("should read")
3109 .expect("a commit");
3110
3111 assert_eq!(short.id, head.id);
3112 }
3113
3114 #[tokio::test]
3115 async fn a_revision_that_names_no_commit_has_none() {
3116 let (_dir, query) = with_history();
3117
3118 assert!(
3119 query
3120 .commit(&handle(), &repo_name(), &rev("nope"))
3121 .await
3122 .expect("should read")
3123 .is_none()
3124 );
3125 }
3126
3127 #[tokio::test]
3128 async fn a_diff_carries_its_counts_before_its_patch() {
3129 let (_dir, query) = with_history();
3130 let head = query
3131 .commit(&handle(), &repo_name(), &rev("main"))
3132 .await
3133 .expect("should read")
3134 .expect("a commit");
3135
3136 let raw = query
3137 .diff(
3138 &handle(),
3139 &repo_name(),
3140 head.parents.first(),
3141 &head.id,
3142 1024 * 1024,
3143 )
3144 .await
3145 .expect("should diff");
3146
3147 let numstat = String::from_utf8_lossy(&raw.numstat);
3148 let patch = String::from_utf8_lossy(&raw.patch);
3149
3150 assert!(!raw.truncated);
3151 // Four files: the rename, the deletion, the binary, and the addition.
3152 assert_eq!(numstat.lines().filter(|line| !line.is_empty()).count(), 4);
3153 // The rename is one entry with both names, which is what `-M` buys.
3154 assert!(
3155 numstat.contains("src/{a.txt => b.txt}"),
3156 "expected a rename in {numstat:?}"
3157 );
3158 // A binary file has no counts, which is git's `-` rather than a zero.
3159 assert!(numstat.contains("-\t-\tlogo.bin"), "{numstat:?}");
3160
3161 // And the patch is the patch, starting where the counts stop.
3162 assert!(
3163 patch.starts_with("diff --git "),
3164 "{:?}",
3165 &patch[..60.min(patch.len())]
3166 );
3167 assert!(patch.contains("rename from src/a.txt"));
3168 assert!(patch.contains("Binary files "));
3169 }
3170
3171 #[tokio::test]
3172 async fn a_root_commit_is_diffed_against_nothing_rather_than_skipped() {
3173 let (_dir, query) = with_history();
3174 let head = query
3175 .commit(&handle(), &repo_name(), &rev("main"))
3176 .await
3177 .expect("should read")
3178 .expect("a commit");
3179 let root = query
3180 .commit(
3181 &handle(),
3182 &repo_name(),
3183 &RefName::from_trusted(head.parents[0].as_str()),
3184 )
3185 .await
3186 .expect("should read")
3187 .expect("a commit");
3188
3189 let raw = query
3190 .diff(&handle(), &repo_name(), None, &root.id, 1024 * 1024)
3191 .await
3192 .expect("should diff");
3193
3194 // Without `--root` this would be empty, and the first commit in a repository
3195 // would show as having changed nothing.
3196 assert!(String::from_utf8_lossy(&raw.numstat).contains("src/a.txt"));
3197 assert!(String::from_utf8_lossy(&raw.patch).contains("new file mode"));
3198 }
3199
3200 #[tokio::test]
3201 async fn a_diff_over_the_cap_is_cut_short_with_its_counts_intact() {
3202 // The reason the counts are asked for in the same run: they are written first,
3203 // so they survive a patch that does not fit.
3204 let (_dir, query) = with_history();
3205 let head = query
3206 .commit(&handle(), &repo_name(), &rev("main"))
3207 .await
3208 .expect("should read")
3209 .expect("a commit");
3210
3211 let raw = query
3212 .diff(&handle(), &repo_name(), head.parents.first(), &head.id, 90)
3213 .await
3214 .expect("should diff");
3215
3216 assert!(raw.truncated);
3217 assert_eq!(raw.numstat.len() + raw.patch.len(), 90);
3218 assert!(String::from_utf8_lossy(&raw.numstat).contains("src/{a.txt => b.txt}"));
3219 }
3220
3221 #[tokio::test]
3222 async fn a_merge_base_is_the_point_two_branches_share() {
3223 let (_dir, query) = with_history();
3224 let main = commit_id(&query, "main").await;
3225 let next = commit_id(&query, "next").await;
3226
3227 let base = query
3228 .merge_base(&handle(), &repo_name(), &main, &next)
3229 .await
3230 .expect("should read")
3231 .expect("a merge base");
3232
3233 // `next` branched off the tip of `main`, so that tip is the base.
3234 assert_eq!(base, main);
3235 }
3236
3237 #[tokio::test]
3238 async fn two_histories_with_no_common_ancestor_have_no_merge_base() {
3239 // git says this with exit 1 and no output — the one documented not-found exit
3240 // this module tolerates. It must be an answer, not a 500.
3241 let (_dir, query) = with_history();
3242 let main = commit_id(&query, "main").await;
3243 let unrelated = commit_id(&query, "unrelated").await;
3244
3245 assert!(
3246 query
3247 .merge_base(&handle(), &repo_name(), &main, &unrelated)
3248 .await
3249 .expect("should read")
3250 .is_none()
3251 );
3252 }
3253
3254 #[tokio::test]
3255 async fn a_range_lists_only_what_the_head_adds() {
3256 let (_dir, query) = with_history();
3257 let main = commit_id(&query, "main").await;
3258 let next = commit_id(&query, "next").await;
3259
3260 let commits = query
3261 .log_between(&handle(), &repo_name(), Some(&main), &next, 50)
3262 .await
3263 .expect("should read");
3264
3265 assert_eq!(
3266 commits
3267 .iter()
3268 .map(|commit| commit.summary.as_str())
3269 .collect::<Vec<_>>(),
3270 vec!["third"]
3271 );
3272
3273 // The other way round adds nothing: `main` is contained in `next`.
3274 assert!(
3275 query
3276 .log_between(&handle(), &repo_name(), Some(&next), &main, 50)
3277 .await
3278 .expect("should read")
3279 .is_empty()
3280 );
3281 }
3282
3283 #[test]
3284 fn the_counts_and_the_patch_are_split_at_the_first_file_header() {
3285 let (numstat, patch) = split_numstat(b"1\t1\ta.txt\n\ndiff --git a/a.txt b/a.txt\n@@\n");
3286
3287 assert_eq!(numstat, b"1\t1\ta.txt\n\n");
3288 assert!(patch.starts_with(b"diff --git "));
3289 }
3290
3291 #[test]
3292 fn a_diff_with_nothing_in_it_splits_into_two_empties() {
3293 let (numstat, patch) = split_numstat(b"");
3294
3295 assert!(numstat.is_empty());
3296 assert!(patch.is_empty());
3297 }
3298
3299 // --- blame ----------------------------------------------------------------------
3300
3301 /// A repository with one file rewritten across three commits, so a blame of it has
3302 /// several runs rather than one.
3303 ///
3304 /// Its own fixture rather than another file in [`populated`], because the shape
3305 /// blame needs — the same file touched repeatedly, at known times — is exactly what
3306 /// the other queries do not want.
3307 fn blamed() -> (TempDir, DiskGitQuery) {
3308 let (dir, query) = empty();
3309 let repo = query.repo_path(&handle(), &repo_name());
3310 let work = dir.path().join("blame-work");
3311
3312 std::fs::create_dir_all(work.join("docs")).expect("create work tree");
3313 git(&work, FIRST_COMMIT, &["init", "--quiet", "-b", "main"]);
3314
3315 std::fs::write(work.join("notes.md"), b"one\ntwo\nthree\n").expect("write");
3316 std::fs::write(work.join("docs/why.md"), b"because\n").expect("write");
3317 std::fs::write(work.join("logo.png"), BINARY).expect("write");
3318 git(&work, FIRST_COMMIT, &["add", "-A"]);
3319 git(&work, FIRST_COMMIT, &["commit", "--quiet", "-m", "first"]);
3320
3321 std::fs::write(work.join("notes.md"), b"one\nTWO\nthree\n").expect("write");
3322 git(&work, SECOND_COMMIT, &["add", "-A"]);
3323 git(&work, SECOND_COMMIT, &["commit", "--quiet", "-m", "second"]);
3324
3325 std::fs::write(work.join("notes.md"), b"one\nTWO\nthree\nfour\n").expect("write");
3326 git(&work, THIRD_COMMIT, &["add", "-A"]);
3327 git(&work, THIRD_COMMIT, &["commit", "--quiet", "-m", "third"]);
3328
3329 git(
3330 &work,
3331 THIRD_COMMIT,
3332 &[
3333 "push",
3334 "--quiet",
3335 repo.to_str().expect("utf-8 fixture path"),
3336 "main",
3337 ],
3338 );
3339
3340 (dir, query)
3341 }
3342
3343 #[tokio::test]
3344 async fn blame_splits_a_file_into_runs_by_the_commit_that_wrote_them() {
3345 let (_dir, query) = blamed();
3346
3347 let blame = query
3348 .blame(&handle(), &repo_name(), &rev("main"), &path("notes.md"))
3349 .await
3350 .expect("should read")
3351 .expect("a blameable file");
3352
3353 // Lines 1 and 3 are the first commit's but are not adjacent, so four runs.
3354 let shape: Vec<(usize, Vec<String>, String)> = blame
3355 .groups
3356 .iter()
3357 .map(|group| {
3358 (
3359 group.start_line,
3360 group.lines.clone(),
3361 group.commit.summary.clone(),
3362 )
3363 })
3364 .collect();
3365
3366 assert_eq!(
3367 shape,
3368 vec![
3369 (1, vec!["one".to_owned()], "first".to_owned()),
3370 (2, vec!["TWO".to_owned()], "second".to_owned()),
3371 (3, vec!["three".to_owned()], "first".to_owned()),
3372 (4, vec!["four".to_owned()], "third".to_owned()),
3373 ]
3374 );
3375 assert_eq!(blame.line_count(), 4);
3376 }
3377
3378 #[tokio::test]
3379 async fn blame_carries_what_a_page_shows_about_each_commit() {
3380 let (_dir, query) = blamed();
3381
3382 let blame = query
3383 .blame(&handle(), &repo_name(), &rev("main"), &path("notes.md"))
3384 .await
3385 .expect("should read")
3386 .expect("a blameable file");
3387 let newest = &blame.groups[3].commit;
3388
3389 assert_eq!(newest.author_name, "Ada Lovelace");
3390 assert_eq!(newest.authored_at, unix_time(THIRD_COMMIT));
3391 assert_eq!(newest.filename, "notes.md");
3392 // Full ids, so the page can link to a commit without an ambiguous abbreviation.
3393 assert_eq!(newest.id.as_str().len(), 40);
3394 // The oldest run is the faintest tint and the newest the strongest.
3395 assert_eq!(blame.groups[0].age, 0);
3396 assert_eq!(blame.groups[3].age, 4);
3397 }
3398
3399 #[tokio::test]
3400 async fn blame_can_be_asked_by_object_id_as_well_as_by_branch() {
3401 // A blame page reached from a commit link names a sha in its URL.
3402 let (_dir, query) = blamed();
3403 let commit = query
3404 .resolve(&handle(), &repo_name(), &rev("main"))
3405 .await
3406 .expect("should read")
3407 .expect("main resolves");
3408
3409 let blame = query
3410 .blame(
3411 &handle(),
3412 &repo_name(),
3413 &rev(commit.as_str()),
3414 &path("notes.md"),
3415 )
3416 .await
3417 .expect("should read")
3418 .expect("a blameable file");
3419
3420 assert_eq!(blame.groups.len(), 4);
3421 }
3422
3423 #[tokio::test]
3424 async fn there_is_nothing_to_blame_that_is_not_a_file() {
3425 // Every one of these is a fatal error if handed straight to `git blame`, which
3426 // is why the existence check runs first.
3427 let (_dir, query) = blamed();
3428
3429 for (revision, target) in [
3430 ("main", "docs"),
3431 ("main", "nope.md"),
3432 ("no-such-branch", "notes.md"),
3433 ] {
3434 assert_eq!(
3435 query
3436 .blame(&handle(), &repo_name(), &rev(revision), &path(target))
3437 .await
3438 .expect("should read"),
3439 None,
3440 "{revision}:{target} should not blame"
3441 );
3442 }
3443 }
3444
3445 #[tokio::test]
3446 async fn an_empty_repository_blames_nothing() {
3447 let (_dir, query) = empty();
3448
3449 assert_eq!(
3450 query
3451 .blame(&handle(), &repo_name(), &rev("main"), &path("README.md"))
3452 .await
3453 .expect("should read"),
3454 None
3455 );
3456 }
3457}