steid

@jamesgill /

steid/src/infrastructure/git_query.rs
Rust173.4 KBCode·Blame·History·Raw
1//! Reading repository contents through the `git` binary.
2//!
3//! **Object reads go through a kept-alive `git cat-file`** — the pool in
4//! [`cat_file`](super::cat_file), which is stage 2 of the upgrade path in the Milestone
5//! 5 amendment to [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md)
6//! and the third amendment's subject. Existence, blob contents, tree listings and
7//! single commit reads are lines written to a process that is already running;
8//! everything that walks history — `log`, `for-each-ref`, `rev-list`, `merge-base`,
9//! `diff-tree`, `blame`, `grep` — is still one process per question, because a fork is
10//! a rounding error next to the walk it pays for.
11//!
12//! # Telling "not there" from "broken"
13//!
14//! git reports both with a non-zero exit, and at different call sites with *different*
15//! non-zero exits: `rev-parse --verify --quiet` says 1 for an unknown ref but 128 for a
16//! missing repository, while `ls-tree` pointed at a blob says 128 for what is, to a
17//! visitor, a 404. Keying off exit codes therefore either turns a typo'd URL into a 500
18//! or buries a corrupt repository behind a "not found".
19//!
20//! So every existence question here goes through one command that does not use its exit
21//! status to answer: `git cat-file --batch-check` writes `<spec> missing` on stdout and
22//! **stays running** for anything it cannot resolve — an unknown ref, an absent path, a path
23//! traversing through a blob, a submodule's commit that lives in another repository.
24//! That gives a single rule for this whole module:
25//!
26//! **A non-zero exit from git is always an error.** "Not found" is a value read off
27//! stdout, never an exit code. Everything else — git missing from `PATH`, a repository
28//! directory that is gone, an unreadable object store — surfaces as [`GitQueryError`]
29//! carrying git's own words.
30//!
31//! The listing and content commands are only ever reached *after* `--batch-check` has
32//! confirmed the object and its type, and are handed the resolved object id rather than
33//! the user's revision, so their failure modes are genuinely faults.
34//!
35//! **Three commands are exempt**, and only those three: `git grep`, `git merge-base`
36//! and `git merge-tree`, whose exit 1 git's own manual promises as "matched nothing",
37//! "no common ancestor" and "the merge has conflicts". All three go through
38//! [`run_allowing`], which is the only place a non-zero exit is ever accepted, and each
39//! names the status it accepts at the call site.
40
41use std::{
42 collections::HashMap,
43 ffi::OsStr,
44 path::{Path, PathBuf},
45 process::{Output, Stdio},
46 sync::Arc,
47 time::{Duration, SystemTime, UNIX_EPOCH},
48};
49
50use tokio::io::AsyncReadExt;
51
52use crate::{
53 application::{
54 blame::{Blame, parse_blame},
55 port::{Blob, CommitCount, GitQuery, GitQueryError, MergePreview, RawDiff},
56 search::parse_grep_output,
57 },
58 domain::{
59 BranchRow, CommitDetail, CommitEntry, CommitSummary, EntryCommit, EntryKind, GitRef,
60 GrepHit, ObjectId, OrgName, RefKind, RefName, RepoName, RepoPath, TagRow, TagSummary,
61 TreeEntry,
62 },
63 infrastructure::{
64 cat_file::{CatFilePool, ObjectInfo, ObjectKind},
65 git::git_command,
66 merge_cache::MergeCache,
67 },
68};
69
70/// Repository contents, read from bare repositories under a data directory.
71///
72/// The pool is shared, not owned: it holds live `git cat-file` processes, and this
73/// adapter is constructed per request. Built per request the pool would spawn and kill a
74/// process per request — the fork cost back, plus a pool that never pools. See the
75/// Milestone 5 amendment to
76/// [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md), which named
77/// that as the one thing to get right before the first batch adapter existed.
78#[derive(Debug, Clone)]
79pub struct DiskGitQuery {
80 data_dir: PathBuf,
81 pool: Arc<CatFilePool>,
82 /// Merge previews already computed, so a pull request page that is reloaded does not
83 /// re-run `merge-tree` — see [`MergeCache`].
84 merges: Arc<MergeCache>,
85}
86
87impl DiskGitQuery {
88 pub fn new(
89 data_dir: impl Into<PathBuf>,
90 pool: Arc<CatFilePool>,
91 merges: Arc<MergeCache>,
92 ) -> Self {
93 Self {
94 data_dir: data_dir.into(),
95 pool,
96 merges,
97 }
98 }
99
100 /// What a revision resolves to, as a commit.
101 ///
102 /// `^{commit}` peels an annotated tag to what it points at, and refuses a revision
103 /// that names a tree or a blob — a browse page wants a commit, and returning a tree
104 /// id here would fail confusingly two calls later.
105 ///
106 /// The whole [`ObjectInfo`] rather than the id, because a caller that goes on to
107 /// read the commit object needs its size to read it, and asking twice would waste
108 /// the round trip this saves.
109 async fn commit_info(
110 &self,
111 repo: &Path,
112 rev: &RefName,
113 ) -> Result<Option<ObjectInfo>, GitQueryError> {
114 self.pool
115 .info(repo, &format!("{}^{{commit}}", rev.as_str()))
116 .await
117 }
118
119 /// Where a repository lives, matching `DiskGitStorage`'s layout.
120 pub(crate) fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf {
121 self.data_dir
122 .join(handle.as_str())
123 .join(format!("{name}.git"))
124 }
125}
126
127impl GitQuery for DiskGitQuery {
128 async fn default_branch(
129 &self,
130 handle: &OrgName,
131 name: &RepoName,
132 ) -> Result<Option<RefName>, GitQueryError> {
133 let repo = self.repo_path(handle, name);
134
135 // An empty repository's HEAD names a branch that does not exist yet, so
136 // `symbolic-ref` happily answers `main` for a repository with nothing in it.
137 // Whether HEAD *resolves* is the actual question, and it is asked first.
138 let Some(head) = self.pool.info(&repo, "HEAD").await? else {
139 return Ok(None);
140 };
141
142 let branch = run(&repo, [OsStr::new("symbolic-ref"), OsStr::new("HEAD")]).await;
143
144 match branch {
145 Ok(output) => {
146 let full = String::from_utf8_lossy(&output.stdout).trim().to_owned();
147 // `refs/heads/main` rather than `--short`, because `--short` shortens
148 // only as far as is unambiguous and would hand back `heads/main` for a
149 // repository that also has a tag called `main`.
150 let short = full.strip_prefix("refs/heads/").unwrap_or(&full);
151
152 Ok(Some(RefName::from_trusted(short)))
153 }
154 // A detached HEAD is not a state Steid creates, but a repository pushed into
155 // from elsewhere can be in it. The commit is still browsable, so name it
156 // rather than claiming the repository is empty — which is what `Ok(None)`
157 // would mean to a page.
158 Err(_) => Ok(Some(RefName::from_trusted(head.id.as_str()))),
159 }
160 }
161
162 async fn resolve(
163 &self,
164 handle: &OrgName,
165 name: &RepoName,
166 rev: &RefName,
167 ) -> Result<Option<ObjectId>, GitQueryError> {
168 let repo = self.repo_path(handle, name);
169
170 Ok(self.commit_info(&repo, rev).await?.map(|info| info.id))
171 }
172
173 async fn list_tree(
174 &self,
175 handle: &OrgName,
176 name: &RepoName,
177 rev: &RefName,
178 path: &RepoPath,
179 ) -> Result<Option<Vec<TreeEntry>>, GitQueryError> {
180 let repo = self.repo_path(handle, name);
181
182 let Some(info) = self.pool.info(&repo, &tree_spec(rev, path)).await? else {
183 return Ok(None);
184 };
185
186 // A file is not a directory. Asking `ls-tree` anyway is a fatal error, which is
187 // exactly the confusion this check exists to avoid.
188 if info.kind != ObjectKind::Tree {
189 return Ok(None);
190 }
191
192 // The tree object itself, read from the kept-alive `--batch` and parsed here.
193 // `ls-tree --long` used to do both jobs in one process; the object carries no
194 // sizes, so they are asked for separately below — still no fork, and one round
195 // trip for the whole directory rather than one per entry.
196 let mut entries = parse_tree_object(&self.pool.contents(&repo, &info).await?)?;
197
198 // Only what a listing shows a size for. A tree and a submodule have none, and
199 // asking about a submodule's commit would be asking about an object that lives
200 // in a repository Steid cannot see.
201 let sized: Vec<usize> = entries
202 .iter()
203 .enumerate()
204 .filter(|(_, entry)| matches!(entry.kind, EntryKind::Blob | EntryKind::Symlink))
205 .map(|(index, _)| index)
206 .collect();
207
208 let specs: Vec<String> = sized
209 .iter()
210 .map(|index| entries[*index].id.as_str().to_owned())
211 .collect();
212
213 for (index, size) in sized.iter().zip(self.pool.info_many(&repo, &specs).await?) {
214 entries[*index].size = size.map(|size| size.size);
215 }
216
217 Ok(Some(entries))
218 }
219
220 async fn last_commits(
221 &self,
222 handle: &OrgName,
223 name: &RepoName,
224 rev: &RefName,
225 path: &RepoPath,
226 entries: &[String],
227 ) -> Result<HashMap<String, EntryCommit>, GitQueryError> {
228 let repo = self.repo_path(handle, name);
229
230 if entries.is_empty() {
231 return Ok(HashMap::new());
232 }
233
234 // Resolved first, as everywhere here: `git log` is fatal on a revision that
235 // names nothing, and an empty repository has no directory to attribute anyway.
236 let Some(info) = self.commit_info(&repo, rev).await? else {
237 return Ok(HashMap::new());
238 };
239
240 // `-z` for the reason `log` uses it — a path may contain a newline, and the
241 // alternative is git's C-style quoting, which would have to be undone here.
242 // `--name-only` rather than `--name-status`: what changed is not shown, only
243 // that something did.
244 let count = format!("--max-count={LAST_COMMIT_SCAN}");
245
246 let mut args: Vec<&OsStr> = vec![
247 OsStr::new("log"),
248 OsStr::new(LAST_COMMIT_FORMAT),
249 OsStr::new("--name-only"),
250 OsStr::new("-z"),
251 OsStr::new(&count),
252 OsStr::new(info.id.as_str()),
253 ];
254
255 // The pathspec narrows the walk to the directory being listed, which is what
256 // makes the cap generous enough to be useful: 500 commits *that touched this
257 // directory*, not 500 commits of the repository. The root needs none.
258 let prefix = if path.is_root() {
259 String::new()
260 } else {
261 args.push(OsStr::new("--"));
262 args.push(OsStr::new(path.as_str()));
263
264 format!("{}/", path.as_str())
265 };
266
267 let output = run(&repo, args).await?;
268
269 Ok(attribute(&output.stdout, &prefix, entries))
270 }
271
272 async fn read_blob(
273 &self,
274 handle: &OrgName,
275 name: &RepoName,
276 rev: &RefName,
277 path: &RepoPath,
278 max_bytes: u64,
279 ) -> Result<Option<Blob>, GitQueryError> {
280 let repo = self.repo_path(handle, name);
281
282 // The root is a tree, and `{rev}:` is how git spells it — but a caller asking to
283 // read the root is asking for a file that is not there.
284 if path.is_root() {
285 return Ok(None);
286 }
287
288 let Some(info) = self.pool.info(&repo, &tree_spec(rev, path)).await? else {
289 return Ok(None);
290 };
291
292 // Symlinks are blobs whose content is the target path, and are read as such:
293 // showing where a link points is more use than a blank page. Trees and
294 // submodules are not files.
295 if info.kind != ObjectKind::Blob {
296 return Ok(None);
297 }
298
299 // The size comes from the object header, so an oversized file is never read.
300 // Doing this the other way round — read, then measure — is how one URL becomes
301 // an out-of-memory kill.
302 let content = if info.size > max_bytes {
303 None
304 } else {
305 Some(self.pool.contents(&repo, &info).await?)
306 };
307
308 Ok(Some(Blob {
309 id: info.id,
310 size: info.size,
311 content,
312 }))
313 }
314
315 async fn log(
316 &self,
317 handle: &OrgName,
318 name: &RepoName,
319 rev: &RefName,
320 offset: usize,
321 limit: usize,
322 ) -> Result<Vec<CommitSummary>, GitQueryError> {
323 let repo = self.repo_path(handle, name);
324
325 // `git log` on a repository with no commits is a fatal error, and so is a log of
326 // a branch that does not exist. Resolving first turns both into the empty list
327 // the port's signature promises, without having to read meaning into a stderr
328 // string that is localised and free to change between git versions.
329 let Some(info) = self.commit_info(&repo, rev).await? else {
330 return Ok(Vec::new());
331 };
332
333 // The first commit of a log *is* the revision it was asked about, so the
334 // commonest log of all — the landing page's latest-commit bar — needs no walk
335 // and no process: the commit object read through `--batch` says everything the
336 // bar shows. Everything wider still walks history, which is what `git log` is
337 // for and what a batch process cannot do.
338 if offset == 0 && limit == 1 {
339 let detail = parse_commit_object(&info.id, &self.pool.contents(&repo, &info).await?)?;
340
341 return Ok(vec![CommitSummary {
342 id: detail.id,
343 summary: detail.summary,
344 author_name: detail.author_name,
345 committed_at: detail.committed_at,
346 }]);
347 }
348
349 let commit = info.id;
350
351 if limit == 0 {
352 return Ok(Vec::new());
353 }
354
355 // Every separator is a NUL: `-z` between commits, `%x00` between fields. A
356 // commit message contains newlines as a matter of course, and a name can contain
357 // almost anything, so splitting on lines or whitespace would misread real
358 // history rather than exotic history.
359 // `--skip` rather than a cursor: git's log order interleaves parallel lines of
360 // history by date, so only git can say what the 51st commit is. See the port.
361 let count = format!("--max-count={limit}");
362 let skip = format!("--skip={offset}");
363
364 let output = run(
365 &repo,
366 [
367 OsStr::new("log"),
368 OsStr::new("-z"),
369 OsStr::new(&count),
370 OsStr::new(&skip),
371 OsStr::new(LOG_FORMAT),
372 OsStr::new(commit.as_str()),
373 ],
374 )
375 .await?;
376
377 parse_log(&output.stdout)
378 }
379
380 async fn log_entries(
381 &self,
382 handle: &OrgName,
383 name: &RepoName,
384 rev: &RefName,
385 limit: usize,
386 ) -> Result<Vec<CommitEntry>, GitQueryError> {
387 let repo = self.repo_path(handle, name);
388
389 // Resolved first for [`log`]'s reason: `git log` is fatal on a repository with no
390 // commits and on a branch that is not there, and both are the empty list here.
391 let Some(commit) = self.resolve(handle, name, rev).await? else {
392 return Ok(Vec::new());
393 };
394
395 if limit == 0 {
396 return Ok(Vec::new());
397 }
398
399 let count = format!("--max-count={limit}");
400
401 let output = run(
402 &repo,
403 [
404 OsStr::new("log"),
405 OsStr::new("-z"),
406 OsStr::new(&count),
407 OsStr::new(ENTRY_FORMAT),
408 OsStr::new(commit.as_str()),
409 ],
410 )
411 .await?;
412
413 parse_log_entries(&output.stdout)
414 }
415
416 async fn list_refs(
417 &self,
418 handle: &OrgName,
419 name: &RepoName,
420 ) -> Result<Vec<GitRef>, GitQueryError> {
421 let repo = self.repo_path(handle, name);
422
423 // One fork, ~14ms — see the port's note. `for-each-ref` is asked for both
424 // namespaces at once rather than once each, because the cost here is the
425 // process, not the question.
426 //
427 // Every field separator is a NUL, for the same reason `log` uses one: a tag name
428 // is close to arbitrary text once git's own restrictions are met, and splitting
429 // on whitespace would misread a real name. The patterns are literals, so unlike
430 // a revision from a URL there is nothing here that could be read as a flag.
431 let output = run(
432 &repo,
433 [
434 OsStr::new("for-each-ref"),
435 OsStr::new(REF_FORMAT),
436 OsStr::new("refs/heads/"),
437 OsStr::new("refs/tags/"),
438 ],
439 )
440 .await?;
441
442 Ok(parse_refs(&output.stdout))
443 }
444
445 async fn count_commits(
446 &self,
447 handle: &OrgName,
448 name: &RepoName,
449 rev: &RefName,
450 ) -> Result<u64, GitQueryError> {
451 let repo = self.repo_path(handle, name);
452
453 // Resolved first, for the same reason `log` resolves first: `rev-list` on an
454 // empty repository or an unknown branch is a fatal error, and the port promises
455 // a count rather than a failure. **That makes this two processes, not one** —
456 // the price of keeping the module's rule that a non-zero exit is always a real
457 // fault. Handing the resolved id to `rev-list` also means nothing from a URL
458 // reaches git's revision parser here.
459 let Some(commit) = self.resolve(handle, name, rev).await? else {
460 return Ok(0);
461 };
462
463 let output = run(
464 &repo,
465 [
466 OsStr::new("rev-list"),
467 OsStr::new("--count"),
468 OsStr::new(commit.as_str()),
469 ],
470 )
471 .await?;
472
473 let count = String::from_utf8_lossy(&output.stdout);
474 let count = count.trim();
475
476 count.parse().map_err(|_| {
477 GitQueryError::new(format!(
478 "git counted commits as {count:?}, which is not a number"
479 ))
480 })
481 }
482
483 async fn latest_tag(
484 &self,
485 handle: &OrgName,
486 name: &RepoName,
487 ) -> Result<Option<TagSummary>, GitQueryError> {
488 let repo = self.repo_path(handle, name);
489
490 // `--count=1` after `--sort` is the whole of the work: git does the ordering,
491 // so this is one process regardless of how many tags a repository carries.
492 // Every argument is a literal — nothing from a URL reaches this call.
493 let output = run(
494 &repo,
495 [
496 OsStr::new("for-each-ref"),
497 OsStr::new("--sort=-creatordate"),
498 OsStr::new("--count=1"),
499 OsStr::new(TAG_FORMAT),
500 OsStr::new("refs/tags/"),
501 ],
502 )
503 .await?;
504
505 Ok(parse_latest_tag(&output.stdout))
506 }
507
508 async fn branches(
509 &self,
510 handle: &OrgName,
511 name: &RepoName,
512 ) -> Result<Vec<BranchRow>, GitQueryError> {
513 let repo = self.repo_path(handle, name);
514
515 // One process for the whole branches page. The sort is git's because it is
516 // free there and would otherwise be a second pass in Rust over the same rows,
517 // and `%(HEAD)` is what saves the page a `symbolic-ref` for the default branch.
518 // Every argument is a literal — nothing from a URL reaches this call.
519 let output = run(
520 &repo,
521 [
522 OsStr::new("for-each-ref"),
523 OsStr::new("--sort=-committerdate"),
524 OsStr::new(BRANCH_FORMAT),
525 OsStr::new("refs/heads/"),
526 ],
527 )
528 .await?;
529
530 parse_branches(&output.stdout)
531 }
532
533 async fn tags(&self, handle: &OrgName, name: &RepoName) -> Result<Vec<TagRow>, GitQueryError> {
534 let repo = self.repo_path(handle, name);
535
536 let output = run(
537 &repo,
538 [
539 OsStr::new("for-each-ref"),
540 OsStr::new("--sort=-creatordate"),
541 OsStr::new(TAG_ROW_FORMAT),
542 OsStr::new("refs/tags/"),
543 ],
544 )
545 .await?;
546
547 parse_tags(&output.stdout)
548 }
549
550 async fn grep(
551 &self,
552 handle: &OrgName,
553 name: &RepoName,
554 commit: &ObjectId,
555 query: &str,
556 limit: usize,
557 ) -> Result<Vec<GrepHit>, GitQueryError> {
558 let repo = self.repo_path(handle, name);
559
560 // **One of the two commands here whose exit status is an answer** — the other
561 // is `merge_base`. `git grep` exits 1 when it found nothing, which is not a
562 // failure. Everything else in this module keeps the rule that a non-zero exit
563 // is a fault; the exception is spelled out in the call rather than hidden in
564 // the helper.
565 //
566 // `-F` fixed strings, `-I` skips binary files, `-n --column` locate the match,
567 // and `-z` makes the output parseable — see `parse_grep_output`. The query is
568 // passed after `-e`, so a query starting with `-` is a search rather than a
569 // flag, and the commit is one git resolved rather than anything from a URL.
570 let output = run_allowing(
571 &repo,
572 [
573 OsStr::new("grep"),
574 OsStr::new("-I"),
575 OsStr::new("-n"),
576 OsStr::new("-z"),
577 OsStr::new("-F"),
578 OsStr::new("--column"),
579 OsStr::new("--no-color"),
580 OsStr::new("-e"),
581 OsStr::new(query),
582 OsStr::new(commit.as_str()),
583 OsStr::new("--"),
584 ],
585 &[NO_MATCHES],
586 )
587 .await?;
588
589 Ok(parse_grep_output(&output.stdout, commit, limit))
590 }
591
592 async fn commit(
593 &self,
594 handle: &OrgName,
595 name: &RepoName,
596 rev: &RefName,
597 ) -> Result<Option<CommitDetail>, GitQueryError> {
598 let repo = self.repo_path(handle, name);
599
600 // Resolved first, as everywhere else in this module: the `^{commit}` peel refuses
601 // a tree or a blob and follows an annotated tag to what it points at, so what is
602 // read below is known to be a commit.
603 //
604 // **No `git log` any more.** A one-commit log was two processes — resolve, then
605 // format — and is now two lines written to processes that are already running:
606 // the peel on `--batch-check`, the object itself on `--batch`. Formatting is
607 // [`parse_commit_object`]'s job rather than git's.
608 let Some(info) = self.commit_info(&repo, rev).await? else {
609 return Ok(None);
610 };
611
612 parse_commit_object(&info.id, &self.pool.contents(&repo, &info).await?).map(Some)
613 }
614
615 async fn diff(
616 &self,
617 handle: &OrgName,
618 name: &RepoName,
619 base: Option<&ObjectId>,
620 head: &ObjectId,
621 max_bytes: u64,
622 ) -> Result<RawDiff, GitQueryError> {
623 let repo = self.repo_path(handle, name);
624
625 // `diff-tree` rather than `diff`, for both shapes: it is the plumbing command,
626 // it takes tree-ish arguments rather than revision expressions, and it does not
627 // consult a working tree that a bare repository does not have.
628 //
629 // The flags, each load-bearing:
630 // --no-commit-id `-p` would otherwise print the commit's id as a first line
631 // -p the patch itself
632 // -M rename detection, so a moved file is one entry, not two
633 // --numstat the per-file counts, written *before* the patch — which is
634 // what makes them survive the byte cap below
635 // --no-color the caller renders; git must not send escape sequences
636 // --root a first commit is diffed against nothing rather than
637 // skipped, which is the only way to see what it introduced
638 let mut args: Vec<&OsStr> = vec![
639 OsStr::new("diff-tree"),
640 OsStr::new("--no-commit-id"),
641 OsStr::new("-p"),
642 OsStr::new("-M"),
643 OsStr::new("--numstat"),
644 OsStr::new("--no-color"),
645 ];
646
647 match base {
648 Some(base) => {
649 args.push(OsStr::new(base.as_str()));
650 }
651 None => args.push(OsStr::new("--root")),
652 }
653
654 args.push(OsStr::new(head.as_str()));
655
656 let (stdout, truncated) = run_capped(&repo, args, max_bytes).await?;
657 let (numstat, patch) = split_numstat(&stdout);
658
659 Ok(RawDiff {
660 numstat: numstat.to_vec(),
661 patch: patch.to_vec(),
662 truncated,
663 })
664 }
665
666 async fn merge_base(
667 &self,
668 handle: &OrgName,
669 name: &RepoName,
670 base: &ObjectId,
671 head: &ObjectId,
672 ) -> Result<Option<ObjectId>, GitQueryError> {
673 let repo = self.repo_path(handle, name);
674
675 // **The other exception to this module's rule that a non-zero exit is a
676 // fault**, `grep` being the first. `git merge-base` documents exit 1 as "no
677 // merge base found" and reserves 128 for real errors, so the two are
678 // distinguishable here in a way they are not for `rev-parse` — which is why the
679 // rule exists at all. Two histories with no common ancestor is a thing a compare
680 // page must be able to say, and the arguments are resolved object ids, so there
681 // is nothing else exit 1 can mean.
682 let output = run_allowing(
683 &repo,
684 [
685 OsStr::new("merge-base"),
686 OsStr::new(base.as_str()),
687 OsStr::new(head.as_str()),
688 ],
689 &[NO_COMMON_ANCESTOR],
690 )
691 .await?;
692
693 let id = String::from_utf8_lossy(&output.stdout);
694 let id = id.trim();
695
696 if id.is_empty() {
697 return Ok(None);
698 }
699
700 Ok(Some(ObjectId::new(id).map_err(|error| {
701 GitQueryError::new(format!("git named a bad merge base: {error}"))
702 })?))
703 }
704
705 async fn log_between(
706 &self,
707 handle: &OrgName,
708 name: &RepoName,
709 base: Option<&ObjectId>,
710 head: &ObjectId,
711 offset: usize,
712 limit: usize,
713 ) -> Result<Vec<CommitSummary>, GitQueryError> {
714 let repo = self.repo_path(handle, name);
715
716 if limit == 0 {
717 return Ok(Vec::new());
718 }
719
720 // Both ends are already object ids, so the range is built here rather than
721 // taken from a URL — `..` is the one piece of revision syntax this module
722 // writes itself, and `RefName` refuses it precisely so that nothing else can.
723 let range = match base {
724 Some(base) => format!("{}..{}", base.as_str(), head.as_str()),
725 None => head.as_str().to_owned(),
726 };
727 let count = format!("--max-count={limit}");
728 let skip = format!("--skip={offset}");
729
730 let output = run(
731 &repo,
732 [
733 OsStr::new("log"),
734 OsStr::new("-z"),
735 OsStr::new(&count),
736 OsStr::new(&skip),
737 OsStr::new(LOG_FORMAT),
738 OsStr::new(&range),
739 ],
740 )
741 .await?;
742
743 parse_log(&output.stdout)
744 }
745
746 async fn count_between(
747 &self,
748 handle: &OrgName,
749 name: &RepoName,
750 base: Option<&ObjectId>,
751 head: &ObjectId,
752 ) -> Result<usize, GitQueryError> {
753 let repo = self.repo_path(handle, name);
754
755 // The range is built here from two resolved ids, exactly as `log_between`
756 // builds it — `..` is the only revision syntax this module writes itself.
757 let range = match base {
758 Some(base) => format!("{}..{}", base.as_str(), head.as_str()),
759 None => head.as_str().to_owned(),
760 };
761
762 let output = run(
763 &repo,
764 [
765 OsStr::new("rev-list"),
766 OsStr::new("--count"),
767 OsStr::new(&range),
768 ],
769 )
770 .await?;
771
772 let count = String::from_utf8_lossy(&output.stdout);
773 let count = count.trim();
774
775 count.parse().map_err(|_| {
776 GitQueryError::new(format!(
777 "git counted commits as {count:?}, which is not a number"
778 ))
779 })
780 }
781
782 async fn blame(
783 &self,
784 handle: &OrgName,
785 name: &RepoName,
786 rev: &RefName,
787 path: &RepoPath,
788 ) -> Result<Option<Blame>, GitQueryError> {
789 let repo = self.repo_path(handle, name);
790
791 // `git blame` is fatal on an unknown revision *and* on a path that is not in it,
792 // so one `--batch-check` on `{rev}:{path}` settles both before the expensive
793 // command runs — the module's rule that a non-zero exit is a real fault only
794 // holds because of checks like this one.
795 let Some(info) = self.pool.info(&repo, &tree_spec(rev, path)).await? else {
796 return Ok(None);
797 };
798
799 // A directory has no lines. Blaming one is another fatal error.
800 if info.kind != ObjectKind::Blob {
801 return Ok(None);
802 }
803
804 // The revision is named rather than the blob id: blame walks *history*, and a
805 // blob knows nothing about which commits reached it. `--` separates the revision
806 // from the path so neither can be read as the other, and `RefName` and
807 // `RepoPath` have already refused a leading hyphen.
808 let output = run(
809 &repo,
810 [
811 OsStr::new("blame"),
812 OsStr::new("--porcelain"),
813 OsStr::new(rev.as_str()),
814 OsStr::new("--"),
815 OsStr::new(path.as_str()),
816 ],
817 )
818 .await?;
819
820 Ok(Some(parse_blame(&output.stdout)))
821 }
822
823 async fn ref_snapshot(
824 &self,
825 handle: &OrgName,
826 name: &RepoName,
827 ) -> Result<Vec<(RefName, ObjectId)>, GitQueryError> {
828 let repo = self.repo_path(handle, name);
829
830 // The whole of `refs/` in one process. Unlike `list_refs`, which asks for the
831 // two namespaces a switcher shows, this is diffed around a push and a ref that
832 // was not asked about is a ref whose change goes unrecorded. The pattern is a
833 // literal; nothing from a URL reaches this call.
834 let output = run(
835 &repo,
836 [
837 OsStr::new("for-each-ref"),
838 OsStr::new(SNAPSHOT_FORMAT),
839 OsStr::new("refs/"),
840 ],
841 )
842 .await?;
843
844 Ok(parse_ref_snapshot(&output.stdout))
845 }
846
847 async fn log_at_path(
848 &self,
849 handle: &OrgName,
850 name: &RepoName,
851 rev: &RefName,
852 path: &RepoPath,
853 follow: bool,
854 offset: usize,
855 limit: usize,
856 ) -> Result<Vec<CommitSummary>, GitQueryError> {
857 let repo = self.repo_path(handle, name);
858
859 // Resolved first, for [`log`]'s reason: a log of a revision that names nothing
860 // is fatal, and the port promises an empty list rather than a failure.
861 let Some(info) = self.commit_info(&repo, rev).await? else {
862 return Ok(Vec::new());
863 };
864
865 if limit == 0 {
866 return Ok(Vec::new());
867 }
868
869 let count = format!("--max-count={limit}");
870 let skip = format!("--skip={offset}");
871 let mut args: Vec<&OsStr> = vec![
872 OsStr::new("log"),
873 OsStr::new("-z"),
874 OsStr::new(&count),
875 OsStr::new(&skip),
876 OsStr::new(LOG_FORMAT),
877 ];
878
879 // `--follow` before the revision, and only for a file: git refuses it for a
880 // directory and for more than one pathspec, and the refusal is a fatal exit
881 // rather than an empty answer.
882 if follow {
883 args.push(OsStr::new("--follow"));
884 }
885
886 args.push(OsStr::new(info.id.as_str()));
887 // Everything after `--` is a path, which is what stops a path that looks like a
888 // flag being read as one — `RepoPath` refuses a leading `-` as well, so this is
889 // the second of two locks on the same door.
890 args.push(OsStr::new("--"));
891 args.push(OsStr::new(path.as_str()));
892
893 let output = run(&repo, args).await?;
894
895 parse_log(&output.stdout)
896 }
897
898 async fn count_commits_at_path(
899 &self,
900 handle: &OrgName,
901 name: &RepoName,
902 rev: &RefName,
903 path: &RepoPath,
904 follow: bool,
905 ) -> Result<CommitCount, GitQueryError> {
906 let repo = self.repo_path(handle, name);
907
908 let Some(info) = self.commit_info(&repo, rev).await? else {
909 return Ok(CommitCount::default());
910 };
911
912 // One more than the cap, so "there are more" is a fact the walk reports rather
913 // than something inferred from hitting the limit exactly.
914 let scan = format!("-n{}", FOLLOWED_LOG_SCAN + 1);
915
916 // **`rev-list` has no `--follow`.** It is a `git log` option, and `rev-list`
917 // answers a usage error rather than ignoring it — so a followed count is a log
918 // of ids, counted here. Only the ids: `%H` alone keeps what git writes
919 // proportional to the number of commits rather than to their messages.
920 let mut args: Vec<&OsStr> = if follow {
921 vec![
922 OsStr::new("log"),
923 OsStr::new("--follow"),
924 OsStr::new("--format=%H"),
925 OsStr::new(&scan),
926 ]
927 } else {
928 vec![OsStr::new("rev-list"), OsStr::new("--count")]
929 };
930
931 args.push(OsStr::new(info.id.as_str()));
932 args.push(OsStr::new("--"));
933 args.push(OsStr::new(path.as_str()));
934
935 let output = run(&repo, args).await?;
936
937 if follow {
938 let counted = output.stdout.iter().filter(|byte| **byte == b'\n').count();
939
940 return Ok(CommitCount {
941 total: counted.min(FOLLOWED_LOG_SCAN) as u64,
942 capped: counted > FOLLOWED_LOG_SCAN,
943 });
944 }
945
946 let count = String::from_utf8_lossy(&output.stdout);
947 let count = count.trim();
948
949 Ok(CommitCount {
950 total: count.parse().map_err(|_| {
951 GitQueryError::new(format!(
952 "git counted commits as {count:?}, which is not a number"
953 ))
954 })?,
955 capped: false,
956 })
957 }
958
959 async fn symlink_targets(
960 &self,
961 handle: &OrgName,
962 name: &RepoName,
963 ids: &[ObjectId],
964 ) -> Result<HashMap<ObjectId, String>, GitQueryError> {
965 let repo = self.repo_path(handle, name);
966 let mut targets = HashMap::new();
967
968 if ids.is_empty() {
969 return Ok(targets);
970 }
971
972 // Sized in bulk first, because `contents` reads an object the batch-check has
973 // already described — the same two steps a tree listing takes, and for the same
974 // reason: the reply header is then a check rather than a parse.
975 let specs: Vec<String> = ids.iter().map(|id| id.as_str().to_owned()).collect();
976
977 for info in self
978 .pool
979 .info_many(&repo, &specs)
980 .await?
981 .into_iter()
982 .flatten()
983 {
984 if info.kind != ObjectKind::Blob {
985 continue;
986 }
987
988 let bytes = self.pool.contents(&repo, &info).await?;
989
990 // A target that is not UTF-8 is left out rather than lossily rendered: the
991 // row simply says nothing about where the link goes, which is honest.
992 if let Ok(target) = String::from_utf8(bytes) {
993 targets.insert(info.id, target);
994 }
995 }
996
997 Ok(targets)
998 }
999
1000 async fn merge_preview(
1001 &self,
1002 handle: &OrgName,
1003 name: &RepoName,
1004 target: &ObjectId,
1005 source: &ObjectId,
1006 ) -> Result<MergePreview, GitQueryError> {
1007 // Asked of the cache first. The pair of commit ids determines the answer
1008 // completely — git objects are content-addressed — so a hit is the same answer
1009 // this would compute, and it saves both the merge and the unreferenced objects
1010 // `--write-tree` writes on every run.
1011 if let Some(cached) = self.merges.get(target, source) {
1012 return Ok(cached);
1013 }
1014
1015 let repo = self.repo_path(handle, name);
1016
1017 // **The third exception to this module's rule that a non-zero exit is a
1018 // fault**, and the last: `git merge-tree` documents exit 1 as "the merge has
1019 // conflicts" and reserves 128 and above for what actually went wrong. A
1020 // conflict is the answer the page came for, not a failure — a pull request
1021 // whose branches disagree is an ordinary pull request.
1022 //
1023 // Both arguments are object ids git resolved, so there is nothing else exit 1
1024 // can mean here.
1025 let output = run_allowing(
1026 &repo,
1027 [
1028 OsStr::new("merge-tree"),
1029 OsStr::new("--write-tree"),
1030 OsStr::new(target.as_str()),
1031 OsStr::new(source.as_str()),
1032 ],
1033 &[MERGE_CONFLICTED],
1034 )
1035 .await?;
1036
1037 let preview = parse_merge_tree(
1038 &output.stdout,
1039 output.status.code() == Some(MERGE_CONFLICTED),
1040 )?;
1041
1042 self.merges.put(target, source, preview.clone());
1043
1044 Ok(preview)
1045 }
1046}
1047
1048/// Reads what `git merge-tree --write-tree` wrote.
1049///
1050/// The output is the merged tree's id on the first line, then — when there were
1051/// conflicts — an `ls-files -u`-shaped block of `<mode> <object> <stage> TAB <path>`
1052/// lines, a blank line, and git's own informational messages. The blank line is what
1053/// ends the block, which is why the messages below it are never mistaken for paths.
1054///
1055/// `conflicted` comes from the exit status rather than from whether the block is empty:
1056/// a clean merge can carry informational messages too, and reading the shape of the
1057/// output to decide what the exit code already said would be two answers to one
1058/// question.
1059///
1060/// A path appears once however many stages of it conflicted — three stages of the same
1061/// file is one file to whoever has to resolve it.
1062fn parse_merge_tree(stdout: &[u8], conflicted: bool) -> Result<MergePreview, GitQueryError> {
1063 let text = String::from_utf8_lossy(stdout);
1064 let mut lines = text.lines();
1065
1066 let tree = lines
1067 .next()
1068 .map(str::trim)
1069 .filter(|line| !line.is_empty())
1070 .ok_or_else(|| GitQueryError::new("git merge-tree named no tree"))?;
1071
1072 if !conflicted {
1073 return Ok(MergePreview::Clean {
1074 tree: ObjectId::new(tree).map_err(|error| {
1075 GitQueryError::new(format!("git merge-tree named a bad tree: {error}"))
1076 })?,
1077 });
1078 }
1079
1080 let mut paths: Vec<String> = Vec::new();
1081
1082 for line in lines {
1083 if line.is_empty() {
1084 break;
1085 }
1086
1087 // The tab is git's own separator between the three fixed fields and the path,
1088 // and it is what makes a filename containing spaces survive. A line without one
1089 // is not a conflicted-file line; skipping it is safer than guessing where the
1090 // path starts.
1091 let Some((_, path)) = line.split_once('\t') else {
1092 continue;
1093 };
1094
1095 let path = path.to_owned();
1096
1097 if !paths.contains(&path) {
1098 paths.push(path);
1099 }
1100 }
1101
1102 Ok(MergePreview::Conflicted { paths })
1103}
1104
1105/// How git addresses a path inside a revision: `{rev}:{path}`, and `{rev}:` for the root.
1106fn tree_spec(rev: &RefName, path: &RepoPath) -> String {
1107 format!("{}:{}", rev.as_str(), path.as_str())
1108}
1109
1110/// What a last-commit walk reads: id, commit time, subject.
1111///
1112/// Every separator is a NUL, and `-z` NUL-terminates the paths too — so the whole stream
1113/// is one NUL-separated sequence and a record boundary has to be recognised rather than
1114/// counted. See [`attribute`].
1115const LAST_COMMIT_FORMAT: &str = "--format=%H%x00%ct%x00%s";
1116
1117/// How far back a directory's last-commit column looks.
1118///
1119/// The walk is already narrowed to the directory by a pathspec, so this is 500 commits
1120/// *that touched this directory* — deep enough that a real listing is fully attributed
1121/// long before it, and shallow enough that a page has a bound on a repository of any
1122/// age. An entry still unattributed at the cap shows nothing, which is the honest answer:
1123/// the alternative is guessing, and a wrong commit beside a filename is worse than a
1124/// blank.
1125const LAST_COMMIT_SCAN: usize = 500;
1126
1127/// How far back a followed path history counts.
1128///
1129/// The last-commit column's cap, for the same reason and the same number. A followed
1130/// walk is the expensive one — `--follow` reads a tree per commit looking for the rename
1131/// that gave the file its name, and `rev-list` cannot do it at all — so on a long
1132/// history this is the read likeliest to meet the 20 s timeout, and a timeout is a page
1133/// with nothing on it. Past the cap the page says `500+`, which is what a reader deciding
1134/// whether they have seen the whole history actually needs to know.
1135pub(crate) const FOLLOWED_LOG_SCAN: usize = 500;
1136
1137/// Attributes each of a directory's entries to the most recent commit that touched it.
1138///
1139/// The stream is `<id> NUL <seconds> NUL <subject> NUL` followed by that commit's paths,
1140/// each NUL-terminated, and then the next commit. Nothing marks a boundary — git writes
1141/// one flat sequence — so a record is recognised by its shape: a full object id followed
1142/// by a field that parses as a time. A file named like an object id would need the field
1143/// after it to be a bare integer as well before it could be mistaken for one.
1144///
1145/// Newest first, so the **first** commit to mention a path is the one that owns it, and
1146/// a path under a child directory attributes to the child: `src/web/page.rs` in a listing
1147/// of `src` is `web`'s. Walking stops as soon as every entry has an answer, which is what
1148/// makes the cap a worst case rather than the usual cost.
1149///
1150/// git prints no file list for a merge commit, so a change that arrived by merge is
1151/// attributed to the commit inside the branch rather than to the merge — git's answer,
1152/// and the more useful one.
1153fn attribute(stdout: &[u8], prefix: &str, entries: &[String]) -> HashMap<String, EntryCommit> {
1154 let mut wanted: std::collections::HashSet<&str> = entries.iter().map(String::as_str).collect();
1155 let mut found: HashMap<String, EntryCommit> = HashMap::new();
1156
1157 let fields: Vec<&[u8]> = stdout.split(|byte| *byte == 0).collect();
1158 let mut index = 0;
1159
1160 while index < fields.len() && !wanted.is_empty() {
1161 let Some(commit) = record_at(&fields, index) else {
1162 index += 1;
1163 continue;
1164 };
1165
1166 index += 3;
1167
1168 // Everything up to the next record is this commit's paths. The first of them
1169 // carries the newline git writes between the formatted line and the file list.
1170 while index < fields.len() && record_at(&fields, index).is_none() {
1171 let path = String::from_utf8_lossy(fields[index]);
1172 let path = path.trim_start_matches('\n');
1173
1174 index += 1;
1175
1176 let Some(child) = path.strip_prefix(prefix) else {
1177 continue;
1178 };
1179
1180 let child = child.split('/').next().unwrap_or_default();
1181
1182 if wanted.remove(child) {
1183 found.insert(child.to_owned(), commit.clone());
1184 }
1185 }
1186 }
1187
1188 found
1189}
1190
1191/// Reads a commit record at `index`, if one starts there.
1192fn record_at(fields: &[&[u8]], index: usize) -> Option<EntryCommit> {
1193 let id = std::str::from_utf8(fields.get(index)?).ok()?;
1194 let seconds = std::str::from_utf8(fields.get(index + 1)?).ok()?;
1195 let summary = fields.get(index + 2)?;
1196
1197 if id.len() != 40 || !id.bytes().all(|byte| byte.is_ascii_hexdigit()) {
1198 return None;
1199 }
1200
1201 Some(EntryCommit {
1202 id: ObjectId::new(id).ok()?,
1203 summary: String::from_utf8_lossy(summary).trim().to_owned(),
1204 committed_at: unix_time(seconds.trim().parse::<i64>().ok()?),
1205 })
1206}
1207
1208/// Parses a tree object as git stores it.
1209///
1210/// The format is one record per entry and nothing else: `<mode> SP <name> NUL <20 raw
1211/// bytes of object id>`, with no terminator, no ordering guarantee a caller should rely
1212/// on, and **no sizes** — a tree records what is in it, not how big. The mode is octal
1213/// with no leading zero, so a directory is `40000` rather than `040000`; the name is raw
1214/// bytes, which is why the split happens before any attempt to read it as text.
1215///
1216/// This replaces `ls-tree -z --long`, whose text format git generated from exactly these
1217/// bytes. Sizes are asked for separately — see [`GitQuery::list_tree`].
1218///
1219/// A truncated record is an error rather than a short listing: half a directory is worse
1220/// than a page that says something went wrong.
1221fn parse_tree_object(bytes: &[u8]) -> Result<Vec<TreeEntry>, GitQueryError> {
1222 const ID_BYTES: usize = 20;
1223
1224 let mut entries = Vec::new();
1225 let mut rest = bytes;
1226
1227 while !rest.is_empty() {
1228 let Some(space) = rest.iter().position(|byte| *byte == b' ') else {
1229 return Err(GitQueryError::new("a tree entry has no mode"));
1230 };
1231
1232 let mode = std::str::from_utf8(&rest[..space])
1233 .map_err(|_| GitQueryError::new("a tree entry's mode is not text"))?;
1234
1235 let after_mode = &rest[space + 1..];
1236
1237 let Some(nul) = after_mode.iter().position(|byte| *byte == 0) else {
1238 return Err(GitQueryError::new("a tree entry's name is not terminated"));
1239 };
1240
1241 let name = &after_mode[..nul];
1242 let after_name = &after_mode[nul + 1..];
1243
1244 if after_name.len() < ID_BYTES {
1245 return Err(GitQueryError::new("a tree entry has no object id"));
1246 }
1247
1248 let id: String = after_name[..ID_BYTES]
1249 .iter()
1250 .map(|byte| format!("{byte:02x}"))
1251 .collect();
1252
1253 entries.push(TreeEntry {
1254 // Lossy, because `TreeEntry::name` is a `String` and a filename is not
1255 // required to be UTF-8. A replacement character renders; refusing to list
1256 // the whole directory because one file has an odd name does not.
1257 name: String::from_utf8_lossy(name).into_owned(),
1258 kind: EntryKind::from_mode(mode)
1259 .map_err(|error| GitQueryError::new(format!("git listed {name:?}: {error}")))?,
1260 id: ObjectId::from_trusted(id),
1261 // Filled in by the caller for the kinds that have one; a tree object records
1262 // no sizes at all.
1263 size: None,
1264 });
1265
1266 rest = &after_name[ID_BYTES..];
1267 }
1268
1269 // Unsorted on purpose: ordering is `TreeEntry::ordering_key`'s decision, made once
1270 // in the application rather than differently in each adapter.
1271 Ok(entries)
1272}
1273
1274/// Parses the NUL-separated `log` stream into four-field records.
1275fn parse_log_entries(stdout: &[u8]) -> Result<Vec<CommitEntry>, GitQueryError> {
1276 // Empty fields are **kept**, as in [`parse_log`]: a one-line commit message has an
1277 // empty body, and dropping it would slide every following field one place left and
1278 // report one commit's subject as another's author. `-z` terminates the last record
1279 // as well, so exactly one trailing empty is the terminator and is dropped by hand.
1280 let mut fields: Vec<&[u8]> = stdout.split(|byte| *byte == 0).collect();
1281
1282 if fields.last().is_some_and(|last| last.is_empty()) {
1283 fields.pop();
1284 }
1285
1286 let mut entries = Vec::with_capacity(fields.len() / 5);
1287
1288 for record in fields.chunks(5) {
1289 let [id, committed_at, author_name, summary, body] = record[..] else {
1290 return Err(GitQueryError::new(
1291 "git logged a commit with missing fields",
1292 ));
1293 };
1294
1295 let id = String::from_utf8_lossy(id);
1296 let committed_at = String::from_utf8_lossy(committed_at);
1297 let committed_at: i64 = committed_at.trim().parse().map_err(|_| {
1298 GitQueryError::new(format!(
1299 "git logged an unreadable commit time {committed_at:?}"
1300 ))
1301 })?;
1302
1303 entries.push(CommitEntry {
1304 commit: CommitSummary {
1305 id: ObjectId::new(id.trim()).map_err(|error| {
1306 GitQueryError::new(format!("git named a bad object id: {error}"))
1307 })?,
1308 summary: String::from_utf8_lossy(summary)
1309 .lines()
1310 .next()
1311 .unwrap_or_default()
1312 .to_owned(),
1313 author_name: String::from_utf8_lossy(author_name).into_owned(),
1314 committed_at: unix_time(committed_at),
1315 },
1316 // `%b` ends with the newline that closed the message. Trimmed at the end
1317 // only: leading blank lines are the author's, and a feed shows what was
1318 // written.
1319 body: String::from_utf8_lossy(body).trim_end().to_owned(),
1320 });
1321 }
1322
1323 Ok(entries)
1324}
1325
1326fn parse_log(stdout: &[u8]) -> Result<Vec<CommitSummary>, GitQueryError> {
1327 // Empty fields are **kept**, as in [`parse_log_entries`]: an author name can be
1328 // empty and so can a subject, and dropping one slides every following field a place
1329 // left, so one commit's subject is reported as the next one's author. `-z`
1330 // terminates the last record as well, so exactly one trailing empty is the
1331 // terminator and is dropped by hand.
1332 let mut fields: Vec<&[u8]> = stdout.split(|byte| *byte == 0).collect();
1333
1334 if fields.last().is_some_and(|last| last.is_empty()) {
1335 fields.pop();
1336 }
1337
1338 let mut commits = Vec::with_capacity(fields.len() / 4);
1339
1340 for record in fields.chunks(4) {
1341 let [id, committed_at, author_name, summary] = record[..] else {
1342 return Err(GitQueryError::new(
1343 "git logged a commit with missing fields",
1344 ));
1345 };
1346
1347 let id = String::from_utf8_lossy(id);
1348 let committed_at = String::from_utf8_lossy(committed_at);
1349 let committed_at: i64 = committed_at.trim().parse().map_err(|_| {
1350 GitQueryError::new(format!(
1351 "git logged an unreadable commit time {committed_at:?}"
1352 ))
1353 })?;
1354
1355 commits.push(CommitSummary {
1356 id: ObjectId::new(id.trim()).map_err(|error| {
1357 GitQueryError::new(format!("git named a bad object id: {error}"))
1358 })?,
1359 // `%s` is git's subject: the first paragraph, joined into one line. Trimmed
1360 // to the first line anyway, because that invariant is git's rather than
1361 // something this parser should assume.
1362 summary: String::from_utf8_lossy(summary)
1363 .lines()
1364 .next()
1365 .unwrap_or_default()
1366 .to_owned(),
1367 author_name: String::from_utf8_lossy(author_name).into_owned(),
1368 committed_at: unix_time(committed_at),
1369 });
1370 }
1371
1372 Ok(commits)
1373}
1374
1375/// A unix timestamp as a `SystemTime`, including the negative ones.
1376///
1377/// A commit dated before 1970 is either a lie or an import from something older than
1378/// git, and both exist in real repositories. `UNIX_EPOCH + Duration` would panic on the
1379/// subtraction it cannot do.
1380fn unix_time(seconds: i64) -> SystemTime {
1381 match u64::try_from(seconds) {
1382 Ok(seconds) => UNIX_EPOCH + Duration::from_secs(seconds),
1383 Err(_) => UNIX_EPOCH - Duration::from_secs(seconds.unsigned_abs()),
1384 }
1385}
1386
1387/// What `for-each-ref` prints per ref: the full name and the object it names,
1388/// NUL-separated and NUL-terminated.
1389///
1390/// The kind is *not* asked for. `%(objecttype)` says `commit` for both a branch and a
1391/// lightweight tag, so the namespace in the name is the only thing that answers which
1392/// one a visitor asked for.
1393const REF_FORMAT: &str = "--format=%(refname)%00";
1394
1395/// What a snapshot asks for: the full name and the object the ref itself names.
1396///
1397/// `%(objectname)` rather than `%(*objectname)`, so an annotated tag reports the tag
1398/// object. What a push changed is the *ref*, and re-tagging the same commit with a new
1399/// annotation is a change even though the peeled ids match.
1400const SNAPSHOT_FORMAT: &str = "--format=%(refname)%00%(objectname)%00";
1401
1402/// Parses a snapshot's NUL-separated pairs.
1403///
1404/// Same shape as [`parse_refs`], two fields instead of one, and the same rule about a
1405/// ref that Steid's own [`RefName`] refuses: left out rather than carried. A push event
1406/// naming a ref no page can address is a row nothing can do anything with.
1407fn parse_ref_snapshot(stdout: &[u8]) -> Vec<(RefName, ObjectId)> {
1408 let fields = ref_fields(stdout);
1409 let mut snapshot = Vec::with_capacity(fields.len() / 2);
1410
1411 for pair in fields.chunks_exact(2) {
1412 // git ends each record with a newline the format cannot suppress, so it arrives
1413 // at the front of the next record's first field. A ref name contains neither a
1414 // newline nor a space, so trimming cannot eat part of one.
1415 let Ok(full) = std::str::from_utf8(pair[0].trim_ascii()) else {
1416 continue;
1417 };
1418 let Ok(id) = std::str::from_utf8(pair[1].trim_ascii()) else {
1419 continue;
1420 };
1421
1422 let (Ok(name), Ok(id)) = (RefName::new(full), ObjectId::new(id)) else {
1423 continue;
1424 };
1425
1426 snapshot.push((name, id));
1427 }
1428
1429 snapshot
1430}
1431
1432/// Parses `for-each-ref`'s NUL-separated output into branches and tags.
1433///
1434/// Each record is `<full refname> NUL`, and git ends every record with a newline of its
1435/// own that the format cannot suppress — so the newline arrives at the *front* of the
1436/// next record's first field and is trimmed off. A ref name can contain neither a
1437/// newline nor a space, so trimming cannot eat part of a name.
1438fn parse_refs(stdout: &[u8]) -> Vec<GitRef> {
1439 let mut refs = Vec::new();
1440
1441 for record in stdout.split(|byte| *byte == 0) {
1442 let record = record.trim_ascii();
1443
1444 if record.is_empty() {
1445 continue;
1446 }
1447
1448 // Lossy would be wrong here: a name that is not UTF-8 cannot be put in a URL,
1449 // and offering a link that cannot work is worse than leaving the ref out of the
1450 // switcher. It is still browsable by object id.
1451 let Ok(full) = std::str::from_utf8(record) else {
1452 continue;
1453 };
1454
1455 let (kind, short) = if let Some(short) = full.strip_prefix("refs/heads/") {
1456 (RefKind::Branch, short)
1457 } else if let Some(short) = full.strip_prefix("refs/tags/") {
1458 (RefKind::Tag, short)
1459 } else {
1460 // Only the two namespaces were asked for, so this cannot happen — and if a
1461 // future pattern is added and this is forgotten, skipping is the safe half
1462 // of the mistake.
1463 continue;
1464 };
1465
1466 // Validated rather than trusted: this name is about to become a URL, and
1467 // `RefName` is what decides a name is safe to hand back to git. A ref git
1468 // accepts but Steid's rules do not is left out rather than linked to.
1469 let Ok(name) = RefName::new(short) else {
1470 continue;
1471 };
1472
1473 refs.push(GitRef { name, kind });
1474 }
1475
1476 refs
1477}
1478
1479/// What the latest-tag query asks for: the full ref name and its creation time.
1480///
1481/// `creatordate` rather than `taggerdate`, which is empty for a lightweight tag, or
1482/// `committerdate`, which is empty for an annotated one. `creatordate` is git's own
1483/// "whichever of those this ref has".
1484const TAG_FORMAT: &str = "--format=%(refname)%00%(creatordate:unix)%00";
1485
1486/// Parses the one record [`TAG_FORMAT`] produces, or `None` for a repository with no
1487/// tags.
1488///
1489/// Anything unreadable is `None` rather than an error: this decorates a page with a
1490/// fact, and a tag whose name is not UTF-8 or whose date git spelled unexpectedly is a
1491/// reason to say nothing, not to fail the repository's landing page.
1492fn parse_latest_tag(stdout: &[u8]) -> Option<TagSummary> {
1493 let fields: Vec<&[u8]> = stdout
1494 .split(|byte| *byte == 0)
1495 .map(<[u8]>::trim_ascii)
1496 .filter(|field| !field.is_empty())
1497 .collect();
1498
1499 let [name, created_at] = fields[..] else {
1500 return None;
1501 };
1502
1503 let short = std::str::from_utf8(name).ok()?.strip_prefix("refs/tags/")?;
1504 let created_at: i64 = std::str::from_utf8(created_at).ok()?.parse().ok()?;
1505
1506 Some(TagSummary {
1507 // Validated rather than trusted, exactly as `parse_refs` does: the name is
1508 // about to become a link.
1509 name: RefName::new(short).ok()?,
1510 created_at: unix_time(created_at),
1511 })
1512}
1513
1514/// What the branches page asks for, per branch.
1515///
1516/// `%(HEAD)` is git's own marker for the branch `HEAD` points at — `*` for it and a
1517/// space for everything else. It is asked for here rather than resolved separately
1518/// because a second process to learn one bit is the cost 0006 is about.
1519///
1520/// `%(objectname)` is the tip commit itself: a branch, unlike a tag, never points at
1521/// anything else.
1522const BRANCH_FORMAT: &str = "--format=%(refname)%00%(HEAD)%00%(objectname)%00%(committerdate:unix)%00%(contents:subject)%00";
1523
1524/// What the tags page asks for, per tag.
1525///
1526/// `%(objecttype)` is `tag` for an annotated tag and `commit` for a lightweight one,
1527/// which is the only reliable way to tell them apart. `%(*objectname)` is the peeled
1528/// object and is empty for a lightweight tag, so the commit is "the peeled one if there
1529/// is one". `%(contents:subject)` is the *tag's* message for an annotated tag and the
1530/// *commit's* for a lightweight one — so it is read only when the type says `tag`,
1531/// otherwise a lightweight tag would appear to carry a message it does not have.
1532const TAG_ROW_FORMAT: &str = "--format=%(refname)%00%(objecttype)%00%(objectname)%00%(*objectname)%00%(creatordate:unix)%00%(contents:subject)%00";
1533
1534/// Splits `for-each-ref` output into its NUL-terminated fields.
1535///
1536/// Every field ends with a NUL and git adds a newline after each record that the format
1537/// cannot suppress, so the split yields exactly one field per `%00` plus a trailing
1538/// remainder holding that last newline — dropped here.
1539///
1540/// **Empty fields are kept.** A lightweight tag has no peeled object, and filtering
1541/// empties the way [`parse_latest_tag`] can afford to would shift every later field of
1542/// that record onto the wrong name.
1543fn ref_fields(stdout: &[u8]) -> Vec<&[u8]> {
1544 let mut fields: Vec<&[u8]> = stdout.split(|byte| *byte == 0).collect();
1545 fields.pop();
1546 fields
1547}
1548
1549/// The first line of git's subject, or `None` when there is nothing to show.
1550///
1551/// `%(contents:subject)` is already one line, but that is git's invariant rather than
1552/// something this parser should assume — the same reason [`parse_log`] trims `%s`.
1553fn subject(field: &[u8]) -> Option<String> {
1554 let line = String::from_utf8_lossy(field)
1555 .lines()
1556 .next()
1557 .unwrap_or_default()
1558 .trim()
1559 .to_owned();
1560
1561 (!line.is_empty()).then_some(line)
1562}
1563
1564/// Parses [`BRANCH_FORMAT`] into rows, in the order git sorted them.
1565///
1566/// A record whose name or commit id Steid cannot use is skipped rather than failing the
1567/// page, exactly as [`parse_refs`] skips one: a branch that cannot be linked to is a
1568/// reason to leave a row out, not to refuse the whole list. A record with the wrong
1569/// number of fields is different — that is git saying something this code does not
1570/// understand, and it is an error.
1571fn parse_branches(stdout: &[u8]) -> Result<Vec<BranchRow>, GitQueryError> {
1572 let fields = ref_fields(stdout);
1573 let mut rows = Vec::with_capacity(fields.len() / 5);
1574
1575 for record in fields.chunks(5) {
1576 let [name, head, commit, committed_at, summary] = record[..] else {
1577 return Err(GitQueryError::new(
1578 "git listed a branch with missing fields",
1579 ));
1580 };
1581
1582 // git's trailing newline arrives in front of the next record's first field.
1583 // A ref name can contain neither a newline nor a space, so trimming cannot eat
1584 // part of one.
1585 let Some(name) = short_ref(name.trim_ascii(), "refs/heads/") else {
1586 continue;
1587 };
1588
1589 let Ok(commit) = ObjectId::new(String::from_utf8_lossy(commit).trim()) else {
1590 continue;
1591 };
1592
1593 let committed_at = String::from_utf8_lossy(committed_at);
1594 let Ok(committed_at) = committed_at.trim().parse::<i64>() else {
1595 continue;
1596 };
1597
1598 rows.push(BranchRow {
1599 name,
1600 // `*` for the branch HEAD names, a space for the rest.
1601 is_default: head.trim_ascii() == b"*",
1602 commit,
1603 summary: subject(summary).unwrap_or_default(),
1604 committed_at: unix_time(committed_at),
1605 });
1606 }
1607
1608 Ok(rows)
1609}
1610
1611/// Parses [`TAG_ROW_FORMAT`] into rows, in the order git sorted them.
1612///
1613/// Skips and errors on the same terms as [`parse_branches`].
1614fn parse_tags(stdout: &[u8]) -> Result<Vec<TagRow>, GitQueryError> {
1615 let fields = ref_fields(stdout);
1616 let mut rows = Vec::with_capacity(fields.len() / 6);
1617
1618 for record in fields.chunks(6) {
1619 let [name, kind, object, peeled, created_at, message] = record[..] else {
1620 return Err(GitQueryError::new("git listed a tag with missing fields"));
1621 };
1622
1623 let Some(name) = short_ref(name.trim_ascii(), "refs/tags/") else {
1624 continue;
1625 };
1626
1627 // An annotated tag's `objectname` is the tag object, so the thing worth linking
1628 // to is the peeled one. A lightweight tag has no peel and already names its
1629 // commit.
1630 let annotated = kind.trim_ascii() == b"tag";
1631 let id = if peeled.trim_ascii().is_empty() {
1632 object
1633 } else {
1634 peeled
1635 };
1636
1637 let Ok(commit) = ObjectId::new(String::from_utf8_lossy(id).trim()) else {
1638 continue;
1639 };
1640
1641 let created_at = String::from_utf8_lossy(created_at);
1642 let Ok(created_at) = created_at.trim().parse::<i64>() else {
1643 continue;
1644 };
1645
1646 rows.push(TagRow {
1647 name,
1648 commit,
1649 // Only an annotated tag has a message of its own; for a lightweight one
1650 // this field is the commit's subject, which belongs to the commit.
1651 message: annotated.then(|| subject(message)).flatten(),
1652 annotated,
1653 created_at: unix_time(created_at),
1654 });
1655 }
1656
1657 Ok(rows)
1658}
1659
1660/// A full ref name reduced to the short form Steid puts in a URL, or `None` when it is
1661/// outside the namespace asked for or is not a name Steid will hand back to git.
1662///
1663/// Validated rather than trusted for the reason [`parse_refs`] gives: this name is
1664/// about to become a link.
1665fn short_ref(full: &[u8], namespace: &str) -> Option<RefName> {
1666 let full = std::str::from_utf8(full).ok()?;
1667 RefName::new(full.strip_prefix(namespace)?).ok()
1668}
1669
1670/// Runs a git command inside a repository and fails on a non-zero exit.
1671///
1672/// Only ever used for commands whose subject has already been confirmed to exist, so a
1673/// failure really is a failure. Built from [`git_command`] so the host isolation 0006
1674/// insists on cannot drift out of this module.
1675/// How long one read-side `git` process may run before it is killed.
1676///
1677/// Every read here is a subprocess on a request path, and nothing bounded it before
1678/// blame and grep arrived — either can run for a long time on a large repository, and
1679/// a request that never finishes holds a worker for as long as the client waits.
1680/// Twenty seconds is far above any read a page should make and far below "hung".
1681const GIT_TIMEOUT: Duration = Duration::from_secs(20);
1682
1683async fn run<I, S>(repo: &Path, args: I) -> Result<Output, GitQueryError>
1684where
1685 I: IntoIterator<Item = S>,
1686 S: AsRef<OsStr>,
1687{
1688 run_within(repo, args, GIT_TIMEOUT).await
1689}
1690
1691// The two exit statuses this module reads as answers rather than as faults. Both are 1
1692// and they are separate constants on purpose: what makes each of them legible is the
1693// question it answers, not the number. See [`run_allowing`], which is the only way
1694// either reaches a command.
1695
1696/// What `git grep` exits with when it matched nothing.
1697const NO_MATCHES: i32 = 1;
1698
1699/// What `git merge-base` exits with for two commits that share no ancestor — documented
1700/// as an answer, with 128 reserved for real errors.
1701const NO_COMMON_ANCESTOR: i32 = 1;
1702
1703/// What `git merge-tree` exits with when the merge has conflicts — documented as an
1704/// answer, with 128 and above reserved for what actually went wrong.
1705const MERGE_CONFLICTED: i32 = 1;
1706
1707/// [`run`] for a command whose exit status is partly an answer.
1708///
1709/// Exists for `git grep`, `git merge-base` and `git merge-tree` alone — grep's 1 is
1710/// "matched nothing", merge-base's is "no common ancestor" and merge-tree's is "the
1711/// merge has conflicts", all three promised by git's manual. Every other command here is
1712/// asked about something `cat-file --batch-check` has already confirmed exists, which is
1713/// what makes the module's "a non-zero exit is always a fault" rule hold. These three are
1714/// asked questions whose answer can legitimately be "there is none".
1715async fn run_allowing<I, S>(repo: &Path, args: I, allowed: &[i32]) -> Result<Output, GitQueryError>
1716where
1717 I: IntoIterator<Item = S>,
1718 S: AsRef<OsStr>,
1719{
1720 run_within_allowing(repo, args, GIT_TIMEOUT, allowed).await
1721}
1722
1723/// [`run`] with an explicit limit, so the timeout path can be tested without waiting
1724/// twenty seconds for it.
1725async fn run_within<I, S>(repo: &Path, args: I, limit: Duration) -> Result<Output, GitQueryError>
1726where
1727 I: IntoIterator<Item = S>,
1728 S: AsRef<OsStr>,
1729{
1730 run_within_allowing(repo, args, limit, &[]).await
1731}
1732
1733/// The whole of running git: isolation, the timeout, and the status rule.
1734async fn run_within_allowing<I, S>(
1735 repo: &Path,
1736 args: I,
1737 limit: Duration,
1738 allowed: &[i32],
1739) -> Result<Output, GitQueryError>
1740where
1741 I: IntoIterator<Item = S>,
1742 S: AsRef<OsStr>,
1743{
1744 let mut command = git_command();
1745 command
1746 .arg("-C")
1747 .arg(repo)
1748 .args(args)
1749 .stdin(Stdio::null())
1750 // Dropping the future on timeout must take the process with it, or a killed
1751 // request leaves git running to completion for nobody.
1752 .kill_on_drop(true);
1753
1754 let output = match tokio::time::timeout(limit, command.output()).await {
1755 Ok(result) => {
1756 result.map_err(|error| GitQueryError::new(format!("could not run git: {error}")))?
1757 }
1758 Err(_elapsed) => return Err(GitQueryError::timed_out(limit)),
1759 };
1760
1761 let expected = output
1762 .status
1763 .code()
1764 .is_some_and(|code| allowed.contains(&code));
1765
1766 if !output.status.success() && !expected {
1767 return Err(GitQueryError::new(format!(
1768 "git exited with {}: {}",
1769 output.status,
1770 String::from_utf8_lossy(&output.stderr).trim()
1771 )));
1772 }
1773
1774 Ok(output)
1775}
1776
1777/// Runs a git command and reads at most `max_bytes` of its output.
1778///
1779/// [`run`] collects everything git writes, which is right for a tree listing and wrong
1780/// for a patch: a single commit can legitimately carry hundreds of megabytes of diff,
1781/// and a page must not be able to pull that into memory. So this one reads through a
1782/// pipe and stops, killing the process rather than draining it — an abandoned `git
1783/// diff-tree` writing into a closed pipe is exactly what SIGPIPE is for.
1784///
1785/// Returns the bytes and whether the cap was hit. **The exit status is only checked
1786/// when it was not**: a process killed part-way through has a status that says so, and
1787/// treating that as a failure would turn every oversized diff into a 500.
1788async fn run_capped<I, S>(
1789 repo: &Path,
1790 args: I,
1791 max_bytes: u64,
1792) -> Result<(Vec<u8>, bool), GitQueryError>
1793where
1794 I: IntoIterator<Item = S>,
1795 S: AsRef<OsStr>,
1796{
1797 let mut command = git_command();
1798 command
1799 .arg("-C")
1800 .arg(repo)
1801 .args(args)
1802 .stdin(Stdio::null())
1803 .stdout(Stdio::piped())
1804 .stderr(Stdio::piped())
1805 .kill_on_drop(true);
1806
1807 let read = async {
1808 let mut child = command
1809 .spawn()
1810 .map_err(|error| GitQueryError::new(format!("could not run git: {error}")))?;
1811
1812 let mut stdout = child.stdout.take().expect("stdout was piped");
1813 let mut bytes = Vec::new();
1814
1815 // One byte past the cap, so hitting it exactly is not mistaken for exceeding
1816 // it. The surplus byte is dropped below.
1817 let limit = max_bytes.saturating_add(1);
1818
1819 (&mut stdout)
1820 .take(limit)
1821 .read_to_end(&mut bytes)
1822 .await
1823 .map_err(|error| GitQueryError::new(format!("could not read from git: {error}")))?;
1824
1825 if bytes.len() as u64 > max_bytes {
1826 bytes.truncate(max_bytes as usize);
1827 // Nothing waits for the exit status: git is still writing, and the whole
1828 // point is not to read the rest. `kill_on_drop` reaps it.
1829 let _ = child.start_kill();
1830
1831 return Ok((bytes, true));
1832 }
1833
1834 // stdout is already drained, so this collects stderr and the status. stderr is
1835 // git's own diagnostics — small by construction, and only read on failure.
1836 let output = child
1837 .wait_with_output()
1838 .await
1839 .map_err(|error| GitQueryError::new(format!("could not wait for git: {error}")))?;
1840
1841 if !output.status.success() {
1842 return Err(GitQueryError::new(format!(
1843 "git exited with {}: {}",
1844 output.status,
1845 String::from_utf8_lossy(&output.stderr).trim()
1846 )));
1847 }
1848
1849 Ok((bytes, false))
1850 };
1851
1852 match tokio::time::timeout(GIT_TIMEOUT, read).await {
1853 Ok(result) => result,
1854 Err(_elapsed) => Err(GitQueryError::timed_out(GIT_TIMEOUT)),
1855 }
1856}
1857
1858/// What a log record carries: id, commit time, author name, subject.
1859///
1860/// Every separator is a NUL, and `-z` separates the records themselves. A commit
1861/// message contains newlines as a matter of course and a name can contain almost
1862/// anything, so splitting on lines or whitespace would misread real history rather than
1863/// exotic history.
1864const LOG_FORMAT: &str = "--format=%H%x00%ct%x00%an%x00%s";
1865
1866/// [`LOG_FORMAT`] plus the message body, which a feed entry shows and a log row does
1867/// not.
1868///
1869/// The body is **last** for the reason [`COMMIT_FORMAT`]'s is: it is the field that can
1870/// contain anything, including nothing at all.
1871const ENTRY_FORMAT: &str = "--format=%H%x00%ct%x00%an%x00%s%x00%b";
1872
1873/// Parses a commit object as git stores it.
1874///
1875/// ```text
1876/// tree <id>
1877/// parent <id> (absent on a root commit, twice on a merge)
1878/// author Name <email> <unix seconds> <offset>
1879/// committer Name <email> <unix seconds> <offset>
1880/// <other headers, whose continuation lines begin with a space>
1881///
1882/// the message
1883/// ```
1884///
1885/// This replaces `git log --format=…`, which produced the same fields out of these same
1886/// bytes for the cost of a process. Two of git's conventions are reproduced rather than
1887/// assumed, because a page shows them:
1888///
1889/// - **The subject is the first paragraph, not the first line.** `%s` folds a
1890/// multi-line first paragraph into one line by joining with spaces, and a log row that
1891/// showed only the first line of one would silently cut a sentence in half.
1892/// - **The body is everything after the blank line that ends the subject**, trimmed of
1893/// trailing whitespace. Trailing whitespace is not part of a message.
1894///
1895/// The id is passed in rather than hashed here: it came off the `--batch` header, which
1896/// is git's own answer to what this object is.
1897///
1898/// The zone offset on a date is read and discarded. Steid renders times in the viewer's
1899/// terms, so the committer's timezone is a fact about them and not about the commit.
1900fn parse_commit_object(id: &ObjectId, bytes: &[u8]) -> Result<CommitDetail, GitQueryError> {
1901 let (headers, message) = split_headers(bytes);
1902
1903 let mut tree = None;
1904 let mut parents = Vec::new();
1905 let mut author = None;
1906 let mut committer = None;
1907
1908 for line in headers.split(|byte| *byte == b'\n') {
1909 // A continuation of the header before it — a `gpgsig`, or an embedded
1910 // `mergetag`. Skipped whole: nothing here reads either.
1911 if line.first() == Some(&b' ') {
1912 continue;
1913 }
1914
1915 let line = String::from_utf8_lossy(line);
1916 let Some((key, value)) = line.split_once(' ') else {
1917 continue;
1918 };
1919
1920 match key {
1921 "tree" => tree = Some(object_id(value)?),
1922 "parent" => parents.push(object_id(value)?),
1923 "author" => author = Some(identity(value)?),
1924 "committer" => committer = Some(identity(value)?),
1925 _ => {}
1926 }
1927 }
1928
1929 let (Some(tree), Some(author), Some(committer)) = (tree, author, committer) else {
1930 return Err(GitQueryError::new(format!(
1931 "git stored {} as a commit with no tree, author or committer",
1932 id.as_str()
1933 )));
1934 };
1935
1936 let (summary, body) = split_message(&String::from_utf8_lossy(message));
1937
1938 Ok(CommitDetail {
1939 id: id.clone(),
1940 tree,
1941 parents,
1942 summary,
1943 body,
1944 author_name: author.name,
1945 author_email: author.email,
1946 authored_at: author.at,
1947 committer_name: committer.name,
1948 committer_email: committer.email,
1949 committed_at: committer.at,
1950 })
1951}
1952
1953/// Splits a commit object into its headers and its message.
1954///
1955/// The boundary is the first genuinely empty line. A `gpgsig` header's continuation
1956/// lines each begin with a space, so even the blank-looking ones inside a signature are
1957/// a space long and do not end the headers.
1958///
1959/// A commit with no message at all — git allows one with `--allow-empty-message` — has
1960/// no blank line either, and the whole object is headers.
1961fn split_headers(bytes: &[u8]) -> (&[u8], &[u8]) {
1962 if let Some(index) = bytes
1963 .windows(2)
1964 .position(|window| window == b"\n\n")
1965 .map(|index| index + 1)
1966 {
1967 (&bytes[..index], &bytes[index + 1..])
1968 } else {
1969 (bytes, &[])
1970 }
1971}
1972
1973/// Splits a commit message into git's `%s` and `%b`.
1974fn split_message(message: &str) -> (String, String) {
1975 let (subject, body) = match message.split_once("\n\n") {
1976 Some((subject, body)) => (subject, body),
1977 None => (message, ""),
1978 };
1979
1980 let subject = subject
1981 .lines()
1982 .map(str::trim_end)
1983 .collect::<Vec<&str>>()
1984 .join(" ");
1985
1986 (subject.trim().to_owned(), body.trim_end().to_owned())
1987}
1988
1989/// Who wrote or committed something, and when.
1990struct Identity {
1991 name: String,
1992 email: String,
1993 at: SystemTime,
1994}
1995
1996/// Parses an `author` or `committer` value: `Name <email> <seconds> <offset>`.
1997///
1998/// Read from the **right**, because a name may contain anything at all — including
1999/// angle brackets and, in real history, an email address of its own. The last two
2000/// whitespace-separated fields are the time and the zone; the email is what sits in the
2001/// final pair of angle brackets before them.
2002fn identity(value: &str) -> Result<Identity, GitQueryError> {
2003 let bad = || GitQueryError::new(format!("git wrote an identity we cannot read: {value:?}"));
2004
2005 let (rest, _zone) = value.rsplit_once(' ').ok_or_else(bad)?;
2006 let (rest, seconds) = rest.rsplit_once(' ').ok_or_else(bad)?;
2007 let (name, email) = rest.rsplit_once(" <").ok_or_else(bad)?;
2008
2009 Ok(Identity {
2010 name: name.trim().to_owned(),
2011 email: email.trim_end().trim_end_matches('>').to_owned(),
2012 at: seconds
2013 .trim()
2014 .parse::<i64>()
2015 .map(unix_time)
2016 .map_err(|_| GitQueryError::new(format!("git dated a commit as {seconds:?}")))?,
2017 })
2018}
2019
2020/// An object id git named, validated rather than trusted.
2021///
2022/// git's ids are trustworthy; this is a parse of a layout we have assumed, and an id is
2023/// about to appear in a URL. A misread field should stop here rather than surface as a
2024/// broken link.
2025fn object_id(value: &str) -> Result<ObjectId, GitQueryError> {
2026 ObjectId::new(value.trim())
2027 .map_err(|error| GitQueryError::new(format!("git named a bad object id: {error}")))
2028}
2029
2030/// Splits `--numstat -p` output into its two halves.
2031///
2032/// git writes every `--numstat` line first and then the patch, so the boundary is the
2033/// first `diff --git ` line — a marker no numstat line can produce, since one always
2034/// begins with a count or the `-` that stands for a binary file. The blank line git
2035/// puts between the two is not relied on.
2036///
2037/// A patch that is entirely absent — a commit that changed nothing, or a read cut short
2038/// before the patch began — leaves the second half empty, which is a state the caller
2039/// already has to handle.
2040fn split_numstat(stdout: &[u8]) -> (&[u8], &[u8]) {
2041 const MARKER: &[u8] = b"diff --git ";
2042
2043 if stdout.starts_with(MARKER) {
2044 return (&[], stdout);
2045 }
2046
2047 for (index, byte) in stdout.iter().enumerate() {
2048 if *byte == b'\n' && stdout[index + 1..].starts_with(MARKER) {
2049 return stdout.split_at(index + 1);
2050 }
2051 }
2052
2053 (stdout, &[])
2054}
2055
2056#[cfg(test)]
2057mod tests {
2058 use std::collections::HashMap;
2059
2060 use tempfile::TempDir;
2061
2062 use super::*;
2063 use crate::domain::EntryKind;
2064
2065 /// Fixed so a timestamp assertion is exact rather than approximate.
2066 const FIRST_COMMIT: i64 = 1_700_000_000;
2067 const SECOND_COMMIT: i64 = 1_700_000_100;
2068 const THIRD_COMMIT: i64 = 1_700_000_200;
2069
2070 /// A subject with the punctuation a naive parser splits on, followed by a body — so
2071 /// a test can prove the body does not leak into the summary.
2072 const ODD_MESSAGE: &str =
2073 "third: 'quotes', \"doubles\" | pipes\n\nbody line one\nbody line two";
2074
2075 const BINARY: &[u8] = &[0x00, 0x01, 0xff, 0xfe, 0x80];
2076
2077 fn handle() -> OrgName {
2078 OrgName::new("jamesgill").expect("valid handle")
2079 }
2080
2081 fn repo_name() -> RepoName {
2082 RepoName::new("steid").expect("valid repository name")
2083 }
2084
2085 fn rev(value: &str) -> RefName {
2086 RefName::new(value).expect("valid revision")
2087 }
2088
2089 fn path(value: &str) -> RepoPath {
2090 RepoPath::new(value).expect("valid path")
2091 }
2092
2093 /// Runs git in a fixture, isolated from the host's configuration the same way the
2094 /// adapter is — otherwise a developer's `commit.gpgsign` or `init.defaultBranch`
2095 /// decides whether the suite passes.
2096 fn git(dir: &Path, when: i64, args: &[&str]) {
2097 let date = format!("@{when} +0000");
2098
2099 let output = std::process::Command::new("git")
2100 .arg("-C")
2101 .arg(dir)
2102 .args(args)
2103 .env("GIT_CONFIG_GLOBAL", "/dev/null")
2104 .env("GIT_CONFIG_SYSTEM", "/dev/null")
2105 .env("GIT_AUTHOR_NAME", "Ada Lovelace")
2106 .env("GIT_AUTHOR_EMAIL", "ada@example.com")
2107 .env("GIT_COMMITTER_NAME", "Ada Lovelace")
2108 .env("GIT_COMMITTER_EMAIL", "ada@example.com")
2109 .env("GIT_AUTHOR_DATE", &date)
2110 .env("GIT_COMMITTER_DATE", &date)
2111 .output()
2112 .expect("git should be on PATH");
2113
2114 assert!(
2115 output.status.success(),
2116 "git {args:?} failed: {}",
2117 String::from_utf8_lossy(&output.stderr)
2118 );
2119 }
2120
2121 /// A data directory holding one empty bare repository, exactly as Steid creates it.
2122 ///
2123 /// The `TempDir` is returned because dropping it deletes the fixture.
2124 fn empty() -> (TempDir, DiskGitQuery) {
2125 let dir = TempDir::new().expect("temp dir");
2126 let query = DiskGitQuery::new(
2127 dir.path(),
2128 Arc::new(CatFilePool::new()),
2129 Arc::new(MergeCache::new()),
2130 );
2131 let repo = query.repo_path(&handle(), &repo_name());
2132
2133 std::fs::create_dir_all(repo.parent().expect("has a parent")).expect("create handle dir");
2134 git(
2135 dir.path(),
2136 FIRST_COMMIT,
2137 &[
2138 "init",
2139 "--bare",
2140 "--quiet",
2141 "--template=",
2142 "--initial-branch=main",
2143 "--",
2144 repo.to_str().expect("utf-8 fixture path"),
2145 ],
2146 );
2147
2148 (dir, query)
2149 }
2150
2151 /// The empty repository with three commits pushed into it, the way a real one fills
2152 /// up — a working copy and a push, rather than plumbing straight into the object
2153 /// store.
2154 fn populated() -> (TempDir, DiskGitQuery) {
2155 let (dir, query) = empty();
2156 let repo = query.repo_path(&handle(), &repo_name());
2157 let work = dir.path().join("work");
2158
2159 std::fs::create_dir_all(work.join("src/deep")).expect("create work tree");
2160 git(&work, FIRST_COMMIT, &["init", "--quiet", "-b", "main"]);
2161
2162 std::fs::write(work.join("README.md"), b"hello\n").expect("write");
2163 std::fs::write(work.join("with space.txt"), b"spaced\n").expect("write");
2164 std::fs::write(work.join("bin.dat"), BINARY).expect("write");
2165 std::fs::write(work.join("big.txt"), vec![b'x'; 100]).expect("write");
2166 std::fs::write(work.join("src/deep/file.rs"), b"fn main() {}\n").expect("write");
2167 std::os::unix::fs::symlink("README.md", work.join("link")).expect("symlink");
2168
2169 git(&work, FIRST_COMMIT, &["add", "-A"]);
2170 git(&work, FIRST_COMMIT, &["commit", "--quiet", "-m", "first"]);
2171
2172 std::fs::write(work.join("README.md"), b"hello again\n").expect("write");
2173 git(&work, SECOND_COMMIT, &["add", "-A"]);
2174 git(&work, SECOND_COMMIT, &["commit", "--quiet", "-m", "second"]);
2175
2176 git(
2177 &work,
2178 THIRD_COMMIT,
2179 &["commit", "--quiet", "--allow-empty", "-m", ODD_MESSAGE],
2180 );
2181
2182 git(
2183 &work,
2184 THIRD_COMMIT,
2185 &[
2186 "push",
2187 "--quiet",
2188 repo.to_str().expect("utf-8 fixture path"),
2189 "main",
2190 ],
2191 );
2192
2193 (dir, query)
2194 }
2195
2196 /// A listing keyed by name, so an assertion does not depend on an order the port
2197 /// explicitly does not promise.
2198 fn by_name(entries: Vec<TreeEntry>) -> HashMap<String, TreeEntry> {
2199 entries
2200 .into_iter()
2201 .map(|entry| (entry.name.clone(), entry))
2202 .collect()
2203 }
2204
2205 // --- ref snapshots ---------------------------------------------------------
2206
2207 /// The snapshot as a map, so an assertion does not depend on git's ordering.
2208 async fn snapshot(query: &DiskGitQuery) -> HashMap<String, String> {
2209 query
2210 .ref_snapshot(&handle(), &repo_name())
2211 .await
2212 .expect("should read")
2213 .into_iter()
2214 .map(|(name, id)| (name.as_str().to_owned(), id.as_str().to_owned()))
2215 .collect()
2216 }
2217
2218 #[tokio::test]
2219 async fn an_empty_repository_snapshots_to_nothing() {
2220 // Nothing pushed yet is not a failure — the first push diffs against this.
2221 let (_dir, query) = empty();
2222
2223 assert!(snapshot(&query).await.is_empty());
2224 }
2225
2226 #[tokio::test]
2227 async fn a_snapshot_names_refs_in_full_and_by_the_object_the_ref_itself_holds() {
2228 // An annotated tag reports the *tag object*, not the commit it peels to: what a
2229 // push changes is the ref, and re-annotating the same commit is a change.
2230 let (dir, query) = populated();
2231 let repo = query.repo_path(&handle(), &repo_name());
2232 let work = dir.path().join("work");
2233
2234 git(&work, THIRD_COMMIT, &["tag", "-a", "v0.1.0", "-m", "first"]);
2235 git(&work, THIRD_COMMIT, &["branch", "feat/x"]);
2236 git(
2237 &work,
2238 THIRD_COMMIT,
2239 &[
2240 "push",
2241 "--quiet",
2242 repo.to_str().expect("utf-8 fixture path"),
2243 "feat/x",
2244 "v0.1.0",
2245 ],
2246 );
2247
2248 let snapshot = snapshot(&query).await;
2249 let main = query
2250 .resolve(&handle(), &repo_name(), &rev("main"))
2251 .await
2252 .expect("should read")
2253 .expect("main resolves");
2254
2255 assert_eq!(snapshot.len(), 3);
2256 assert_eq!(snapshot.get("refs/heads/main"), Some(&main.to_string()));
2257 assert_eq!(snapshot.get("refs/heads/feat/x"), Some(&main.to_string()));
2258 assert_ne!(
2259 snapshot.get("refs/tags/v0.1.0"),
2260 Some(&main.to_string()),
2261 "an annotated tag is its own object"
2262 );
2263 }
2264
2265 #[tokio::test]
2266 async fn a_snapshot_taken_twice_around_a_push_shows_what_moved() {
2267 // The sequence the push path actually performs, end to end.
2268 let (dir, query) = populated();
2269 let repo = query.repo_path(&handle(), &repo_name());
2270 let work = dir.path().join("work");
2271
2272 let before = snapshot(&query).await;
2273
2274 std::fs::write(work.join("README.md"), b"hello once more\n").expect("write");
2275 git(&work, THIRD_COMMIT, &["add", "-A"]);
2276 git(&work, THIRD_COMMIT, &["commit", "--quiet", "-m", "fourth"]);
2277 git(
2278 &work,
2279 THIRD_COMMIT,
2280 &[
2281 "push",
2282 "--quiet",
2283 repo.to_str().expect("utf-8 fixture path"),
2284 "main",
2285 ],
2286 );
2287
2288 let after = snapshot(&query).await;
2289
2290 assert_eq!(before.len(), 1);
2291 assert_eq!(after.len(), 1);
2292 assert_ne!(before.get("refs/heads/main"), after.get("refs/heads/main"));
2293 }
2294
2295 // --- grep ------------------------------------------------------------------
2296
2297 async fn hits(query: &str, limit: usize) -> Vec<GrepHit> {
2298 let (_dir, query_port) = populated();
2299 let commit = query_port
2300 .resolve(&handle(), &repo_name(), &rev("main"))
2301 .await
2302 .expect("should read")
2303 .expect("main resolves");
2304
2305 query_port
2306 .grep(&handle(), &repo_name(), &commit, query, limit)
2307 .await
2308 .expect("should grep")
2309 }
2310
2311 #[tokio::test]
2312 async fn a_search_finds_the_line_it_matched() {
2313 let found = hits("fn main", 10).await;
2314
2315 assert_eq!(found.len(), 1);
2316 assert_eq!(found[0].path.as_str(), "src/deep/file.rs");
2317 assert_eq!(found[0].line, 1);
2318 assert_eq!(found[0].text, "fn main() {}");
2319 }
2320
2321 #[tokio::test]
2322 async fn a_search_that_matches_nothing_is_not_a_failure() {
2323 // `git grep` exits 1 here, which every other command in this module would treat
2324 // as a fault. This is the one exception, and this test is what pins it.
2325 assert_eq!(hits("nothing matches this", 10).await, Vec::new());
2326 }
2327
2328 #[tokio::test]
2329 async fn a_binary_file_is_never_reported() {
2330 // `bin.dat` contains 0x00 0x01 0xff 0xfe 0x80, so a byte-wise search would hit
2331 // it. `-I` is what keeps unreadable matches off the page.
2332 let found = hits("\u{fffd}", 10).await;
2333
2334 assert!(
2335 found.iter().all(|hit| hit.path.as_str() != "bin.dat"),
2336 "a binary file should never appear in results"
2337 );
2338 }
2339
2340 #[tokio::test]
2341 async fn a_search_is_a_fixed_string_not_a_pattern() {
2342 // `.` would match every line if this were a regular expression.
2343 assert_eq!(hits("hello.again", 10).await, Vec::new());
2344 }
2345
2346 #[tokio::test]
2347 async fn the_limit_bounds_what_comes_back() {
2348 // Every file in the fixture contains an `e` somewhere, so this is more than one
2349 // match without depending on how many.
2350 assert_eq!(hits("e", 2).await.len(), 2);
2351 }
2352
2353 // --- an empty repository ---------------------------------------------------
2354
2355 #[tokio::test]
2356 async fn an_empty_repository_has_no_default_branch() {
2357 // The distinction the port exists for: HEAD names `main`, but `main` has no
2358 // commits, so "nothing pushed yet" rather than a branch a page can browse.
2359 let (_dir, query) = empty();
2360
2361 assert_eq!(
2362 query
2363 .default_branch(&handle(), &repo_name())
2364 .await
2365 .expect("should read"),
2366 None
2367 );
2368 }
2369
2370 #[tokio::test]
2371 async fn nothing_resolves_in_an_empty_repository() {
2372 let (_dir, query) = empty();
2373
2374 for revision in ["main", "HEAD", "v1.0"] {
2375 assert_eq!(
2376 query
2377 .resolve(&handle(), &repo_name(), &rev(revision))
2378 .await
2379 .expect("should read"),
2380 None,
2381 "{revision} should not resolve"
2382 );
2383 }
2384 }
2385
2386 #[tokio::test]
2387 async fn an_empty_repository_lists_nothing_and_reads_nothing() {
2388 let (_dir, query) = empty();
2389
2390 assert_eq!(
2391 query
2392 .list_tree(&handle(), &repo_name(), &rev("main"), &RepoPath::root())
2393 .await
2394 .expect("should read"),
2395 None
2396 );
2397 assert_eq!(
2398 query
2399 .read_blob(
2400 &handle(),
2401 &repo_name(),
2402 &rev("main"),
2403 &path("README.md"),
2404 1024
2405 )
2406 .await
2407 .expect("should read"),
2408 None
2409 );
2410 }
2411
2412 #[tokio::test]
2413 async fn an_empty_repository_has_an_empty_log() {
2414 // `git log` is a fatal error here, and an empty list is what the port promises.
2415 let (_dir, query) = empty();
2416
2417 assert_eq!(
2418 query
2419 .log(&handle(), &repo_name(), &rev("main"), 0, 10)
2420 .await
2421 .expect("should read"),
2422 Vec::new()
2423 );
2424 }
2425
2426 // --- a missing repository is a failure, not a 404 ---------------------------
2427
2428 #[tokio::test]
2429 async fn a_repository_that_is_not_on_disk_is_an_error() {
2430 // A record with no directory is a fault to investigate, not a "no such branch".
2431 // Answering `Ok(None)` here would hide it behind a plausible-looking 404.
2432 let (_dir, query) = empty();
2433 let missing = RepoName::new("never-created").expect("valid repository name");
2434
2435 assert!(query.default_branch(&handle(), &missing).await.is_err());
2436 assert!(
2437 query
2438 .resolve(&handle(), &missing, &rev("main"))
2439 .await
2440 .is_err()
2441 );
2442 assert!(
2443 query
2444 .list_tree(&handle(), &missing, &rev("main"), &RepoPath::root())
2445 .await
2446 .is_err()
2447 );
2448 assert!(
2449 query
2450 .log(&handle(), &missing, &rev("main"), 0, 10)
2451 .await
2452 .is_err()
2453 );
2454 }
2455
2456 // --- default_branch and resolve --------------------------------------------
2457
2458 #[tokio::test]
2459 async fn a_repository_with_commits_reports_its_default_branch() {
2460 let (_dir, query) = populated();
2461
2462 assert_eq!(
2463 query
2464 .default_branch(&handle(), &repo_name())
2465 .await
2466 .expect("should read"),
2467 Some(RefName::from_trusted("main"))
2468 );
2469 }
2470
2471 #[tokio::test]
2472 async fn a_branch_and_head_resolve_to_the_same_commit() {
2473 let (_dir, query) = populated();
2474
2475 let main = query
2476 .resolve(&handle(), &repo_name(), &rev("main"))
2477 .await
2478 .expect("should read")
2479 .expect("main should resolve");
2480 let head = query
2481 .resolve(&handle(), &repo_name(), &rev("HEAD"))
2482 .await
2483 .expect("should read");
2484
2485 assert_eq!(head, Some(main));
2486 }
2487
2488 #[tokio::test]
2489 async fn a_commit_id_resolves_to_itself() {
2490 let (_dir, query) = populated();
2491
2492 let main = query
2493 .resolve(&handle(), &repo_name(), &rev("main"))
2494 .await
2495 .expect("should read")
2496 .expect("main should resolve");
2497
2498 assert_eq!(
2499 query
2500 .resolve(&handle(), &repo_name(), &rev(main.as_str()))
2501 .await
2502 .expect("should read"),
2503 Some(main)
2504 );
2505 }
2506
2507 #[tokio::test]
2508 async fn an_unknown_revision_resolves_to_nothing() {
2509 let (_dir, query) = populated();
2510
2511 assert_eq!(
2512 query
2513 .resolve(&handle(), &repo_name(), &rev("no-such-branch"))
2514 .await
2515 .expect("looking up a missing branch is not a failure"),
2516 None
2517 );
2518 }
2519
2520 // --- list_tree --------------------------------------------------------------
2521
2522 #[tokio::test]
2523 async fn the_root_lists_every_top_level_entry() {
2524 let (_dir, query) = populated();
2525
2526 let entries = by_name(
2527 query
2528 .list_tree(&handle(), &repo_name(), &rev("main"), &RepoPath::root())
2529 .await
2530 .expect("should read")
2531 .expect("the root is a directory"),
2532 );
2533
2534 let mut names: Vec<&str> = entries.keys().map(String::as_str).collect();
2535 names.sort_unstable();
2536 assert_eq!(
2537 names,
2538 vec![
2539 "README.md",
2540 "big.txt",
2541 "bin.dat",
2542 "link",
2543 "src",
2544 "with space.txt"
2545 ]
2546 );
2547 assert_eq!(entries["src"].kind, EntryKind::Tree);
2548 assert_eq!(entries["README.md"].kind, EntryKind::Blob);
2549 assert_eq!(
2550 entries["link"].kind,
2551 EntryKind::Symlink,
2552 "a symlink is its own kind, not a file"
2553 );
2554 }
2555
2556 #[tokio::test]
2557 async fn a_listing_carries_blob_sizes_but_not_tree_sizes() {
2558 let (_dir, query) = populated();
2559
2560 let entries = by_name(
2561 query
2562 .list_tree(&handle(), &repo_name(), &rev("main"), &RepoPath::root())
2563 .await
2564 .expect("should read")
2565 .expect("the root is a directory"),
2566 );
2567
2568 assert_eq!(entries["big.txt"].size, Some(100));
2569 assert_eq!(
2570 entries["src"].size, None,
2571 "a directory has no size a listing can show"
2572 );
2573 }
2574
2575 #[tokio::test]
2576 async fn a_filename_containing_a_space_survives_the_listing() {
2577 // The reason `-z` is not optional: split on whitespace and this name becomes two.
2578 let (_dir, query) = populated();
2579
2580 let entries = by_name(
2581 query
2582 .list_tree(&handle(), &repo_name(), &rev("main"), &RepoPath::root())
2583 .await
2584 .expect("should read")
2585 .expect("the root is a directory"),
2586 );
2587
2588 assert_eq!(entries["with space.txt"].kind, EntryKind::Blob);
2589 assert_eq!(entries["with space.txt"].size, Some(7));
2590 }
2591
2592 #[tokio::test]
2593 async fn a_nested_directory_lists_only_its_own_entries() {
2594 let (_dir, query) = populated();
2595
2596 let entries = query
2597 .list_tree(&handle(), &repo_name(), &rev("main"), &path("src"))
2598 .await
2599 .expect("should read")
2600 .expect("src is a directory");
2601
2602 assert_eq!(entries.len(), 1);
2603 assert_eq!(entries[0].name, "deep", "names are entry names, not paths");
2604 assert_eq!(entries[0].kind, EntryKind::Tree);
2605
2606 let deeper = query
2607 .list_tree(&handle(), &repo_name(), &rev("main"), &path("src/deep"))
2608 .await
2609 .expect("should read")
2610 .expect("src/deep is a directory");
2611
2612 assert_eq!(deeper.len(), 1);
2613 assert_eq!(deeper[0].name, "file.rs");
2614 }
2615
2616 #[tokio::test]
2617 async fn listing_a_file_as_a_directory_finds_nothing() {
2618 // git calls this a fatal error; to a visitor it is a wrong URL.
2619 let (_dir, query) = populated();
2620
2621 assert_eq!(
2622 query
2623 .list_tree(&handle(), &repo_name(), &rev("main"), &path("README.md"))
2624 .await
2625 .expect("a file is not a failure"),
2626 None
2627 );
2628 }
2629
2630 #[tokio::test]
2631 async fn listing_a_path_that_is_not_there_finds_nothing() {
2632 let (_dir, query) = populated();
2633
2634 for missing in ["nope", "src/nope", "README.md/nope"] {
2635 assert_eq!(
2636 query
2637 .list_tree(&handle(), &repo_name(), &rev("main"), &path(missing))
2638 .await
2639 .expect("should read"),
2640 None,
2641 "{missing} should not be found"
2642 );
2643 }
2644 }
2645
2646 #[tokio::test]
2647 async fn listing_at_an_unknown_revision_finds_nothing() {
2648 let (_dir, query) = populated();
2649
2650 assert_eq!(
2651 query
2652 .list_tree(
2653 &handle(),
2654 &repo_name(),
2655 &rev("no-such-branch"),
2656 &RepoPath::root()
2657 )
2658 .await
2659 .expect("should read"),
2660 None
2661 );
2662 }
2663
2664 #[tokio::test]
2665 async fn a_listing_reflects_the_revision_it_was_asked_for() {
2666 // Proves the revision is actually used rather than HEAD being read every time.
2667 let (_dir, query) = populated();
2668
2669 let first = query
2670 .log(&handle(), &repo_name(), &rev("main"), 0, 10)
2671 .await
2672 .expect("should read")
2673 .last()
2674 .expect("three commits")
2675 .id
2676 .clone();
2677
2678 let old = query
2679 .read_blob(
2680 &handle(),
2681 &repo_name(),
2682 &rev(first.as_str()),
2683 &path("README.md"),
2684 1024,
2685 )
2686 .await
2687 .expect("should read")
2688 .expect("README existed in the first commit");
2689
2690 assert_eq!(old.content.as_deref(), Some(b"hello\n".as_slice()));
2691 }
2692
2693 // --- read_blob --------------------------------------------------------------
2694
2695 #[tokio::test]
2696 async fn a_file_is_read_with_its_size_and_content() {
2697 let (_dir, query) = populated();
2698
2699 let blob = query
2700 .read_blob(
2701 &handle(),
2702 &repo_name(),
2703 &rev("main"),
2704 &path("README.md"),
2705 1024,
2706 )
2707 .await
2708 .expect("should read")
2709 .expect("README.md is a file");
2710
2711 assert_eq!(blob.size, 12);
2712 assert_eq!(blob.content.as_deref(), Some(b"hello again\n".as_slice()));
2713 }
2714
2715 #[tokio::test]
2716 async fn a_binary_file_survives_intact() {
2717 // Nothing in this adapter may assume UTF-8: a lossy conversion here would swap
2718 // bytes for replacement characters and quietly corrupt every download.
2719 let (_dir, query) = populated();
2720
2721 let blob = query
2722 .read_blob(
2723 &handle(),
2724 &repo_name(),
2725 &rev("main"),
2726 &path("bin.dat"),
2727 1024,
2728 )
2729 .await
2730 .expect("should read")
2731 .expect("bin.dat is a file");
2732
2733 assert_eq!(blob.size, BINARY.len() as u64);
2734 assert_eq!(blob.content.as_deref(), Some(BINARY));
2735 }
2736
2737 #[tokio::test]
2738 async fn a_file_over_the_cap_reports_its_size_without_its_content() {
2739 let (_dir, query) = populated();
2740
2741 let blob = query
2742 .read_blob(&handle(), &repo_name(), &rev("main"), &path("big.txt"), 10)
2743 .await
2744 .expect("should read")
2745 .expect("big.txt is a file");
2746
2747 assert_eq!(blob.size, 100, "the page still says how big it is");
2748 assert_eq!(blob.content, None);
2749 }
2750
2751 #[tokio::test]
2752 async fn a_file_exactly_at_the_cap_is_still_read() {
2753 let (_dir, query) = populated();
2754
2755 let blob = query
2756 .read_blob(&handle(), &repo_name(), &rev("main"), &path("big.txt"), 100)
2757 .await
2758 .expect("should read")
2759 .expect("big.txt is a file");
2760
2761 assert_eq!(blob.content.map(|content| content.len()), Some(100));
2762 }
2763
2764 #[tokio::test]
2765 async fn a_file_with_a_space_in_its_name_can_be_read() {
2766 let (_dir, query) = populated();
2767
2768 let blob = query
2769 .read_blob(
2770 &handle(),
2771 &repo_name(),
2772 &rev("main"),
2773 &path("with space.txt"),
2774 1024,
2775 )
2776 .await
2777 .expect("should read")
2778 .expect("the file is there");
2779
2780 assert_eq!(blob.content.as_deref(), Some(b"spaced\n".as_slice()));
2781 }
2782
2783 #[tokio::test]
2784 async fn reading_a_directory_as_a_file_finds_nothing() {
2785 let (_dir, query) = populated();
2786
2787 for directory in ["src", "src/deep", ""] {
2788 assert_eq!(
2789 query
2790 .read_blob(
2791 &handle(),
2792 &repo_name(),
2793 &rev("main"),
2794 &path(directory),
2795 1024
2796 )
2797 .await
2798 .expect("a directory is not a failure"),
2799 None,
2800 "{directory:?} is a directory"
2801 );
2802 }
2803 }
2804
2805 #[tokio::test]
2806 async fn reading_a_path_that_is_not_there_finds_nothing() {
2807 let (_dir, query) = populated();
2808
2809 for missing in ["nope.txt", "src/nope.txt", "README.md/nope"] {
2810 assert_eq!(
2811 query
2812 .read_blob(&handle(), &repo_name(), &rev("main"), &path(missing), 1024)
2813 .await
2814 .expect("should read"),
2815 None,
2816 "{missing} should not be found"
2817 );
2818 }
2819 }
2820
2821 #[tokio::test]
2822 async fn a_blobs_id_matches_the_listing() {
2823 // Two commands, one object: if they disagree, one of the two parsers is wrong.
2824 let (_dir, query) = populated();
2825
2826 let entries = by_name(
2827 query
2828 .list_tree(&handle(), &repo_name(), &rev("main"), &RepoPath::root())
2829 .await
2830 .expect("should read")
2831 .expect("the root is a directory"),
2832 );
2833 let blob = query
2834 .read_blob(
2835 &handle(),
2836 &repo_name(),
2837 &rev("main"),
2838 &path("README.md"),
2839 1024,
2840 )
2841 .await
2842 .expect("should read")
2843 .expect("README.md is a file");
2844
2845 assert_eq!(blob.id, entries["README.md"].id);
2846 assert_eq!(Some(blob.size), entries["README.md"].size);
2847 }
2848
2849 #[tokio::test]
2850 async fn a_symlink_reads_as_its_target_path() {
2851 // The object store cannot tell a symlink from a file — both are blobs — and its
2852 // content is the path it points at. Showing that is more use than a blank page,
2853 // so this is a deliberate choice rather than an oversight.
2854 let (_dir, query) = populated();
2855
2856 let blob = query
2857 .read_blob(&handle(), &repo_name(), &rev("main"), &path("link"), 1024)
2858 .await
2859 .expect("should read")
2860 .expect("a symlink is readable");
2861
2862 assert_eq!(blob.content.as_deref(), Some(b"README.md".as_slice()));
2863 }
2864
2865 // --- log ---------------------------------------------------------------------
2866
2867 #[tokio::test]
2868 async fn the_log_is_newest_first() {
2869 let (_dir, query) = populated();
2870
2871 let commits = query
2872 .log(&handle(), &repo_name(), &rev("main"), 0, 10)
2873 .await
2874 .expect("should read");
2875
2876 assert_eq!(commits.len(), 3);
2877 assert_eq!(
2878 commits
2879 .iter()
2880 .map(|commit| commit.summary.as_str())
2881 .collect::<Vec<_>>(),
2882 vec!["third: 'quotes', \"doubles\" | pipes", "second", "first"]
2883 );
2884 }
2885
2886 #[tokio::test]
2887 async fn the_second_page_of_a_log_starts_where_the_first_ended() {
2888 let (_dir, query) = populated();
2889
2890 let first = query
2891 .log(&handle(), &repo_name(), &rev("main"), 0, 2)
2892 .await
2893 .expect("should read");
2894 let second = query
2895 .log(&handle(), &repo_name(), &rev("main"), 2, 2)
2896 .await
2897 .expect("should read");
2898
2899 assert_eq!(first.len(), 2);
2900 assert_eq!(second.len(), 1, "one commit left over");
2901 assert_eq!(second[0].summary, "first");
2902 assert!(
2903 !first.iter().any(|commit| commit.id == second[0].id),
2904 "the pages do not overlap"
2905 );
2906 }
2907
2908 #[tokio::test]
2909 async fn an_offset_past_the_end_of_a_log_is_an_empty_page() {
2910 // What a bookmarked deep page becomes after a branch is rewritten. The page
2911 // clamps before it asks, but the port must not fail if one gets through.
2912 let (_dir, query) = populated();
2913
2914 let commits = query
2915 .log(&handle(), &repo_name(), &rev("main"), 500, 10)
2916 .await
2917 .expect("should read");
2918
2919 assert!(commits.is_empty());
2920 }
2921
2922 #[tokio::test]
2923 async fn the_log_stops_at_the_limit() {
2924 let (_dir, query) = populated();
2925
2926 let commits = query
2927 .log(&handle(), &repo_name(), &rev("main"), 0, 2)
2928 .await
2929 .expect("should read");
2930
2931 assert_eq!(commits.len(), 2);
2932 assert_eq!(commits[0].summary, "third: 'quotes', \"doubles\" | pipes");
2933
2934 assert!(
2935 query
2936 .log(&handle(), &repo_name(), &rev("main"), 0, 0)
2937 .await
2938 .expect("should read")
2939 .is_empty()
2940 );
2941 }
2942
2943 #[tokio::test]
2944 async fn a_commit_message_body_does_not_leak_into_the_summary() {
2945 // The message has a blank line and two body lines. A parser that split the
2946 // stream on newlines would report "body line one" as a separate commit.
2947 let (_dir, query) = populated();
2948
2949 let commits = query
2950 .log(&handle(), &repo_name(), &rev("main"), 0, 10)
2951 .await
2952 .expect("should read");
2953
2954 assert_eq!(commits.len(), 3, "three commits, not five");
2955 assert!(
2956 !commits[0].summary.contains("body line"),
2957 "got: {:?}",
2958 commits[0].summary
2959 );
2960 }
2961
2962 #[tokio::test]
2963 async fn a_log_entry_carries_its_author_and_time() {
2964 let (_dir, query) = populated();
2965
2966 let commits = query
2967 .log(&handle(), &repo_name(), &rev("main"), 0, 10)
2968 .await
2969 .expect("should read");
2970
2971 assert_eq!(commits[0].author_name, "Ada Lovelace");
2972 assert_eq!(
2973 commits[0].committed_at,
2974 UNIX_EPOCH + Duration::from_secs(THIRD_COMMIT as u64)
2975 );
2976 assert_eq!(
2977 commits[2].committed_at,
2978 UNIX_EPOCH + Duration::from_secs(FIRST_COMMIT as u64)
2979 );
2980 }
2981
2982 #[tokio::test]
2983 async fn a_log_entry_id_is_the_commit_the_revision_resolves_to() {
2984 let (_dir, query) = populated();
2985
2986 let head = query
2987 .resolve(&handle(), &repo_name(), &rev("main"))
2988 .await
2989 .expect("should read")
2990 .expect("main resolves");
2991 let commits = query
2992 .log(&handle(), &repo_name(), &rev("main"), 0, 1)
2993 .await
2994 .expect("should read");
2995
2996 assert_eq!(commits[0].id, head);
2997 }
2998
2999 #[tokio::test]
3000 async fn the_log_of_an_unknown_revision_is_empty_rather_than_a_failure() {
3001 let (_dir, query) = populated();
3002
3003 assert_eq!(
3004 query
3005 .log(&handle(), &repo_name(), &rev("no-such-branch"), 0, 10)
3006 .await
3007 .expect("an unknown branch is not a failure"),
3008 Vec::new()
3009 );
3010 }
3011
3012 #[tokio::test]
3013 async fn a_log_can_start_from_an_older_commit() {
3014 let (_dir, query) = populated();
3015
3016 let all = query
3017 .log(&handle(), &repo_name(), &rev("main"), 0, 10)
3018 .await
3019 .expect("should read");
3020 let from_second = query
3021 .log(&handle(), &repo_name(), &rev(all[1].id.as_str()), 0, 10)
3022 .await
3023 .expect("should read");
3024
3025 assert_eq!(from_second.len(), 2, "history behind the second commit");
3026 assert_eq!(from_second[0].id, all[1].id);
3027 }
3028
3029 // --- list_refs ---------------------------------------------------------------
3030
3031 /// The populated repository with a second branch and two tags pushed into it — one
3032 /// lightweight, one annotated, because they are different objects and the switcher
3033 /// must not care.
3034 fn with_refs() -> (TempDir, DiskGitQuery) {
3035 let (dir, query) = populated();
3036 let repo = query.repo_path(&handle(), &repo_name());
3037 let work = dir.path().join("work");
3038 let target = repo.to_str().expect("utf-8 fixture path").to_owned();
3039
3040 // A slash in the name, because that is what makes a ref name interesting: it is
3041 // the case the `/-/` separator in the URL exists for.
3042 git(&work, THIRD_COMMIT, &["branch", "feature/login"]);
3043 git(&work, THIRD_COMMIT, &["tag", "v1.0"]);
3044 git(
3045 &work,
3046 THIRD_COMMIT,
3047 &["tag", "-a", "v2.0", "-m", "second release"],
3048 );
3049 git(
3050 &work,
3051 THIRD_COMMIT,
3052 &["push", "--quiet", &target, "feature/login"],
3053 );
3054 git(&work, THIRD_COMMIT, &["push", "--quiet", &target, "--tags"]);
3055
3056 (dir, query)
3057 }
3058
3059 fn named(refs: &[GitRef], kind: RefKind) -> Vec<String> {
3060 let mut names: Vec<String> = refs
3061 .iter()
3062 .filter(|git_ref| git_ref.kind == kind)
3063 .map(|git_ref| git_ref.name.to_string())
3064 .collect();
3065
3066 // The port promises no order, so a test that asserted one would be asserting
3067 // something the adapter is free to change.
3068 names.sort();
3069 names
3070 }
3071
3072 #[tokio::test]
3073 async fn branches_and_tags_are_listed_and_told_apart() {
3074 let (_dir, query) = with_refs();
3075
3076 let refs = query
3077 .list_refs(&handle(), &repo_name())
3078 .await
3079 .expect("should read");
3080
3081 assert_eq!(
3082 named(&refs, RefKind::Branch),
3083 vec!["feature/login".to_owned(), "main".to_owned()]
3084 );
3085 // An annotated tag points at a tag object rather than a commit, and a
3086 // lightweight one points straight at the commit. Both are tags.
3087 assert_eq!(
3088 named(&refs, RefKind::Tag),
3089 vec!["v1.0".to_owned(), "v2.0".to_owned()]
3090 );
3091 }
3092
3093 #[tokio::test]
3094 async fn a_repository_with_one_branch_lists_just_it() {
3095 let (_dir, query) = populated();
3096
3097 let refs = query
3098 .list_refs(&handle(), &repo_name())
3099 .await
3100 .expect("should read");
3101
3102 assert_eq!(refs.len(), 1);
3103 assert_eq!(refs[0].name.as_str(), "main");
3104 assert_eq!(refs[0].kind, RefKind::Branch);
3105 }
3106
3107 #[tokio::test]
3108 async fn an_empty_repository_lists_no_refs() {
3109 // HEAD names `main`, but no ref exists, so there is nothing to switch to. An
3110 // empty list rather than an error: nothing pushed yet is not a failure.
3111 let (_dir, query) = empty();
3112
3113 assert_eq!(
3114 query
3115 .list_refs(&handle(), &repo_name())
3116 .await
3117 .expect("should read"),
3118 Vec::new()
3119 );
3120 }
3121
3122 #[tokio::test]
3123 async fn listing_refs_of_a_repository_that_is_not_on_disk_is_an_error() {
3124 let (_dir, query) = empty();
3125 let missing = RepoName::new("never-created").expect("valid repository name");
3126
3127 assert!(query.list_refs(&handle(), &missing).await.is_err());
3128 }
3129
3130 #[test]
3131 fn refs_are_parsed_from_nul_terminated_records() {
3132 // git ends each record with a newline the format cannot suppress, so it arrives
3133 // in front of the next record's name. Anything outside the two namespaces is
3134 // dropped rather than guessed at.
3135 let stdout = b"refs/heads/main\0\nrefs/tags/v1.0\0\nrefs/pull/7/head\0\n";
3136 let refs = parse_refs(stdout);
3137
3138 assert_eq!(refs.len(), 2);
3139 assert_eq!(refs[0].name.as_str(), "main");
3140 assert_eq!(refs[0].kind, RefKind::Branch);
3141 assert_eq!(refs[1].name.as_str(), "v1.0");
3142 assert_eq!(refs[1].kind, RefKind::Tag);
3143 }
3144
3145 #[test]
3146 fn nothing_is_parsed_from_an_empty_listing() {
3147 assert!(parse_refs(b"").is_empty());
3148 }
3149
3150 // --- count_commits ------------------------------------------------------------
3151
3152 #[tokio::test]
3153 async fn commits_are_counted_from_the_revision_asked_about() {
3154 let (_dir, query) = populated();
3155
3156 assert_eq!(
3157 query
3158 .count_commits(&handle(), &repo_name(), &rev("main"))
3159 .await
3160 .expect("should count"),
3161 3
3162 );
3163 }
3164
3165 #[tokio::test]
3166 async fn a_revision_with_no_commits_counts_zero_rather_than_failing() {
3167 // Both spellings of "nothing here": an empty repository, and a branch that is
3168 // not there. `rev-list` is fatal for each, and a page asking how big a
3169 // repository is wants a number.
3170 let (_dir, empty_query) = empty();
3171 assert_eq!(
3172 empty_query
3173 .count_commits(&handle(), &repo_name(), &rev("main"))
3174 .await
3175 .expect("should count"),
3176 0
3177 );
3178
3179 let (_dir, query) = populated();
3180 assert_eq!(
3181 query
3182 .count_commits(&handle(), &repo_name(), &rev("no-such-branch"))
3183 .await
3184 .expect("should count"),
3185 0
3186 );
3187 }
3188
3189 #[tokio::test]
3190 async fn counting_a_repository_that_is_not_on_disk_is_an_error() {
3191 // Same rule as everywhere else here: absent from disk is a fault, not a zero.
3192 let (_dir, query) = empty();
3193 let missing = RepoName::new("gone").expect("valid repository name");
3194
3195 assert!(
3196 query
3197 .count_commits(&handle(), &missing, &rev("main"))
3198 .await
3199 .is_err()
3200 );
3201 }
3202
3203 // --- latest_tag ---------------------------------------------------------------
3204
3205 /// The populated repository with two annotated tags whose dates disagree with their
3206 /// names, so a test can tell "newest" from "last alphabetically".
3207 fn with_dated_tags() -> (TempDir, DiskGitQuery) {
3208 let (dir, query) = populated();
3209 let repo = query.repo_path(&handle(), &repo_name());
3210 let work = dir.path().join("work");
3211 let target = repo.to_str().expect("utf-8 fixture path").to_owned();
3212
3213 git(&work, FIRST_COMMIT, &["tag", "-a", "v1.0", "-m", "first"]);
3214 // Made later but named lower: sorting by name would pick `v1.0`.
3215 git(
3216 &work,
3217 THIRD_COMMIT,
3218 &["tag", "-a", "v0.9", "-m", "backport"],
3219 );
3220 git(&work, THIRD_COMMIT, &["push", "--quiet", &target, "--tags"]);
3221
3222 (dir, query)
3223 }
3224
3225 #[tokio::test]
3226 async fn the_latest_tag_is_the_newest_one_not_the_last_one_alphabetically() {
3227 let (_dir, query) = with_dated_tags();
3228
3229 let tag = query
3230 .latest_tag(&handle(), &repo_name())
3231 .await
3232 .expect("should read")
3233 .expect("a tag");
3234
3235 assert_eq!(tag.name.as_str(), "v0.9");
3236 assert_eq!(tag.created_at, unix_time(THIRD_COMMIT));
3237 }
3238
3239 #[tokio::test]
3240 async fn a_lightweight_tag_is_dated_by_the_commit_it_points_at() {
3241 // It has no date of its own, and `creatordate` is what fills that in.
3242 let (dir, query) = populated();
3243 let repo = query.repo_path(&handle(), &repo_name());
3244 let work = dir.path().join("work");
3245 let target = repo.to_str().expect("utf-8 fixture path").to_owned();
3246
3247 git(&work, THIRD_COMMIT, &["tag", "v1.0"]);
3248 git(&work, THIRD_COMMIT, &["push", "--quiet", &target, "--tags"]);
3249
3250 let tag = query
3251 .latest_tag(&handle(), &repo_name())
3252 .await
3253 .expect("should read")
3254 .expect("a tag");
3255
3256 assert_eq!(tag.name.as_str(), "v1.0");
3257 assert_eq!(tag.created_at, unix_time(THIRD_COMMIT));
3258 }
3259
3260 #[tokio::test]
3261 async fn a_repository_with_no_tags_has_no_latest_tag() {
3262 let (_dir, query) = populated();
3263 assert_eq!(
3264 query
3265 .latest_tag(&handle(), &repo_name())
3266 .await
3267 .expect("should read"),
3268 None
3269 );
3270
3271 let (_dir, empty_query) = empty();
3272 assert_eq!(
3273 empty_query
3274 .latest_tag(&handle(), &repo_name())
3275 .await
3276 .expect("should read"),
3277 None
3278 );
3279 }
3280
3281 #[test]
3282 fn a_tag_record_is_parsed_past_the_trailing_newline() {
3283 // `for-each-ref` ends every record with a newline the format cannot suppress,
3284 // exactly as it does for `parse_refs`.
3285 let tag = parse_latest_tag(b"refs/tags/v1.0\x001700000000\x00\n").expect("a tag");
3286
3287 assert_eq!(tag.name.as_str(), "v1.0");
3288 assert_eq!(tag.created_at, unix_time(1_700_000_000));
3289 }
3290
3291 #[test]
3292 fn nothing_is_parsed_from_an_empty_tag_listing() {
3293 assert_eq!(parse_latest_tag(b""), None);
3294 // A ref outside the tags namespace is not a tag, whatever asked for it.
3295 assert_eq!(
3296 parse_latest_tag(b"refs/heads/main\x001700000000\x00\n"),
3297 None
3298 );
3299 }
3300
3301 // --- branches and tags ---------------------------------------------------------
3302
3303 /// The populated repository with two more branches, each left at an older commit so
3304 /// the three tips carry three different dates — otherwise "newest first" is not
3305 /// something a test can see.
3306 fn with_branches() -> (TempDir, DiskGitQuery) {
3307 let (dir, query) = populated();
3308 let repo = query.repo_path(&handle(), &repo_name());
3309 let work = dir.path().join("work");
3310 let target = repo.to_str().expect("utf-8 fixture path").to_owned();
3311
3312 git(&work, THIRD_COMMIT, &["branch", "stale", "main~2"]);
3313 // A slash in the name, because that is the case the `/-/` separator exists for.
3314 git(&work, THIRD_COMMIT, &["branch", "feature/login", "main~1"]);
3315 git(
3316 &work,
3317 THIRD_COMMIT,
3318 &["push", "--quiet", &target, "stale", "feature/login"],
3319 );
3320
3321 (dir, query)
3322 }
3323
3324 /// The populated repository with one lightweight tag and two annotated ones, made
3325 /// on three different dates so ordering and the annotated/lightweight split can be
3326 /// asserted together.
3327 fn with_mixed_tags() -> (TempDir, DiskGitQuery) {
3328 let (dir, query) = populated();
3329 let repo = query.repo_path(&handle(), &repo_name());
3330 let work = dir.path().join("work");
3331 let target = repo.to_str().expect("utf-8 fixture path").to_owned();
3332
3333 // Lightweight: no object of its own, so its date is the commit's.
3334 git(&work, FIRST_COMMIT, &["tag", "v0.5", "main~2"]);
3335 git(
3336 &work,
3337 SECOND_COMMIT,
3338 &["tag", "-a", "v1.0", "-m", "first release"],
3339 );
3340 git(
3341 &work,
3342 THIRD_COMMIT,
3343 &["tag", "-a", "v2.0", "-m", "second release\n\nnotes below"],
3344 );
3345 git(&work, THIRD_COMMIT, &["push", "--quiet", &target, "--tags"]);
3346
3347 (dir, query)
3348 }
3349
3350 #[tokio::test]
3351 async fn branches_are_newest_first_with_the_default_marked() {
3352 let (_dir, query) = with_branches();
3353
3354 let rows = query
3355 .branches(&handle(), &repo_name())
3356 .await
3357 .expect("should read");
3358
3359 assert_eq!(
3360 rows.iter().map(|row| row.name.as_str()).collect::<Vec<_>>(),
3361 vec!["main", "feature/login", "stale"]
3362 );
3363 // `%(HEAD)` marks exactly one branch, and it is the one a bare repository's
3364 // HEAD names — which is what the page pins to the top.
3365 assert_eq!(
3366 rows.iter()
3367 .filter(|row| row.is_default)
3368 .map(|row| row.name.as_str())
3369 .collect::<Vec<_>>(),
3370 vec!["main"]
3371 );
3372 }
3373
3374 #[tokio::test]
3375 async fn a_branch_row_carries_its_tip_commit() {
3376 let (_dir, query) = with_branches();
3377
3378 let rows = query
3379 .branches(&handle(), &repo_name())
3380 .await
3381 .expect("should read");
3382
3383 let main = rows.first().expect("main is first");
3384
3385 // The subject only, from a message whose body would leak into it if the format
3386 // were read line-wise.
3387 assert_eq!(main.summary, "third: 'quotes', \"doubles\" | pipes");
3388 assert_eq!(main.committed_at, unix_time(THIRD_COMMIT));
3389 assert_eq!(main.commit.as_str().len(), 40);
3390
3391 let stale = rows.last().expect("stale is last");
3392 assert_eq!(stale.summary, "first");
3393 assert_eq!(stale.committed_at, unix_time(FIRST_COMMIT));
3394 }
3395
3396 #[tokio::test]
3397 async fn an_empty_repository_has_no_branches() {
3398 // The same answer `list_refs` gives, and for the same reason: nothing pushed
3399 // yet is not a failure. It is also how the page knows to show the push snippet.
3400 let (_dir, query) = empty();
3401
3402 assert_eq!(
3403 query
3404 .branches(&handle(), &repo_name())
3405 .await
3406 .expect("should read"),
3407 Vec::new()
3408 );
3409 }
3410
3411 #[tokio::test]
3412 async fn tags_are_newest_first_and_only_annotated_ones_carry_a_message() {
3413 let (_dir, query) = with_mixed_tags();
3414
3415 let rows = query
3416 .tags(&handle(), &repo_name())
3417 .await
3418 .expect("should read");
3419
3420 assert_eq!(
3421 rows.iter().map(|row| row.name.as_str()).collect::<Vec<_>>(),
3422 vec!["v2.0", "v1.0", "v0.5"]
3423 );
3424
3425 let newest = &rows[0];
3426 assert!(newest.annotated);
3427 // The subject of the tag's own message, not its body.
3428 assert_eq!(newest.message.as_deref(), Some("second release"));
3429 assert_eq!(newest.created_at, unix_time(THIRD_COMMIT));
3430
3431 let lightweight = &rows[2];
3432 assert!(!lightweight.annotated);
3433 // A lightweight tag has no message of its own; the commit's subject is the
3434 // commit's, and reporting it would invent one.
3435 assert_eq!(lightweight.message, None);
3436 assert_eq!(lightweight.created_at, unix_time(FIRST_COMMIT));
3437 }
3438
3439 #[tokio::test]
3440 async fn an_annotated_tag_reports_the_commit_it_peels_to() {
3441 // Its `objectname` is the tag object, which is not what a visitor browses.
3442 let (_dir, query) = with_mixed_tags();
3443
3444 let tip = query
3445 .branches(&handle(), &repo_name())
3446 .await
3447 .expect("should read")
3448 .into_iter()
3449 .find(|row| row.name.as_str() == "main")
3450 .expect("main");
3451
3452 let annotated = query
3453 .tags(&handle(), &repo_name())
3454 .await
3455 .expect("should read")
3456 .into_iter()
3457 .find(|row| row.name.as_str() == "v1.0")
3458 .expect("v1.0");
3459
3460 assert_eq!(annotated.commit, tip.commit);
3461 }
3462
3463 #[tokio::test]
3464 async fn a_repository_with_no_tags_lists_none() {
3465 let (_dir, query) = populated();
3466 assert_eq!(
3467 query
3468 .tags(&handle(), &repo_name())
3469 .await
3470 .expect("should read"),
3471 Vec::new()
3472 );
3473
3474 let (_dir, empty_query) = empty();
3475 assert_eq!(
3476 empty_query
3477 .tags(&handle(), &repo_name())
3478 .await
3479 .expect("should read"),
3480 Vec::new()
3481 );
3482 }
3483
3484 #[tokio::test]
3485 async fn listing_rows_of_a_repository_that_is_not_on_disk_is_an_error() {
3486 let (_dir, query) = empty();
3487 let missing = RepoName::new("never-created").expect("valid repository name");
3488
3489 assert!(query.branches(&handle(), &missing).await.is_err());
3490 assert!(query.tags(&handle(), &missing).await.is_err());
3491 }
3492
3493 #[test]
3494 fn branch_records_survive_the_newline_git_puts_between_them() {
3495 let rows = parse_branches(
3496 b"refs/heads/main\x00*\x00aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\x001700000000\x00first\x00\nrefs/heads/side\x00 \x00bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\x001700000100\x00second\x00\n",
3497 )
3498 .expect("should parse");
3499
3500 assert_eq!(rows.len(), 2);
3501 assert!(rows[0].is_default);
3502 assert_eq!(rows[0].summary, "first");
3503 // The newline in front of `refs/heads/side` is git's record separator, not part
3504 // of the name.
3505 assert_eq!(rows[1].name.as_str(), "side");
3506 assert!(!rows[1].is_default);
3507 assert_eq!(rows[1].committed_at, unix_time(1_700_000_100));
3508 }
3509
3510 #[test]
3511 fn a_lightweight_tags_empty_peel_does_not_shift_the_fields_after_it() {
3512 // The reason `ref_fields` keeps empty fields: filtering them would read this
3513 // record's date as its commit id.
3514 let rows = parse_tags(
3515 b"refs/tags/v1.0\x00commit\x00aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\x00\x001700000000\x00a commit subject\x00\n",
3516 )
3517 .expect("should parse");
3518
3519 assert_eq!(rows.len(), 1);
3520 assert_eq!(rows[0].name.as_str(), "v1.0");
3521 assert_eq!(rows[0].commit.as_str(), "a".repeat(40));
3522 assert!(!rows[0].annotated);
3523 assert_eq!(rows[0].message, None);
3524 assert_eq!(rows[0].created_at, unix_time(1_700_000_000));
3525 }
3526
3527 #[test]
3528 fn nothing_is_parsed_from_an_empty_row_listing() {
3529 assert_eq!(parse_branches(b"").expect("should parse"), Vec::new());
3530 assert_eq!(parse_tags(b"").expect("should parse"), Vec::new());
3531 }
3532
3533 #[test]
3534 fn a_record_with_the_wrong_number_of_fields_is_a_fault() {
3535 // Skipping a ref Steid cannot link to is right; misreading git's output is not.
3536 assert!(parse_branches(b"refs/heads/main\x00*\x00\n").is_err());
3537 }
3538
3539 // --- helpers ------------------------------------------------------------------
3540
3541 #[tokio::test]
3542 async fn repo_path_lands_under_the_data_directory() {
3543 let query = DiskGitQuery::new(
3544 "/data",
3545 Arc::new(CatFilePool::new()),
3546 Arc::new(MergeCache::new()),
3547 );
3548
3549 assert_eq!(
3550 query.repo_path(&handle(), &repo_name()),
3551 PathBuf::from("/data/jamesgill/steid.git")
3552 );
3553 }
3554
3555 #[test]
3556 fn a_pre_epoch_commit_time_does_not_panic() {
3557 // git will hand back a negative `%ct` for an imported history, and
3558 // `UNIX_EPOCH + Duration` cannot represent it.
3559 assert!(unix_time(-1) < UNIX_EPOCH);
3560 assert_eq!(unix_time(0), UNIX_EPOCH);
3561 }
3562
3563 #[tokio::test]
3564 async fn a_read_that_exceeds_its_limit_is_a_timeout_not_a_fault() {
3565 let (_dir, repo) = fixture_repo_for_timeout().await;
3566 let error = run_within(&repo, ["rev-parse", "HEAD"], Duration::ZERO)
3567 .await
3568 .expect_err("a zero limit cannot be met");
3569 assert!(error.is_timeout(), "{error}");
3570 }
3571
3572 /// A bare repository with nothing in it: `rev-parse` failing is not the point, the
3573 /// process being cut off before it can answer is.
3574 async fn fixture_repo_for_timeout() -> (TempDir, std::path::PathBuf) {
3575 let dir = TempDir::new().unwrap();
3576 let repo = dir.path().join("t.git");
3577 let status = git_command()
3578 .args(["init", "--bare", "-q"])
3579 .arg(&repo)
3580 .status()
3581 .await
3582 .unwrap();
3583 assert!(status.success());
3584 (dir, repo)
3585 }
3586
3587 // --- commits, diffs and comparisons ----------------------------------------
3588
3589 /// A repository with the shapes a diff parser has to survive: a rename, a binary
3590 /// file, a file added, a file deleted — plus a second branch and an unrelated
3591 /// history, which is what compare needs.
3592 fn with_history() -> (TempDir, DiskGitQuery) {
3593 let (dir, query) = empty();
3594 let repo = query.repo_path(&handle(), &repo_name());
3595 let work = dir.path().join("work");
3596
3597 std::fs::create_dir_all(work.join("src")).expect("create work tree");
3598 git(&work, FIRST_COMMIT, &["init", "--quiet", "-b", "main"]);
3599
3600 std::fs::write(work.join("src/a.txt"), b"aaa\nbbb\nccc\nddd\neee\n").expect("write");
3601 std::fs::write(work.join("gone.txt"), b"going\n").expect("write");
3602 std::fs::write(work.join("logo.bin"), BINARY).expect("write");
3603 git(&work, FIRST_COMMIT, &["add", "-A"]);
3604 git(&work, FIRST_COMMIT, &["commit", "--quiet", "-m", "first"]);
3605
3606 // A rename git will only find with `-M`: the content is 83% the same.
3607 std::fs::rename(work.join("src/a.txt"), work.join("src/b.txt")).expect("rename");
3608 std::fs::write(work.join("src/b.txt"), b"aaa\nbbb\nccc\nddd\neee\nfff\n").expect("write");
3609 std::fs::remove_file(work.join("gone.txt")).expect("remove");
3610 std::fs::write(work.join("logo.bin"), [0x00, 0x02, 0xff]).expect("write");
3611 std::fs::write(work.join("new.txt"), b"new\n").expect("write");
3612 git(&work, SECOND_COMMIT, &["add", "-A"]);
3613 git(
3614 &work,
3615 SECOND_COMMIT,
3616 &["commit", "--quiet", "-m", "second\n\nwhy it was done"],
3617 );
3618
3619 // A branch ahead of main, for compare.
3620 git(&work, THIRD_COMMIT, &["checkout", "--quiet", "-b", "next"]);
3621 std::fs::write(work.join("new.txt"), b"new\nand more\n").expect("write");
3622 git(&work, THIRD_COMMIT, &["add", "-A"]);
3623 git(&work, THIRD_COMMIT, &["commit", "--quiet", "-m", "third"]);
3624
3625 // A history sharing no ancestor with either, which a compare page must be able
3626 // to report rather than fail on.
3627 git(
3628 &work,
3629 THIRD_COMMIT,
3630 &["checkout", "--quiet", "--orphan", "unrelated"],
3631 );
3632 git(&work, THIRD_COMMIT, &["rm", "-rq", "--cached", "."]);
3633 std::fs::write(work.join("z.txt"), b"z\n").expect("write");
3634 git(&work, THIRD_COMMIT, &["add", "z.txt"]);
3635 git(
3636 &work,
3637 THIRD_COMMIT,
3638 &["commit", "--quiet", "-m", "unrelated"],
3639 );
3640
3641 git(
3642 &work,
3643 THIRD_COMMIT,
3644 &[
3645 "push",
3646 "--quiet",
3647 repo.to_str().expect("utf-8 fixture path"),
3648 "main",
3649 "next",
3650 "unrelated",
3651 ],
3652 );
3653
3654 (dir, query)
3655 }
3656
3657 /// The commit a revision names, for a test that needs the id rather than the name.
3658 async fn commit_id(query: &DiskGitQuery, name: &str) -> ObjectId {
3659 query
3660 .resolve(&handle(), &repo_name(), &rev(name))
3661 .await
3662 .expect("should resolve")
3663 .expect("a commit")
3664 }
3665
3666 #[tokio::test]
3667 async fn a_commit_carries_its_message_its_people_and_its_parent() {
3668 let (_dir, query) = with_history();
3669
3670 let commit = query
3671 .commit(&handle(), &repo_name(), &rev("main"))
3672 .await
3673 .expect("should read")
3674 .expect("a commit");
3675
3676 assert_eq!(commit.summary, "second");
3677 // The body is everything after the blank line, and the trailing newline git
3678 // adds to the record is not part of it.
3679 assert_eq!(commit.body, "why it was done");
3680 assert_eq!(commit.author_name, "Ada Lovelace");
3681 assert_eq!(commit.author_email, "ada@example.com");
3682 assert_eq!(commit.committed_at, unix_time(SECOND_COMMIT));
3683 assert_eq!(commit.parents.len(), 1);
3684 assert!(!commit.is_root());
3685 assert!(!commit.has_distinct_committer());
3686 }
3687
3688 #[tokio::test]
3689 async fn a_first_commit_has_no_parent() {
3690 let (_dir, query) = with_history();
3691
3692 let head = query
3693 .commit(&handle(), &repo_name(), &rev("main"))
3694 .await
3695 .expect("should read")
3696 .expect("a commit");
3697 let parent = RefName::from_trusted(head.parents[0].as_str());
3698
3699 let root = query
3700 .commit(&handle(), &repo_name(), &parent)
3701 .await
3702 .expect("should read")
3703 .expect("a commit");
3704
3705 assert_eq!(root.summary, "first");
3706 assert!(root.is_root());
3707 }
3708
3709 #[tokio::test]
3710 async fn an_abbreviated_id_names_the_same_commit_as_the_branch() {
3711 // What a URL carries when someone clicks a shortened sha in the log.
3712 let (_dir, query) = with_history();
3713
3714 let head = query
3715 .commit(&handle(), &repo_name(), &rev("main"))
3716 .await
3717 .expect("should read")
3718 .expect("a commit");
3719
3720 let short = query
3721 .commit(
3722 &handle(),
3723 &repo_name(),
3724 &RefName::from_trusted(head.id.short()),
3725 )
3726 .await
3727 .expect("should read")
3728 .expect("a commit");
3729
3730 assert_eq!(short.id, head.id);
3731 }
3732
3733 #[tokio::test]
3734 async fn a_revision_that_names_no_commit_has_none() {
3735 let (_dir, query) = with_history();
3736
3737 assert!(
3738 query
3739 .commit(&handle(), &repo_name(), &rev("nope"))
3740 .await
3741 .expect("should read")
3742 .is_none()
3743 );
3744 }
3745
3746 #[tokio::test]
3747 async fn a_diff_carries_its_counts_before_its_patch() {
3748 let (_dir, query) = with_history();
3749 let head = query
3750 .commit(&handle(), &repo_name(), &rev("main"))
3751 .await
3752 .expect("should read")
3753 .expect("a commit");
3754
3755 let raw = query
3756 .diff(
3757 &handle(),
3758 &repo_name(),
3759 head.parents.first(),
3760 &head.id,
3761 1024 * 1024,
3762 )
3763 .await
3764 .expect("should diff");
3765
3766 let numstat = String::from_utf8_lossy(&raw.numstat);
3767 let patch = String::from_utf8_lossy(&raw.patch);
3768
3769 assert!(!raw.truncated);
3770 // Four files: the rename, the deletion, the binary, and the addition.
3771 assert_eq!(numstat.lines().filter(|line| !line.is_empty()).count(), 4);
3772 // The rename is one entry with both names, which is what `-M` buys.
3773 assert!(
3774 numstat.contains("src/{a.txt => b.txt}"),
3775 "expected a rename in {numstat:?}"
3776 );
3777 // A binary file has no counts, which is git's `-` rather than a zero.
3778 assert!(numstat.contains("-\t-\tlogo.bin"), "{numstat:?}");
3779
3780 // And the patch is the patch, starting where the counts stop.
3781 assert!(
3782 patch.starts_with("diff --git "),
3783 "{:?}",
3784 &patch[..60.min(patch.len())]
3785 );
3786 assert!(patch.contains("rename from src/a.txt"));
3787 assert!(patch.contains("Binary files "));
3788 }
3789
3790 #[tokio::test]
3791 async fn a_root_commit_is_diffed_against_nothing_rather_than_skipped() {
3792 let (_dir, query) = with_history();
3793 let head = query
3794 .commit(&handle(), &repo_name(), &rev("main"))
3795 .await
3796 .expect("should read")
3797 .expect("a commit");
3798 let root = query
3799 .commit(
3800 &handle(),
3801 &repo_name(),
3802 &RefName::from_trusted(head.parents[0].as_str()),
3803 )
3804 .await
3805 .expect("should read")
3806 .expect("a commit");
3807
3808 let raw = query
3809 .diff(&handle(), &repo_name(), None, &root.id, 1024 * 1024)
3810 .await
3811 .expect("should diff");
3812
3813 // Without `--root` this would be empty, and the first commit in a repository
3814 // would show as having changed nothing.
3815 assert!(String::from_utf8_lossy(&raw.numstat).contains("src/a.txt"));
3816 assert!(String::from_utf8_lossy(&raw.patch).contains("new file mode"));
3817 }
3818
3819 #[tokio::test]
3820 async fn a_diff_over_the_cap_is_cut_short_with_its_counts_intact() {
3821 // The reason the counts are asked for in the same run: they are written first,
3822 // so they survive a patch that does not fit.
3823 let (_dir, query) = with_history();
3824 let head = query
3825 .commit(&handle(), &repo_name(), &rev("main"))
3826 .await
3827 .expect("should read")
3828 .expect("a commit");
3829
3830 let raw = query
3831 .diff(&handle(), &repo_name(), head.parents.first(), &head.id, 90)
3832 .await
3833 .expect("should diff");
3834
3835 assert!(raw.truncated);
3836 assert_eq!(raw.numstat.len() + raw.patch.len(), 90);
3837 assert!(String::from_utf8_lossy(&raw.numstat).contains("src/{a.txt => b.txt}"));
3838 }
3839
3840 #[tokio::test]
3841 async fn a_merge_base_is_the_point_two_branches_share() {
3842 let (_dir, query) = with_history();
3843 let main = commit_id(&query, "main").await;
3844 let next = commit_id(&query, "next").await;
3845
3846 let base = query
3847 .merge_base(&handle(), &repo_name(), &main, &next)
3848 .await
3849 .expect("should read")
3850 .expect("a merge base");
3851
3852 // `next` branched off the tip of `main`, so that tip is the base.
3853 assert_eq!(base, main);
3854 }
3855
3856 #[tokio::test]
3857 async fn two_histories_with_no_common_ancestor_have_no_merge_base() {
3858 // git says this with exit 1 and no output — the one documented not-found exit
3859 // this module tolerates. It must be an answer, not a 500.
3860 let (_dir, query) = with_history();
3861 let main = commit_id(&query, "main").await;
3862 let unrelated = commit_id(&query, "unrelated").await;
3863
3864 assert!(
3865 query
3866 .merge_base(&handle(), &repo_name(), &main, &unrelated)
3867 .await
3868 .expect("should read")
3869 .is_none()
3870 );
3871 }
3872
3873 #[tokio::test]
3874 async fn a_range_lists_only_what_the_head_adds() {
3875 let (_dir, query) = with_history();
3876 let main = commit_id(&query, "main").await;
3877 let next = commit_id(&query, "next").await;
3878
3879 let commits = query
3880 .log_between(&handle(), &repo_name(), Some(&main), &next, 0, 50)
3881 .await
3882 .expect("should read");
3883
3884 assert_eq!(
3885 commits
3886 .iter()
3887 .map(|commit| commit.summary.as_str())
3888 .collect::<Vec<_>>(),
3889 vec!["third"]
3890 );
3891
3892 // The other way round adds nothing: `main` is contained in `next`.
3893 assert!(
3894 query
3895 .log_between(&handle(), &repo_name(), Some(&next), &main, 0, 50)
3896 .await
3897 .expect("should read")
3898 .is_empty()
3899 );
3900 }
3901
3902 #[tokio::test]
3903 async fn a_range_counts_what_the_head_adds_and_pages_from_it() {
3904 let (_dir, query) = with_history();
3905 let main = commit_id(&query, "main").await;
3906 let next = commit_id(&query, "next").await;
3907
3908 let total = query
3909 .count_between(&handle(), &repo_name(), Some(&main), &next)
3910 .await
3911 .expect("should count");
3912 let second = query
3913 .log_between(&handle(), &repo_name(), Some(&main), &next, 1, 50)
3914 .await
3915 .expect("should read");
3916
3917 assert_eq!(total, 1);
3918 assert!(second.is_empty(), "one commit, so nothing on a second page");
3919 }
3920
3921 #[test]
3922 fn the_counts_and_the_patch_are_split_at_the_first_file_header() {
3923 let (numstat, patch) = split_numstat(b"1\t1\ta.txt\n\ndiff --git a/a.txt b/a.txt\n@@\n");
3924
3925 assert_eq!(numstat, b"1\t1\ta.txt\n\n");
3926 assert!(patch.starts_with(b"diff --git "));
3927 }
3928
3929 #[test]
3930 fn a_diff_with_nothing_in_it_splits_into_two_empties() {
3931 let (numstat, patch) = split_numstat(b"");
3932
3933 assert!(numstat.is_empty());
3934 assert!(patch.is_empty());
3935 }
3936
3937 // --- blame ----------------------------------------------------------------------
3938
3939 /// A repository with one file rewritten across three commits, so a blame of it has
3940 /// several runs rather than one.
3941 ///
3942 /// Its own fixture rather than another file in [`populated`], because the shape
3943 /// blame needs — the same file touched repeatedly, at known times — is exactly what
3944 /// the other queries do not want.
3945 fn blamed() -> (TempDir, DiskGitQuery) {
3946 let (dir, query) = empty();
3947 let repo = query.repo_path(&handle(), &repo_name());
3948 let work = dir.path().join("blame-work");
3949
3950 std::fs::create_dir_all(work.join("docs")).expect("create work tree");
3951 git(&work, FIRST_COMMIT, &["init", "--quiet", "-b", "main"]);
3952
3953 std::fs::write(work.join("notes.md"), b"one\ntwo\nthree\n").expect("write");
3954 std::fs::write(work.join("docs/why.md"), b"because\n").expect("write");
3955 std::fs::write(work.join("logo.png"), BINARY).expect("write");
3956 git(&work, FIRST_COMMIT, &["add", "-A"]);
3957 git(&work, FIRST_COMMIT, &["commit", "--quiet", "-m", "first"]);
3958
3959 std::fs::write(work.join("notes.md"), b"one\nTWO\nthree\n").expect("write");
3960 git(&work, SECOND_COMMIT, &["add", "-A"]);
3961 git(&work, SECOND_COMMIT, &["commit", "--quiet", "-m", "second"]);
3962
3963 std::fs::write(work.join("notes.md"), b"one\nTWO\nthree\nfour\n").expect("write");
3964 git(&work, THIRD_COMMIT, &["add", "-A"]);
3965 git(&work, THIRD_COMMIT, &["commit", "--quiet", "-m", "third"]);
3966
3967 git(
3968 &work,
3969 THIRD_COMMIT,
3970 &[
3971 "push",
3972 "--quiet",
3973 repo.to_str().expect("utf-8 fixture path"),
3974 "main",
3975 ],
3976 );
3977
3978 (dir, query)
3979 }
3980
3981 #[tokio::test]
3982 async fn blame_splits_a_file_into_runs_by_the_commit_that_wrote_them() {
3983 let (_dir, query) = blamed();
3984
3985 let blame = query
3986 .blame(&handle(), &repo_name(), &rev("main"), &path("notes.md"))
3987 .await
3988 .expect("should read")
3989 .expect("a blameable file");
3990
3991 // Lines 1 and 3 are the first commit's but are not adjacent, so four runs.
3992 let shape: Vec<(usize, Vec<String>, String)> = blame
3993 .groups
3994 .iter()
3995 .map(|group| {
3996 (
3997 group.start_line,
3998 group.lines.clone(),
3999 group.commit.summary.clone(),
4000 )
4001 })
4002 .collect();
4003
4004 assert_eq!(
4005 shape,
4006 vec![
4007 (1, vec!["one".to_owned()], "first".to_owned()),
4008 (2, vec!["TWO".to_owned()], "second".to_owned()),
4009 (3, vec!["three".to_owned()], "first".to_owned()),
4010 (4, vec!["four".to_owned()], "third".to_owned()),
4011 ]
4012 );
4013 assert_eq!(blame.line_count(), 4);
4014 }
4015
4016 #[tokio::test]
4017 async fn blame_carries_what_a_page_shows_about_each_commit() {
4018 let (_dir, query) = blamed();
4019
4020 let blame = query
4021 .blame(&handle(), &repo_name(), &rev("main"), &path("notes.md"))
4022 .await
4023 .expect("should read")
4024 .expect("a blameable file");
4025 let newest = &blame.groups[3].commit;
4026
4027 assert_eq!(newest.author_name, "Ada Lovelace");
4028 assert_eq!(newest.authored_at, unix_time(THIRD_COMMIT));
4029 assert_eq!(newest.filename, "notes.md");
4030 // Full ids, so the page can link to a commit without an ambiguous abbreviation.
4031 assert_eq!(newest.id.as_str().len(), 40);
4032 // The oldest run is the faintest tint and the newest the strongest.
4033 assert_eq!(blame.groups[0].age, 0);
4034 assert_eq!(blame.groups[3].age, 4);
4035 }
4036
4037 #[tokio::test]
4038 async fn blame_can_be_asked_by_object_id_as_well_as_by_branch() {
4039 // A blame page reached from a commit link names a sha in its URL.
4040 let (_dir, query) = blamed();
4041 let commit = query
4042 .resolve(&handle(), &repo_name(), &rev("main"))
4043 .await
4044 .expect("should read")
4045 .expect("main resolves");
4046
4047 let blame = query
4048 .blame(
4049 &handle(),
4050 &repo_name(),
4051 &rev(commit.as_str()),
4052 &path("notes.md"),
4053 )
4054 .await
4055 .expect("should read")
4056 .expect("a blameable file");
4057
4058 assert_eq!(blame.groups.len(), 4);
4059 }
4060
4061 #[tokio::test]
4062 async fn there_is_nothing_to_blame_that_is_not_a_file() {
4063 // Every one of these is a fatal error if handed straight to `git blame`, which
4064 // is why the existence check runs first.
4065 let (_dir, query) = blamed();
4066
4067 for (revision, target) in [
4068 ("main", "docs"),
4069 ("main", "nope.md"),
4070 ("no-such-branch", "notes.md"),
4071 ] {
4072 assert_eq!(
4073 query
4074 .blame(&handle(), &repo_name(), &rev(revision), &path(target))
4075 .await
4076 .expect("should read"),
4077 None,
4078 "{revision}:{target} should not blame"
4079 );
4080 }
4081 }
4082
4083 #[tokio::test]
4084 async fn an_empty_repository_blames_nothing() {
4085 let (_dir, query) = empty();
4086
4087 assert_eq!(
4088 query
4089 .blame(&handle(), &repo_name(), &rev("main"), &path("README.md"))
4090 .await
4091 .expect("should read"),
4092 None
4093 );
4094 }
4095
4096 // --- log entries -------------------------------------------------------------
4097
4098 #[tokio::test]
4099 async fn a_log_entry_carries_the_message_body() {
4100 let (_dir, query) = populated();
4101
4102 let entries = query
4103 .log_entries(&handle(), &repo_name(), &rev("main"), 10)
4104 .await
4105 .expect("should read");
4106
4107 assert_eq!(entries.len(), 3);
4108 assert_eq!(
4109 entries[0].commit.summary,
4110 "third: 'quotes', \"doubles\" | pipes"
4111 );
4112 assert_eq!(entries[0].body, "body line one\nbody line two");
4113 }
4114
4115 #[tokio::test]
4116 async fn a_one_line_message_has_an_empty_body_and_does_not_shift_the_record() {
4117 let (_dir, query) = populated();
4118
4119 let entries = query
4120 .log_entries(&handle(), &repo_name(), &rev("main"), 10)
4121 .await
4122 .expect("should read");
4123
4124 // The two older commits were made with `-m` alone, so both bodies are empty —
4125 // which is exactly the case a parser that drops empty fields misreads, reporting
4126 // the next commit's id as this one's body and sliding every field after it.
4127 assert_eq!(entries[1].commit.summary, "second");
4128 assert_eq!(entries[1].body, "");
4129 assert_eq!(entries[2].commit.summary, "first");
4130 assert_eq!(entries[2].body, "");
4131 assert_eq!(entries[2].commit.author_name, "Ada Lovelace");
4132 }
4133
4134 #[test]
4135 fn an_empty_author_name_or_subject_does_not_shift_the_log() {
4136 // The same trap `parse_log_entries` was written to avoid, on the four-field
4137 // parser: git writes the field, empty, and dropping it slides everything after
4138 // it one place left — so the *next* commit's id lands in this commit's subject
4139 // and the record after that fails to parse for a reason naming none of this.
4140 //
4141 // Both are reachable: `--allow-empty-message` leaves `%s` empty, and an ident
4142 // whose name is blank leaves `%an` empty.
4143 let stdout = b"\
4144aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\x001700000200\x00\x00a commit by nobody\x00\
4145bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\x001700000100\x00Ada Lovelace\x00\x00";
4146
4147 let commits = parse_log(stdout).expect("should parse");
4148
4149 assert_eq!(commits.len(), 2);
4150 assert_eq!(commits[0].author_name, "");
4151 assert_eq!(commits[0].summary, "a commit by nobody");
4152 assert_eq!(commits[1].author_name, "Ada Lovelace");
4153 assert_eq!(commits[1].summary, "", "an empty subject stays empty");
4154 assert_eq!(
4155 commits[1].id.as_str(),
4156 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
4157 "the second record must not have been shifted into the first"
4158 );
4159 }
4160
4161 #[tokio::test]
4162 async fn log_entries_agree_with_the_log_they_come_from() {
4163 let (_dir, query) = populated();
4164
4165 let commits = query
4166 .log(&handle(), &repo_name(), &rev("main"), 0, 10)
4167 .await
4168 .expect("should read");
4169 let entries = query
4170 .log_entries(&handle(), &repo_name(), &rev("main"), 10)
4171 .await
4172 .expect("should read");
4173
4174 assert_eq!(
4175 commits,
4176 entries
4177 .into_iter()
4178 .map(|entry| entry.commit)
4179 .collect::<Vec<_>>()
4180 );
4181 }
4182
4183 #[tokio::test]
4184 async fn an_empty_repository_has_no_log_entries() {
4185 let (_dir, query) = empty();
4186
4187 assert!(
4188 query
4189 .log_entries(&handle(), &repo_name(), &rev("main"), 10)
4190 .await
4191 .expect("should read")
4192 .is_empty()
4193 );
4194 assert!(
4195 query
4196 .log_entries(&handle(), &repo_name(), &rev("main"), 0)
4197 .await
4198 .expect("should read")
4199 .is_empty()
4200 );
4201 }
4202
4203 // --- The object parsers -------------------------------------------------------
4204 //
4205 // Pure, so they are tested against bytes written by hand rather than against a
4206 // fixture repository: the point is the format, and a fixture would only prove that
4207 // git and this parser agree about the easy cases. The round trip through a real
4208 // repository is covered by the listing and commit tests above.
4209
4210 /// A tree record: `<mode> SP <name> NUL <20 raw bytes>`.
4211 fn tree_record(mode: &str, name: &str, id: u8) -> Vec<u8> {
4212 let mut record = format!("{mode} {name}").into_bytes();
4213 record.push(0);
4214 record.extend(std::iter::repeat_n(id, 20));
4215 record
4216 }
4217
4218 #[test]
4219 fn a_tree_object_is_parsed_into_entries() {
4220 let mut bytes = tree_record("100644", "README.md", 0xab);
4221 bytes.extend(tree_record("40000", "src", 0xcd));
4222
4223 let entries = parse_tree_object(&bytes).expect("should parse");
4224
4225 assert_eq!(entries.len(), 2);
4226 assert_eq!(entries[0].name, "README.md");
4227 assert_eq!(entries[0].kind, EntryKind::Blob);
4228 assert_eq!(entries[0].id.as_str(), "ab".repeat(20));
4229 // A tree object carries no sizes; `list_tree` asks for them separately.
4230 assert_eq!(entries[0].size, None);
4231 assert_eq!(entries[1].name, "src");
4232 assert_eq!(entries[1].kind, EntryKind::Tree);
4233 }
4234
4235 #[test]
4236 fn a_filename_containing_a_space_is_one_entry() {
4237 // The mode is separated from the name by a space too, which is why the split is
4238 // at the *first* space and the name runs to the NUL.
4239 let bytes = tree_record("100644", "a file.txt", 0x01);
4240
4241 let entries = parse_tree_object(&bytes).expect("should parse");
4242
4243 assert_eq!(entries.len(), 1);
4244 assert_eq!(entries[0].name, "a file.txt");
4245 }
4246
4247 #[test]
4248 fn a_submodule_entry_is_listed_as_one() {
4249 let bytes = tree_record("160000", "vendor", 0x07);
4250
4251 let entries = parse_tree_object(&bytes).expect("should parse");
4252
4253 assert_eq!(entries[0].kind, EntryKind::Submodule);
4254 // The id names a commit in a repository Steid cannot see, so nothing asks about
4255 // it — the entry carries the id and no size.
4256 assert_eq!(entries[0].id.as_str(), "07".repeat(20));
4257 assert_eq!(entries[0].size, None);
4258 }
4259
4260 #[test]
4261 fn an_empty_tree_lists_nothing() {
4262 assert!(parse_tree_object(&[]).expect("should parse").is_empty());
4263 }
4264
4265 #[test]
4266 fn a_truncated_tree_is_a_fault_rather_than_a_short_listing() {
4267 let mut bytes = tree_record("100644", "a.txt", 0x01);
4268 bytes.truncate(bytes.len() - 4);
4269
4270 assert!(parse_tree_object(&bytes).is_err());
4271 }
4272
4273 fn commit_object(headers: &str, message: &str) -> Vec<u8> {
4274 format!("{headers}\n{message}").into_bytes()
4275 }
4276
4277 fn an_id(byte: u8) -> ObjectId {
4278 ObjectId::from_trusted(format!("{byte:02x}").repeat(20))
4279 }
4280
4281 #[test]
4282 fn a_commit_object_is_parsed_into_a_detail() {
4283 let bytes = commit_object(
4284 &format!(
4285 "tree {}\nparent {}\nauthor Ada <ada@example.com> 1700000000 +0100\ncommitter Bo <bo@example.com> 1700000060 -0500\n",
4286 an_id(0xaa).as_str(),
4287 an_id(0xbb).as_str()
4288 ),
4289 "feat: a thing\n\nWhy it is a thing.\n",
4290 );
4291
4292 let commit = parse_commit_object(&an_id(0x11), &bytes).expect("should parse");
4293
4294 assert_eq!(commit.id, an_id(0x11));
4295 assert_eq!(commit.tree, an_id(0xaa));
4296 assert_eq!(commit.parents, vec![an_id(0xbb)]);
4297 assert_eq!(commit.author_name, "Ada");
4298 assert_eq!(commit.author_email, "ada@example.com");
4299 assert_eq!(commit.committer_name, "Bo");
4300 assert_eq!(commit.summary, "feat: a thing");
4301 assert_eq!(commit.body, "Why it is a thing.");
4302 assert_eq!(commit.authored_at, unix_time(1_700_000_000));
4303 assert_eq!(commit.committed_at, unix_time(1_700_000_060));
4304 }
4305
4306 #[test]
4307 fn a_root_commit_has_no_parents_and_a_merge_has_two() {
4308 let root = commit_object(
4309 &format!(
4310 "tree {}\nauthor A <a@b> 1 +0000\ncommitter A <a@b> 1 +0000\n",
4311 an_id(0xaa).as_str()
4312 ),
4313 "first\n",
4314 );
4315 let merge = commit_object(
4316 &format!(
4317 "tree {}\nparent {}\nparent {}\nauthor A <a@b> 1 +0000\ncommitter A <a@b> 1 +0000\n",
4318 an_id(0xaa).as_str(),
4319 an_id(0xbb).as_str(),
4320 an_id(0xcc).as_str()
4321 ),
4322 "merge\n",
4323 );
4324
4325 assert!(
4326 parse_commit_object(&an_id(0x11), &root)
4327 .expect("should parse")
4328 .parents
4329 .is_empty()
4330 );
4331 assert_eq!(
4332 parse_commit_object(&an_id(0x11), &merge)
4333 .expect("should parse")
4334 .parents,
4335 vec![an_id(0xbb), an_id(0xcc)]
4336 );
4337 }
4338
4339 #[test]
4340 fn a_signature_does_not_end_the_headers() {
4341 // `gpgsig`'s continuation lines each begin with a space — including the ones that
4342 // look blank. A parser that split on the first line with nothing much on it would
4343 // read half a signature as the commit message.
4344 let bytes = commit_object(
4345 &format!(
4346 "tree {}\nauthor A <a@b> 1 +0000\ncommitter A <a@b> 1 +0000\ngpgsig -----BEGIN PGP SIGNATURE-----\n \n iQIzBAABCgAd\n -----END PGP SIGNATURE-----\n",
4347 an_id(0xaa).as_str()
4348 ),
4349 "signed\n",
4350 );
4351
4352 let commit = parse_commit_object(&an_id(0x11), &bytes).expect("should parse");
4353
4354 assert_eq!(commit.summary, "signed");
4355 assert_eq!(commit.body, "");
4356 }
4357
4358 #[test]
4359 fn a_multi_line_subject_is_folded_the_way_git_folds_it() {
4360 let bytes = commit_object(
4361 &format!(
4362 "tree {}\nauthor A <a@b> 1 +0000\ncommitter A <a@b> 1 +0000\n",
4363 an_id(0xaa).as_str()
4364 ),
4365 "a subject that\nran onto a second line\n\nand then a body\n",
4366 );
4367
4368 let commit = parse_commit_object(&an_id(0x11), &bytes).expect("should parse");
4369
4370 assert_eq!(commit.summary, "a subject that ran onto a second line");
4371 assert_eq!(commit.body, "and then a body");
4372 }
4373
4374 #[test]
4375 fn a_commit_with_no_message_parses() {
4376 let bytes = format!(
4377 "tree {}\nauthor A <a@b> 1 +0000\ncommitter A <a@b> 1 +0000\n",
4378 an_id(0xaa).as_str()
4379 )
4380 .into_bytes();
4381
4382 let commit = parse_commit_object(&an_id(0x11), &bytes).expect("should parse");
4383
4384 assert_eq!(commit.summary, "");
4385 assert_eq!(commit.body, "");
4386 }
4387
4388 #[test]
4389 fn an_identity_is_read_from_the_right_so_a_name_may_contain_anything() {
4390 let bytes = commit_object(
4391 &format!(
4392 "tree {}\nauthor A <weird> Name <real@example.com> 1700000000 +0000\ncommitter A <a@b> 1 +0000\n",
4393 an_id(0xaa).as_str()
4394 ),
4395 "x\n",
4396 );
4397
4398 let commit = parse_commit_object(&an_id(0x11), &bytes).expect("should parse");
4399
4400 assert_eq!(commit.author_name, "A <weird> Name");
4401 assert_eq!(commit.author_email, "real@example.com");
4402 }
4403
4404 #[test]
4405 fn a_commit_with_no_tree_is_a_fault() {
4406 let bytes = commit_object("author A <a@b> 1 +0000\ncommitter A <a@b> 1 +0000\n", "x\n");
4407
4408 assert!(parse_commit_object(&an_id(0x11), &bytes).is_err());
4409 }
4410
4411 // --- The last-commit column ---------------------------------------------------
4412
4413 /// One commit's worth of the `-z --name-only` stream: three NUL-terminated fields,
4414 /// then its paths, the first of them carrying the newline git writes after the
4415 /// formatted line.
4416 fn walked(id: u8, at: i64, summary: &str, paths: &[&str]) -> Vec<u8> {
4417 let mut bytes = Vec::new();
4418
4419 bytes.extend(format!("{id:02x}").repeat(20).into_bytes());
4420 bytes.push(0);
4421 bytes.extend(at.to_string().into_bytes());
4422 bytes.push(0);
4423 bytes.extend(summary.as_bytes());
4424 bytes.push(0);
4425
4426 for (index, path) in paths.iter().enumerate() {
4427 if index == 0 {
4428 bytes.push(b'\n');
4429 }
4430
4431 bytes.extend(path.as_bytes());
4432 bytes.push(0);
4433 }
4434
4435 bytes
4436 }
4437
4438 fn names(values: &[&str]) -> Vec<String> {
4439 values.iter().map(|value| (*value).to_owned()).collect()
4440 }
4441
4442 #[test]
4443 fn each_entry_takes_the_newest_commit_that_touched_it() {
4444 let mut stream = walked(0x33, 300, "fix: the reader", &["src/read.rs"]);
4445 stream.extend(walked(0x22, 200, "feat: a writer", &["src/write.rs"]));
4446 stream.extend(walked(0x11, 100, "first", &["src/read.rs", "src/write.rs"]));
4447
4448 let found = attribute(&stream, "src/", &names(&["read.rs", "write.rs"]));
4449
4450 assert_eq!(found["read.rs"].summary, "fix: the reader");
4451 assert_eq!(found["read.rs"].committed_at, unix_time(300));
4452 assert_eq!(found["write.rs"].summary, "feat: a writer");
4453 }
4454
4455 #[test]
4456 fn a_path_under_a_child_directory_attributes_to_the_child() {
4457 let stream = walked(0x44, 400, "docs: a page", &["src/web/page.rs"]);
4458
4459 let found = attribute(&stream, "src/", &names(&["web", "read.rs"]));
4460
4461 assert_eq!(found["web"].summary, "docs: a page");
4462 assert!(!found.contains_key("read.rs"), "nothing touched it");
4463 }
4464
4465 #[test]
4466 fn the_root_of_a_repository_needs_no_prefix() {
4467 let stream = walked(
4468 0x55,
4469 500,
4470 "chore: the manifest",
4471 &["Cargo.toml", "src/lib.rs"],
4472 );
4473
4474 let found = attribute(&stream, "", &names(&["Cargo.toml", "src"]));
4475
4476 assert_eq!(found["Cargo.toml"].summary, "chore: the manifest");
4477 assert_eq!(found["src"].summary, "chore: the manifest");
4478 }
4479
4480 #[test]
4481 fn a_rename_attributes_the_new_name_to_the_commit_that_made_it() {
4482 // git lists both sides of a rename in the commit that made it, so the new name's
4483 // first mention is that commit and the old name's is too — the old name is simply
4484 // not in the listing any more, so nothing asks about it.
4485 let mut stream = walked(0x66, 600, "refactor: rename it", &["new.rs", "old.rs"]);
4486 stream.extend(walked(0x11, 100, "first", &["old.rs"]));
4487
4488 let found = attribute(&stream, "", &names(&["new.rs"]));
4489
4490 assert_eq!(found["new.rs"].summary, "refactor: rename it");
4491 assert_eq!(found.len(), 1, "the old name is not in the listing");
4492 }
4493
4494 #[test]
4495 fn an_entry_the_walk_never_reached_is_absent_rather_than_wrong() {
4496 // What the cap looks like from here: the stream ends with an entry unmentioned,
4497 // and the answer says nothing about it rather than naming the oldest commit read.
4498 let stream = walked(0x77, 700, "only this one", &["touched.rs"]);
4499
4500 let found = attribute(&stream, "", &names(&["touched.rs", "untouched.rs"]));
4501
4502 assert_eq!(found.len(), 1);
4503 assert!(!found.contains_key("untouched.rs"));
4504 }
4505
4506 #[test]
4507 fn a_commit_that_lists_no_files_does_not_shift_the_ones_after_it() {
4508 // A merge, which `--name-only` prints with no file list at all. The record after
4509 // it must still be recognised as a record.
4510 let mut stream = walked(0x88, 800, "merge: a branch", &[]);
4511 stream.extend(walked(0x99, 900, "feat: the thing", &["thing.rs"]));
4512
4513 let found = attribute(&stream, "", &names(&["thing.rs"]));
4514
4515 assert_eq!(found["thing.rs"].summary, "feat: the thing");
4516 }
4517
4518 #[test]
4519 fn a_filename_containing_a_newline_is_still_one_path() {
4520 // `-z` is why: without it git would quote this, and the quoting would have to be
4521 // undone here.
4522 let stream = walked(0xaa, 100, "add it", &["odd\nname.rs"]);
4523
4524 let found = attribute(&stream, "", &names(&["odd\nname.rs"]));
4525
4526 assert_eq!(found.len(), 1);
4527 }
4528
4529 #[test]
4530 fn nothing_is_attributed_from_an_empty_walk() {
4531 assert!(attribute(&[], "", &names(&["a.rs"])).is_empty());
4532 }
4533
4534 #[tokio::test]
4535 async fn a_listing_says_what_last_touched_each_of_its_entries() {
4536 let (_dir, query) = with_history();
4537
4538 let found = query
4539 .last_commits(
4540 &handle(),
4541 &repo_name(),
4542 &rev("main"),
4543 &RepoPath::root(),
4544 &names(&["new.txt", "src", "never-existed.txt"]),
4545 )
4546 .await
4547 .expect("should read");
4548
4549 // `new.txt` and `src` were both last touched by the second commit; the entry
4550 // that was never in the repository is absent rather than guessed at.
4551 assert_eq!(found.len(), 2);
4552 assert_eq!(found["new.txt"].summary, "second");
4553 assert_eq!(found["src"].summary, "second");
4554 assert!(!found.contains_key("never-existed.txt"));
4555 }
4556
4557 #[tokio::test]
4558 async fn an_empty_repository_attributes_nothing() {
4559 let (_dir, query) = empty();
4560
4561 assert!(
4562 query
4563 .last_commits(
4564 &handle(),
4565 &repo_name(),
4566 &rev("main"),
4567 &RepoPath::root(),
4568 &names(&["a.txt"]),
4569 )
4570 .await
4571 .expect("should read")
4572 .is_empty()
4573 );
4574 }
4575
4576 // --- a path's own log ------------------------------------------------------
4577
4578 /// The summaries of a path's log, which is what a history page renders.
4579 async fn path_log(
4580 query: &DiskGitQuery,
4581 at: &str,
4582 follow: bool,
4583 offset: usize,
4584 limit: usize,
4585 ) -> Vec<String> {
4586 query
4587 .log_at_path(
4588 &handle(),
4589 &repo_name(),
4590 &rev("main"),
4591 &path(at),
4592 follow,
4593 offset,
4594 limit,
4595 )
4596 .await
4597 .expect("should read")
4598 .into_iter()
4599 .map(|commit| commit.summary)
4600 .collect()
4601 }
4602
4603 #[tokio::test]
4604 async fn a_paths_log_holds_only_the_commits_that_touched_it() {
4605 let (_dir, query) = with_history();
4606
4607 // `new.txt` arrived in the second commit and the first knows nothing about it.
4608 assert_eq!(path_log(&query, "new.txt", false, 0, 50).await, ["second"]);
4609 }
4610
4611 #[tokio::test]
4612 async fn a_directorys_log_is_every_commit_that_touched_anything_beneath_it() {
4613 let (_dir, query) = with_history();
4614
4615 assert_eq!(
4616 path_log(&query, "src", false, 0, 50).await,
4617 ["second", "first"]
4618 );
4619 }
4620
4621 #[tokio::test]
4622 async fn following_a_rename_reaches_the_history_before_it() {
4623 let (_dir, query) = with_history();
4624
4625 // `src/a.txt` became `src/b.txt` in the second commit. Without `--follow` the
4626 // file's history starts at the rename, which is the thing a reader least wants.
4627 assert_eq!(
4628 path_log(&query, "src/b.txt", false, 0, 50).await,
4629 ["second"]
4630 );
4631 assert_eq!(
4632 path_log(&query, "src/b.txt", true, 0, 50).await,
4633 ["second", "first"]
4634 );
4635 }
4636
4637 #[tokio::test]
4638 async fn a_paths_log_pages_by_skipping() {
4639 let (_dir, query) = with_history();
4640
4641 assert_eq!(path_log(&query, "src", false, 1, 50).await, ["first"]);
4642 assert!(path_log(&query, "src", false, 9, 50).await.is_empty());
4643 assert_eq!(path_log(&query, "src", false, 0, 1).await, ["second"]);
4644 }
4645
4646 #[tokio::test]
4647 async fn a_paths_log_of_an_unknown_revision_is_empty_rather_than_a_failure() {
4648 let (_dir, query) = with_history();
4649
4650 let commits = query
4651 .log_at_path(
4652 &handle(),
4653 &repo_name(),
4654 &rev("nope"),
4655 &path("src"),
4656 false,
4657 0,
4658 50,
4659 )
4660 .await
4661 .expect("should read");
4662
4663 assert!(commits.is_empty());
4664 }
4665
4666 #[tokio::test]
4667 async fn a_paths_commits_are_counted_the_same_way_they_are_listed() {
4668 let (_dir, query) = with_history();
4669
4670 let count = async |at: &str, follow: bool| {
4671 query
4672 .count_commits_at_path(&handle(), &repo_name(), &rev("main"), &path(at), follow)
4673 .await
4674 .expect("should count")
4675 };
4676
4677 // The followed count must match the followed listing, or a page says "showing
4678 // 1–2 of 1".
4679 assert_eq!(count("src/b.txt", false).await.total, 1);
4680 assert_eq!(count("src/b.txt", true).await.total, 2);
4681 assert_eq!(count("src", false).await.total, 2);
4682 // A path nothing ever touched is zero rather than an error.
4683 assert_eq!(count("never-existed.txt", false).await.total, 0);
4684 // Nothing here is anywhere near the cap, so nothing claims to be.
4685 assert!(!count("src/b.txt", true).await.capped);
4686 }
4687
4688 #[tokio::test]
4689 async fn counting_a_path_in_an_empty_repository_is_zero() {
4690 let (_dir, query) = empty();
4691
4692 assert_eq!(
4693 query
4694 .count_commits_at_path(&handle(), &repo_name(), &rev("main"), &path("a.txt"), false)
4695 .await
4696 .expect("should count"),
4697 CommitCount::default()
4698 );
4699 }
4700
4701 // --- symlink targets -------------------------------------------------------
4702
4703 #[tokio::test]
4704 async fn a_symlinks_target_is_read_from_the_blob_it_is_stored_as() {
4705 let (_dir, query) = populated();
4706
4707 let entries = by_name(
4708 query
4709 .list_tree(&handle(), &repo_name(), &rev("main"), &RepoPath::root())
4710 .await
4711 .expect("should read")
4712 .expect("a directory"),
4713 );
4714 let link = &entries["link"];
4715
4716 assert_eq!(link.kind, EntryKind::Symlink);
4717
4718 let targets = query
4719 .symlink_targets(&handle(), &repo_name(), std::slice::from_ref(&link.id))
4720 .await
4721 .expect("should read");
4722
4723 assert_eq!(targets[&link.id], "README.md");
4724 }
4725
4726 #[tokio::test]
4727 async fn asking_about_no_symlinks_reads_nothing() {
4728 let (_dir, query) = populated();
4729
4730 assert!(
4731 query
4732 .symlink_targets(&handle(), &repo_name(), &[])
4733 .await
4734 .expect("should read")
4735 .is_empty()
4736 );
4737 }
4738
4739 #[tokio::test]
4740 async fn an_id_that_is_not_a_blob_is_left_out_rather_than_guessed_at() {
4741 let (_dir, query) = populated();
4742
4743 let tree = query
4744 .resolve(&handle(), &repo_name(), &rev("main"))
4745 .await
4746 .expect("should read")
4747 .expect("a commit");
4748
4749 // A commit id, which is not a link and has no target.
4750 assert!(
4751 query
4752 .symlink_targets(&handle(), &repo_name(), &[tree])
4753 .await
4754 .expect("should read")
4755 .is_empty()
4756 );
4757 }
4758
4759 // --- merge preview ---------------------------------------------------------------
4760
4761 /// A bare repository holding `main` plus two branches off it: one that merges
4762 /// cleanly and one that does not, both touching the same commit's tree.
4763 ///
4764 /// Built by pushing from a working copy, like [`populated`], rather than by
4765 /// plumbing into the object store — the merge is about what a real branch looks
4766 /// like, and a hand-built one would prove less.
4767 fn branched() -> (TempDir, DiskGitQuery) {
4768 let (dir, query) = empty();
4769 let repo = query.repo_path(&handle(), &repo_name());
4770 let work = dir.path().join("merge-work");
4771
4772 std::fs::create_dir_all(&work).expect("create work tree");
4773 git(&work, FIRST_COMMIT, &["init", "--quiet", "-b", "main"]);
4774
4775 std::fs::write(work.join("shared.txt"), b"one\n").expect("write");
4776 git(&work, FIRST_COMMIT, &["add", "-A"]);
4777 git(&work, FIRST_COMMIT, &["commit", "--quiet", "-m", "first"]);
4778
4779 // A branch that touches a file `main` never does: nothing to disagree about.
4780 git(&work, SECOND_COMMIT, &["checkout", "--quiet", "-b", "tidy"]);
4781 std::fs::write(work.join("other.txt"), b"tidy\n").expect("write");
4782 git(&work, SECOND_COMMIT, &["add", "-A"]);
4783 git(&work, SECOND_COMMIT, &["commit", "--quiet", "-m", "tidy"]);
4784
4785 // A branch that rewrites the same line `main` is about to rewrite differently.
4786 git(&work, SECOND_COMMIT, &["checkout", "--quiet", "main"]);
4787 git(
4788 &work,
4789 SECOND_COMMIT,
4790 &["checkout", "--quiet", "-b", "clash"],
4791 );
4792 std::fs::write(work.join("shared.txt"), b"theirs\n").expect("write");
4793 git(&work, SECOND_COMMIT, &["add", "-A"]);
4794 git(&work, SECOND_COMMIT, &["commit", "--quiet", "-m", "theirs"]);
4795
4796 git(&work, THIRD_COMMIT, &["checkout", "--quiet", "main"]);
4797 std::fs::write(work.join("shared.txt"), b"ours\n").expect("write");
4798 git(&work, THIRD_COMMIT, &["add", "-A"]);
4799 git(&work, THIRD_COMMIT, &["commit", "--quiet", "-m", "ours"]);
4800
4801 git(
4802 &work,
4803 THIRD_COMMIT,
4804 &[
4805 "push",
4806 "--quiet",
4807 repo.to_str().expect("utf-8 fixture path"),
4808 "main",
4809 "tidy",
4810 "clash",
4811 ],
4812 );
4813
4814 (dir, query)
4815 }
4816
4817 /// Resolves a revision in the fixture, so a test can name a branch and hand the
4818 /// port the ids it takes.
4819 async fn resolved(query: &DiskGitQuery, revision: &str) -> ObjectId {
4820 query
4821 .resolve(&handle(), &repo_name(), &rev(revision))
4822 .await
4823 .expect("should resolve")
4824 .expect("the revision exists")
4825 }
4826
4827 #[tokio::test]
4828 async fn two_branches_that_do_not_overlap_merge_cleanly() {
4829 let (_dir, query) = branched();
4830 let target = resolved(&query, "main").await;
4831 let source = resolved(&query, "tidy").await;
4832
4833 let preview = query
4834 .merge_preview(&handle(), &repo_name(), &target, &source)
4835 .await
4836 .expect("should preview");
4837
4838 // The tree is what makes this usable: `commit_tree` takes it straight, so a
4839 // clean preview is the merge, already computed.
4840 let MergePreview::Clean { tree } = preview else {
4841 panic!("expected a clean merge, got {preview:?}");
4842 };
4843 assert_eq!(tree.as_str().len(), 40);
4844 }
4845
4846 #[tokio::test]
4847 async fn two_branches_that_rewrite_one_line_report_the_file() {
4848 let (_dir, query) = branched();
4849 let target = resolved(&query, "main").await;
4850 let source = resolved(&query, "clash").await;
4851
4852 let preview = query
4853 .merge_preview(&handle(), &repo_name(), &target, &source)
4854 .await
4855 .expect("a conflict is an answer, not a failure");
4856
4857 // Named once, though git reports three stages of it: three stages of a file is
4858 // one file to whoever has to resolve it.
4859 assert_eq!(
4860 preview,
4861 MergePreview::Conflicted {
4862 paths: vec!["shared.txt".to_owned()],
4863 }
4864 );
4865 }
4866
4867 #[tokio::test]
4868 async fn a_second_look_at_the_same_pair_is_answered_from_the_cache() {
4869 // What the pull request page was paying per view: a full three-way merge, and a
4870 // fresh set of objects `--write-tree` leaves unreferenced. Counted by asking the
4871 // cache rather than by counting processes, because the pair is the key and a
4872 // populated key is exactly what stops the second run.
4873 let (dir, _built) = branched();
4874 let merges = std::sync::Arc::new(MergeCache::new());
4875 let query = DiskGitQuery::new(dir.path(), Arc::new(CatFilePool::new()), merges.clone());
4876
4877 let target = resolved(&query, "main").await;
4878 let source = resolved(&query, "clash").await;
4879
4880 assert_eq!(merges.get(&target, &source), None);
4881
4882 let first = query
4883 .merge_preview(&handle(), &repo_name(), &target, &source)
4884 .await
4885 .expect("should preview");
4886
4887 assert_eq!(merges.get(&target, &source).as_ref(), Some(&first));
4888
4889 let second = query
4890 .merge_preview(&handle(), &repo_name(), &target, &source)
4891 .await
4892 .expect("should preview");
4893
4894 assert_eq!(second, first);
4895 }
4896
4897 #[tokio::test]
4898 async fn merging_a_branch_already_contained_in_the_target_is_clean() {
4899 // The fast-forward case seen from the preview's side: `main` contains `main`,
4900 // so there is nothing to disagree about and the tree is the one it already has.
4901 let (_dir, query) = branched();
4902 let main = resolved(&query, "main").await;
4903
4904 assert!(
4905 query
4906 .merge_preview(&handle(), &repo_name(), &main, &main)
4907 .await
4908 .expect("should preview")
4909 .is_clean()
4910 );
4911 }
4912
4913 #[test]
4914 fn a_conflict_block_stops_at_the_blank_line() {
4915 // git writes its informational messages after a blank line, and they contain
4916 // tabs of their own — so a parser that read to the end would report prose as
4917 // filenames.
4918 let stdout = concat!(
4919 "0123456789012345678901234567890123456789\n",
4920 "100644 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 1\tshared.txt\n",
4921 "100644 bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb 2\tshared.txt\n",
4922 "100644 cccccccccccccccccccccccccccccccccccccccc 3\tshared.txt\n",
4923 "100644 dddddddddddddddddddddddddddddddddddddddd 1\tsrc/with space.rs\n",
4924 "\n",
4925 "Auto-merging shared.txt\n",
4926 "CONFLICT (content): Merge conflict in\tshared.txt\n",
4927 );
4928
4929 assert_eq!(
4930 parse_merge_tree(stdout.as_bytes(), true).expect("should parse"),
4931 MergePreview::Conflicted {
4932 paths: vec!["shared.txt".to_owned(), "src/with space.rs".to_owned()],
4933 }
4934 );
4935 }
4936
4937 #[test]
4938 fn a_clean_merge_reads_only_its_tree() {
4939 // A clean merge can still carry informational messages, which is why the exit
4940 // status decides and not the shape of what was written.
4941 let stdout = "0123456789012345678901234567890123456789\n\nAuto-merging other.txt\n";
4942
4943 assert_eq!(
4944 parse_merge_tree(stdout.as_bytes(), false).expect("should parse"),
4945 MergePreview::Clean {
4946 tree: ObjectId::from_trusted("0123456789012345678901234567890123456789"),
4947 }
4948 );
4949 }
4950
4951 #[test]
4952 fn output_with_no_tree_is_a_fault_not_an_empty_merge() {
4953 assert!(parse_merge_tree(b"", false).is_err());
4954 assert!(parse_merge_tree(b"\n", true).is_err());
4955 }
4956}