steid

@jamesgill /

steid/src/infrastructure/git_query.rs
Rust50.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//!
41//! # What lives where
42//!
43//! This file holds [`DiskGitQuery`], its `impl GitQuery`, and the `run*` helpers that
44//! actually spawn git. Everything that only turns git's bytes into values sits in
45//! `parse_refs`, `parse_log`, `parse_tree` and `parse_diff` beside it, each with the
46//! `--format` strings it is the reader of and its own unit tests. Those four are pure:
47//! nothing in them spawns a process or touches a path, which is why they can be tested
48//! against bytes written by hand.
49
50use std::{
51 collections::HashMap,
52 ffi::OsStr,
53 path::{Path, PathBuf},
54 process::{Output, Stdio},
55 sync::Arc,
56 time::{Duration, SystemTime, UNIX_EPOCH},
57};
58
59use tokio::io::AsyncReadExt;
60
61use crate::{
62 application::{
63 blame::{Blame, parse_blame},
64 port::{Blob, CommitCount, GitQuery, GitQueryError, MergePreview, RawDiff},
65 search::parse_grep_output,
66 },
67 domain::{
68 BranchRow, CommitDetail, CommitEntry, CommitSummary, EntryCommit, EntryKind, GitRef,
69 GrepHit, ObjectId, OrgName, RefName, RepoName, RepoPath, TagRow, TagSummary, TreeEntry,
70 },
71 infrastructure::{
72 cat_file::{CatFilePool, ObjectInfo, ObjectKind},
73 git::{count_spawn, git_command},
74 merge_cache::MergeCache,
75 },
76};
77
78mod parse_diff;
79mod parse_log;
80mod parse_refs;
81mod parse_tree;
82
83use parse_diff::{parse_merge_tree, split_numstat};
84use parse_log::{ENTRY_FORMAT, LOG_FORMAT, parse_commit_object, parse_log, parse_log_entries};
85use parse_refs::{
86 BRANCH_FORMAT, REF_FORMAT, SNAPSHOT_FORMAT, TAG_FORMAT, TAG_ROW_FORMAT, parse_branches,
87 parse_latest_tag, parse_ref_snapshot, parse_refs, parse_tags,
88};
89use parse_tree::{LAST_COMMIT_FORMAT, attribute, parse_tree_object, tree_spec};
90
91mod in_memory;
92
93pub use in_memory::InMemoryGitQuery;
94
95/// Repository contents, read from bare repositories under a data directory.
96///
97/// The pool is shared, not owned: it holds live `git cat-file` processes, and this
98/// adapter is constructed per request. Built per request the pool would spawn and kill a
99/// process per request — the fork cost back, plus a pool that never pools. See the
100/// Milestone 5 amendment to
101/// [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md), which named
102/// that as the one thing to get right before the first batch adapter existed.
103#[derive(Debug, Clone)]
104pub struct DiskGitQuery {
105 data_dir: PathBuf,
106 pool: Arc<CatFilePool>,
107 /// Merge previews already computed, so a pull request page that is reloaded does not
108 /// re-run `merge-tree` — see [`MergeCache`].
109 merges: Arc<MergeCache>,
110}
111
112impl DiskGitQuery {
113 pub fn new(
114 data_dir: impl Into<PathBuf>,
115 pool: Arc<CatFilePool>,
116 merges: Arc<MergeCache>,
117 ) -> Self {
118 Self {
119 data_dir: data_dir.into(),
120 pool,
121 merges,
122 }
123 }
124
125 /// What a revision resolves to, as a commit.
126 ///
127 /// `^{commit}` peels an annotated tag to what it points at, and refuses a revision
128 /// that names a tree or a blob — a browse page wants a commit, and returning a tree
129 /// id here would fail confusingly two calls later.
130 ///
131 /// The whole [`ObjectInfo`] rather than the id, because a caller that goes on to
132 /// read the commit object needs its size to read it, and asking twice would waste
133 /// the round trip this saves.
134 async fn commit_info(
135 &self,
136 repo: &Path,
137 rev: &RefName,
138 ) -> Result<Option<ObjectInfo>, GitQueryError> {
139 self.pool
140 .info(repo, &format!("{}^{{commit}}", rev.as_str()))
141 .await
142 }
143
144 /// Where a repository lives, matching `DiskGitStorage`'s layout.
145 pub(crate) fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf {
146 self.data_dir
147 .join(handle.as_str())
148 .join(format!("{name}.git"))
149 }
150}
151
152impl GitQuery for DiskGitQuery {
153 async fn default_branch(
154 &self,
155 handle: &OrgName,
156 name: &RepoName,
157 ) -> Result<Option<RefName>, GitQueryError> {
158 let repo = self.repo_path(handle, name);
159
160 // An empty repository's HEAD names a branch that does not exist yet, so
161 // `symbolic-ref` happily answers `main` for a repository with nothing in it.
162 // Whether HEAD *resolves* is the actual question, and it is asked first.
163 let Some(head) = self.pool.info(&repo, "HEAD").await? else {
164 return Ok(None);
165 };
166
167 let branch = run(&repo, [OsStr::new("symbolic-ref"), OsStr::new("HEAD")]).await;
168
169 match branch {
170 Ok(output) => {
171 let full = String::from_utf8_lossy(&output.stdout).trim().to_owned();
172 // `refs/heads/main` rather than `--short`, because `--short` shortens
173 // only as far as is unambiguous and would hand back `heads/main` for a
174 // repository that also has a tag called `main`.
175 let short = full.strip_prefix("refs/heads/").unwrap_or(&full);
176
177 Ok(Some(RefName::from_trusted(short)))
178 }
179 // A detached HEAD is not a state Steid creates, but a repository pushed into
180 // from elsewhere can be in it. The commit is still browsable, so name it
181 // rather than claiming the repository is empty — which is what `Ok(None)`
182 // would mean to a page.
183 Err(_) => Ok(Some(RefName::from_trusted(head.id.as_str()))),
184 }
185 }
186
187 async fn resolve(
188 &self,
189 handle: &OrgName,
190 name: &RepoName,
191 rev: &RefName,
192 ) -> Result<Option<ObjectId>, GitQueryError> {
193 let repo = self.repo_path(handle, name);
194
195 Ok(self.commit_info(&repo, rev).await?.map(|info| info.id))
196 }
197
198 async fn list_tree(
199 &self,
200 handle: &OrgName,
201 name: &RepoName,
202 rev: &RefName,
203 path: &RepoPath,
204 ) -> Result<Option<Vec<TreeEntry>>, GitQueryError> {
205 let repo = self.repo_path(handle, name);
206
207 let Some(info) = self.pool.info(&repo, &tree_spec(rev, path)).await? else {
208 return Ok(None);
209 };
210
211 // A file is not a directory. Asking `ls-tree` anyway is a fatal error, which is
212 // exactly the confusion this check exists to avoid.
213 if info.kind != ObjectKind::Tree {
214 return Ok(None);
215 }
216
217 // The tree object itself, read from the kept-alive `--batch` and parsed here.
218 // `ls-tree --long` used to do both jobs in one process; the object carries no
219 // sizes, so they are asked for separately below — still no fork, and one round
220 // trip for the whole directory rather than one per entry.
221 let mut entries = parse_tree_object(&self.pool.contents(&repo, &info).await?)?;
222
223 // Only what a listing shows a size for. A tree and a submodule have none, and
224 // asking about a submodule's commit would be asking about an object that lives
225 // in a repository Steid cannot see.
226 let sized: Vec<usize> = entries
227 .iter()
228 .enumerate()
229 .filter(|(_, entry)| matches!(entry.kind, EntryKind::Blob | EntryKind::Symlink))
230 .map(|(index, _)| index)
231 .collect();
232
233 let specs: Vec<String> = sized
234 .iter()
235 .map(|index| entries[*index].id.as_str().to_owned())
236 .collect();
237
238 for (index, size) in sized.iter().zip(self.pool.info_many(&repo, &specs).await?) {
239 entries[*index].size = size.map(|size| size.size);
240 }
241
242 Ok(Some(entries))
243 }
244
245 async fn last_commits(
246 &self,
247 handle: &OrgName,
248 name: &RepoName,
249 rev: &RefName,
250 path: &RepoPath,
251 entries: &[String],
252 ) -> Result<HashMap<String, EntryCommit>, GitQueryError> {
253 let repo = self.repo_path(handle, name);
254
255 if entries.is_empty() {
256 return Ok(HashMap::new());
257 }
258
259 // Resolved first, as everywhere here: `git log` is fatal on a revision that
260 // names nothing, and an empty repository has no directory to attribute anyway.
261 let Some(info) = self.commit_info(&repo, rev).await? else {
262 return Ok(HashMap::new());
263 };
264
265 // `-z` for the reason `log` uses it — a path may contain a newline, and the
266 // alternative is git's C-style quoting, which would have to be undone here.
267 // `--name-only` rather than `--name-status`: what changed is not shown, only
268 // that something did.
269 let count = format!("--max-count={LAST_COMMIT_SCAN}");
270
271 let mut args: Vec<&OsStr> = vec![
272 OsStr::new("log"),
273 OsStr::new(LAST_COMMIT_FORMAT),
274 OsStr::new("--name-only"),
275 OsStr::new("-z"),
276 OsStr::new(&count),
277 OsStr::new(info.id.as_str()),
278 ];
279
280 // The pathspec narrows the walk to the directory being listed, which is what
281 // makes the cap generous enough to be useful: 500 commits *that touched this
282 // directory*, not 500 commits of the repository. The root needs none.
283 let prefix = if path.is_root() {
284 String::new()
285 } else {
286 args.push(OsStr::new("--"));
287 args.push(OsStr::new(path.as_str()));
288
289 format!("{}/", path.as_str())
290 };
291
292 let output = run(&repo, args).await?;
293
294 Ok(attribute(&output.stdout, &prefix, entries))
295 }
296
297 async fn read_blob(
298 &self,
299 handle: &OrgName,
300 name: &RepoName,
301 rev: &RefName,
302 path: &RepoPath,
303 max_bytes: u64,
304 ) -> Result<Option<Blob>, GitQueryError> {
305 let repo = self.repo_path(handle, name);
306
307 // The root is a tree, and `{rev}:` is how git spells it — but a caller asking to
308 // read the root is asking for a file that is not there.
309 if path.is_root() {
310 return Ok(None);
311 }
312
313 let Some(info) = self.pool.info(&repo, &tree_spec(rev, path)).await? else {
314 return Ok(None);
315 };
316
317 // Symlinks are blobs whose content is the target path, and are read as such:
318 // showing where a link points is more use than a blank page. Trees and
319 // submodules are not files.
320 if info.kind != ObjectKind::Blob {
321 return Ok(None);
322 }
323
324 // The size comes from the object header, so an oversized file is never read.
325 // Doing this the other way round — read, then measure — is how one URL becomes
326 // an out-of-memory kill.
327 let content = if info.size > max_bytes {
328 None
329 } else {
330 Some(self.pool.contents(&repo, &info).await?)
331 };
332
333 Ok(Some(Blob {
334 id: info.id,
335 size: info.size,
336 content,
337 }))
338 }
339
340 async fn log(
341 &self,
342 handle: &OrgName,
343 name: &RepoName,
344 rev: &RefName,
345 offset: usize,
346 limit: usize,
347 ) -> Result<Vec<CommitSummary>, GitQueryError> {
348 let repo = self.repo_path(handle, name);
349
350 // `git log` on a repository with no commits is a fatal error, and so is a log of
351 // a branch that does not exist. Resolving first turns both into the empty list
352 // the port's signature promises, without having to read meaning into a stderr
353 // string that is localised and free to change between git versions.
354 let Some(info) = self.commit_info(&repo, rev).await? else {
355 return Ok(Vec::new());
356 };
357
358 // The first commit of a log *is* the revision it was asked about, so the
359 // commonest log of all — the landing page's latest-commit bar — needs no walk
360 // and no process: the commit object read through `--batch` says everything the
361 // bar shows. Everything wider still walks history, which is what `git log` is
362 // for and what a batch process cannot do.
363 if offset == 0 && limit == 1 {
364 let detail = parse_commit_object(&info.id, &self.pool.contents(&repo, &info).await?)?;
365
366 return Ok(vec![CommitSummary {
367 id: detail.id,
368 summary: detail.summary,
369 author_name: detail.author_name,
370 committed_at: detail.committed_at,
371 }]);
372 }
373
374 let commit = info.id;
375
376 if limit == 0 {
377 return Ok(Vec::new());
378 }
379
380 // Every separator is a NUL: `-z` between commits, `%x00` between fields. A
381 // commit message contains newlines as a matter of course, and a name can contain
382 // almost anything, so splitting on lines or whitespace would misread real
383 // history rather than exotic history.
384 // `--skip` rather than a cursor: git's log order interleaves parallel lines of
385 // history by date, so only git can say what the 51st commit is. See the port.
386 let count = format!("--max-count={limit}");
387 let skip = format!("--skip={offset}");
388
389 let output = run(
390 &repo,
391 [
392 OsStr::new("log"),
393 OsStr::new("-z"),
394 OsStr::new(&count),
395 OsStr::new(&skip),
396 OsStr::new(LOG_FORMAT),
397 OsStr::new(commit.as_str()),
398 ],
399 )
400 .await?;
401
402 parse_log(&output.stdout)
403 }
404
405 async fn log_entries(
406 &self,
407 handle: &OrgName,
408 name: &RepoName,
409 rev: &RefName,
410 limit: usize,
411 ) -> Result<Vec<CommitEntry>, GitQueryError> {
412 let repo = self.repo_path(handle, name);
413
414 // Resolved first for [`log`]'s reason: `git log` is fatal on a repository with no
415 // commits and on a branch that is not there, and both are the empty list here.
416 let Some(commit) = self.resolve(handle, name, rev).await? else {
417 return Ok(Vec::new());
418 };
419
420 if limit == 0 {
421 return Ok(Vec::new());
422 }
423
424 let count = format!("--max-count={limit}");
425
426 let output = run(
427 &repo,
428 [
429 OsStr::new("log"),
430 OsStr::new("-z"),
431 OsStr::new(&count),
432 OsStr::new(ENTRY_FORMAT),
433 OsStr::new(commit.as_str()),
434 ],
435 )
436 .await?;
437
438 parse_log_entries(&output.stdout)
439 }
440
441 async fn list_refs(
442 &self,
443 handle: &OrgName,
444 name: &RepoName,
445 ) -> Result<Vec<GitRef>, GitQueryError> {
446 let repo = self.repo_path(handle, name);
447
448 // One fork, ~14ms — see the port's note. `for-each-ref` is asked for both
449 // namespaces at once rather than once each, because the cost here is the
450 // process, not the question.
451 //
452 // Every field separator is a NUL, for the same reason `log` uses one: a tag name
453 // is close to arbitrary text once git's own restrictions are met, and splitting
454 // on whitespace would misread a real name. The patterns are literals, so unlike
455 // a revision from a URL there is nothing here that could be read as a flag.
456 let output = run(
457 &repo,
458 [
459 OsStr::new("for-each-ref"),
460 OsStr::new(REF_FORMAT),
461 OsStr::new("refs/heads/"),
462 OsStr::new("refs/tags/"),
463 ],
464 )
465 .await?;
466
467 Ok(parse_refs(&output.stdout))
468 }
469
470 async fn count_commits(
471 &self,
472 handle: &OrgName,
473 name: &RepoName,
474 rev: &RefName,
475 ) -> Result<u64, GitQueryError> {
476 let repo = self.repo_path(handle, name);
477
478 // Resolved first, for the same reason `log` resolves first: `rev-list` on an
479 // empty repository or an unknown branch is a fatal error, and the port promises
480 // a count rather than a failure. **That makes this two processes, not one** —
481 // the price of keeping the module's rule that a non-zero exit is always a real
482 // fault. Handing the resolved id to `rev-list` also means nothing from a URL
483 // reaches git's revision parser here.
484 let Some(commit) = self.resolve(handle, name, rev).await? else {
485 return Ok(0);
486 };
487
488 let output = run(
489 &repo,
490 [
491 OsStr::new("rev-list"),
492 OsStr::new("--count"),
493 OsStr::new(commit.as_str()),
494 ],
495 )
496 .await?;
497
498 let count = String::from_utf8_lossy(&output.stdout);
499 let count = count.trim();
500
501 count.parse().map_err(|_| {
502 GitQueryError::new(format!(
503 "git counted commits as {count:?}, which is not a number"
504 ))
505 })
506 }
507
508 async fn latest_tag(
509 &self,
510 handle: &OrgName,
511 name: &RepoName,
512 ) -> Result<Option<TagSummary>, GitQueryError> {
513 let repo = self.repo_path(handle, name);
514
515 // `--count=1` after `--sort` is the whole of the work: git does the ordering,
516 // so this is one process regardless of how many tags a repository carries.
517 // Every argument is a literal — nothing from a URL reaches this call.
518 let output = run(
519 &repo,
520 [
521 OsStr::new("for-each-ref"),
522 OsStr::new("--sort=-creatordate"),
523 OsStr::new("--count=1"),
524 OsStr::new(TAG_FORMAT),
525 OsStr::new("refs/tags/"),
526 ],
527 )
528 .await?;
529
530 Ok(parse_latest_tag(&output.stdout))
531 }
532
533 async fn branches(
534 &self,
535 handle: &OrgName,
536 name: &RepoName,
537 ) -> Result<Vec<BranchRow>, GitQueryError> {
538 let repo = self.repo_path(handle, name);
539
540 // One process for the whole branches page. The sort is git's because it is
541 // free there and would otherwise be a second pass in Rust over the same rows,
542 // and `%(HEAD)` is what saves the page a `symbolic-ref` for the default branch.
543 // Every argument is a literal — nothing from a URL reaches this call.
544 let output = run(
545 &repo,
546 [
547 OsStr::new("for-each-ref"),
548 OsStr::new("--sort=-committerdate"),
549 OsStr::new(BRANCH_FORMAT),
550 OsStr::new("refs/heads/"),
551 ],
552 )
553 .await?;
554
555 parse_branches(&output.stdout)
556 }
557
558 async fn tags(&self, handle: &OrgName, name: &RepoName) -> Result<Vec<TagRow>, GitQueryError> {
559 let repo = self.repo_path(handle, name);
560
561 let output = run(
562 &repo,
563 [
564 OsStr::new("for-each-ref"),
565 OsStr::new("--sort=-creatordate"),
566 OsStr::new(TAG_ROW_FORMAT),
567 OsStr::new("refs/tags/"),
568 ],
569 )
570 .await?;
571
572 parse_tags(&output.stdout)
573 }
574
575 async fn grep(
576 &self,
577 handle: &OrgName,
578 name: &RepoName,
579 commit: &ObjectId,
580 query: &str,
581 limit: usize,
582 ) -> Result<Vec<GrepHit>, GitQueryError> {
583 let repo = self.repo_path(handle, name);
584
585 // **One of the two commands here whose exit status is an answer** — the other
586 // is `merge_base`. `git grep` exits 1 when it found nothing, which is not a
587 // failure. Everything else in this module keeps the rule that a non-zero exit
588 // is a fault; the exception is spelled out in the call rather than hidden in
589 // the helper.
590 //
591 // `-F` fixed strings, `-I` skips binary files, `-n --column` locate the match,
592 // and `-z` makes the output parseable — see `parse_grep_output`. The query is
593 // passed after `-e`, so a query starting with `-` is a search rather than a
594 // flag, and the commit is one git resolved rather than anything from a URL.
595 //
596 // **Read through a cap rather than collected**, which is [`diff`]'s reason and
597 // is sharper here: the search page is anonymous, unthrottled, and takes its
598 // query from a URL, so `?q=e` on a large repository had git write every matching
599 // line in it into this process's memory before `parse_grep_output` threw all but
600 // the first thousand away. One letter over Steid's own source is already 5 MB.
601 // The caller only ever keeps
602 // [`SEARCH_MAX_MATCHES`](crate::application::SEARCH_MAX_MATCHES) hits, so a
603 // truncated tail costs a result nobody was going to be shown; a partial final
604 // record simply fails to parse and is dropped.
605 let (stdout, _truncated) = run_capped_allowing(
606 &repo,
607 [
608 OsStr::new("grep"),
609 OsStr::new("-I"),
610 OsStr::new("-n"),
611 OsStr::new("-z"),
612 OsStr::new("-F"),
613 OsStr::new("--column"),
614 OsStr::new("--no-color"),
615 OsStr::new("-e"),
616 OsStr::new(query),
617 OsStr::new(commit.as_str()),
618 OsStr::new("--"),
619 ],
620 MAX_GREP_BYTES,
621 &[NO_MATCHES],
622 )
623 .await?;
624
625 Ok(parse_grep_output(&stdout, commit, limit))
626 }
627
628 async fn commit(
629 &self,
630 handle: &OrgName,
631 name: &RepoName,
632 rev: &RefName,
633 ) -> Result<Option<CommitDetail>, GitQueryError> {
634 let repo = self.repo_path(handle, name);
635
636 // Resolved first, as everywhere else in this module: the `^{commit}` peel refuses
637 // a tree or a blob and follows an annotated tag to what it points at, so what is
638 // read below is known to be a commit.
639 //
640 // **No `git log` any more.** A one-commit log was two processes — resolve, then
641 // format — and is now two lines written to processes that are already running:
642 // the peel on `--batch-check`, the object itself on `--batch`. Formatting is
643 // [`parse_commit_object`]'s job rather than git's.
644 let Some(info) = self.commit_info(&repo, rev).await? else {
645 return Ok(None);
646 };
647
648 parse_commit_object(&info.id, &self.pool.contents(&repo, &info).await?).map(Some)
649 }
650
651 async fn diff(
652 &self,
653 handle: &OrgName,
654 name: &RepoName,
655 base: Option<&ObjectId>,
656 head: &ObjectId,
657 max_bytes: u64,
658 ) -> Result<RawDiff, GitQueryError> {
659 let repo = self.repo_path(handle, name);
660
661 // `diff-tree` rather than `diff`, for both shapes: it is the plumbing command,
662 // it takes tree-ish arguments rather than revision expressions, and it does not
663 // consult a working tree that a bare repository does not have.
664 //
665 // The flags, each load-bearing:
666 // --no-commit-id `-p` would otherwise print the commit's id as a first line
667 // -p the patch itself
668 // -M rename detection, so a moved file is one entry, not two
669 // --numstat the per-file counts, written *before* the patch — which is
670 // what makes them survive the byte cap below
671 // --no-color the caller renders; git must not send escape sequences
672 // --root a first commit is diffed against nothing rather than
673 // skipped, which is the only way to see what it introduced
674 let mut args: Vec<&OsStr> = vec![
675 OsStr::new("diff-tree"),
676 OsStr::new("--no-commit-id"),
677 OsStr::new("-p"),
678 OsStr::new("-M"),
679 OsStr::new("--numstat"),
680 OsStr::new("--no-color"),
681 ];
682
683 match base {
684 Some(base) => {
685 args.push(OsStr::new(base.as_str()));
686 }
687 None => args.push(OsStr::new("--root")),
688 }
689
690 args.push(OsStr::new(head.as_str()));
691
692 let (stdout, truncated) = run_capped(&repo, args, max_bytes).await?;
693 let (numstat, patch) = split_numstat(&stdout);
694
695 Ok(RawDiff {
696 numstat: numstat.to_vec(),
697 patch: patch.to_vec(),
698 truncated,
699 })
700 }
701
702 async fn merge_base(
703 &self,
704 handle: &OrgName,
705 name: &RepoName,
706 base: &ObjectId,
707 head: &ObjectId,
708 ) -> Result<Option<ObjectId>, GitQueryError> {
709 let repo = self.repo_path(handle, name);
710
711 // **The other exception to this module's rule that a non-zero exit is a
712 // fault**, `grep` being the first. `git merge-base` documents exit 1 as "no
713 // merge base found" and reserves 128 for real errors, so the two are
714 // distinguishable here in a way they are not for `rev-parse` — which is why the
715 // rule exists at all. Two histories with no common ancestor is a thing a compare
716 // page must be able to say, and the arguments are resolved object ids, so there
717 // is nothing else exit 1 can mean.
718 let output = run_allowing(
719 &repo,
720 [
721 OsStr::new("merge-base"),
722 OsStr::new(base.as_str()),
723 OsStr::new(head.as_str()),
724 ],
725 &[NO_COMMON_ANCESTOR],
726 )
727 .await?;
728
729 let id = String::from_utf8_lossy(&output.stdout);
730 let id = id.trim();
731
732 if id.is_empty() {
733 return Ok(None);
734 }
735
736 Ok(Some(ObjectId::new(id).map_err(|error| {
737 GitQueryError::new(format!("git named a bad merge base: {error}"))
738 })?))
739 }
740
741 async fn log_between(
742 &self,
743 handle: &OrgName,
744 name: &RepoName,
745 base: Option<&ObjectId>,
746 head: &ObjectId,
747 offset: usize,
748 limit: usize,
749 ) -> Result<Vec<CommitSummary>, GitQueryError> {
750 let repo = self.repo_path(handle, name);
751
752 if limit == 0 {
753 return Ok(Vec::new());
754 }
755
756 // Both ends are already object ids, so the range is built here rather than
757 // taken from a URL — `..` is the one piece of revision syntax this module
758 // writes itself, and `RefName` refuses it precisely so that nothing else can.
759 let range = match base {
760 Some(base) => format!("{}..{}", base.as_str(), head.as_str()),
761 None => head.as_str().to_owned(),
762 };
763 let count = format!("--max-count={limit}");
764 let skip = format!("--skip={offset}");
765
766 let output = run(
767 &repo,
768 [
769 OsStr::new("log"),
770 OsStr::new("-z"),
771 OsStr::new(&count),
772 OsStr::new(&skip),
773 OsStr::new(LOG_FORMAT),
774 OsStr::new(&range),
775 ],
776 )
777 .await?;
778
779 parse_log(&output.stdout)
780 }
781
782 async fn count_between(
783 &self,
784 handle: &OrgName,
785 name: &RepoName,
786 base: Option<&ObjectId>,
787 head: &ObjectId,
788 ) -> Result<usize, GitQueryError> {
789 let repo = self.repo_path(handle, name);
790
791 // The range is built here from two resolved ids, exactly as `log_between`
792 // builds it — `..` is the only revision syntax this module writes itself.
793 let range = match base {
794 Some(base) => format!("{}..{}", base.as_str(), head.as_str()),
795 None => head.as_str().to_owned(),
796 };
797
798 let output = run(
799 &repo,
800 [
801 OsStr::new("rev-list"),
802 OsStr::new("--count"),
803 OsStr::new(&range),
804 ],
805 )
806 .await?;
807
808 let count = String::from_utf8_lossy(&output.stdout);
809 let count = count.trim();
810
811 count.parse().map_err(|_| {
812 GitQueryError::new(format!(
813 "git counted commits as {count:?}, which is not a number"
814 ))
815 })
816 }
817
818 async fn blame(
819 &self,
820 handle: &OrgName,
821 name: &RepoName,
822 rev: &RefName,
823 path: &RepoPath,
824 ) -> Result<Option<Blame>, GitQueryError> {
825 let repo = self.repo_path(handle, name);
826
827 // `git blame` is fatal on an unknown revision *and* on a path that is not in it,
828 // so one `--batch-check` on `{rev}:{path}` settles both before the expensive
829 // command runs — the module's rule that a non-zero exit is a real fault only
830 // holds because of checks like this one.
831 let Some(info) = self.pool.info(&repo, &tree_spec(rev, path)).await? else {
832 return Ok(None);
833 };
834
835 // A directory has no lines. Blaming one is another fatal error.
836 if info.kind != ObjectKind::Blob {
837 return Ok(None);
838 }
839
840 // The revision is named rather than the blob id: blame walks *history*, and a
841 // blob knows nothing about which commits reached it. `--` separates the revision
842 // from the path so neither can be read as the other, and `RefName` and
843 // `RepoPath` have already refused a leading hyphen.
844 let output = run(
845 &repo,
846 [
847 OsStr::new("blame"),
848 OsStr::new("--porcelain"),
849 OsStr::new(rev.as_str()),
850 OsStr::new("--"),
851 OsStr::new(path.as_str()),
852 ],
853 )
854 .await?;
855
856 Ok(Some(parse_blame(&output.stdout)))
857 }
858
859 async fn ref_snapshot(
860 &self,
861 handle: &OrgName,
862 name: &RepoName,
863 ) -> Result<Vec<(RefName, ObjectId)>, GitQueryError> {
864 let repo = self.repo_path(handle, name);
865
866 // The whole of `refs/` in one process. Unlike `list_refs`, which asks for the
867 // two namespaces a switcher shows, this is diffed around a push and a ref that
868 // was not asked about is a ref whose change goes unrecorded. The pattern is a
869 // literal; nothing from a URL reaches this call.
870 let output = run(
871 &repo,
872 [
873 OsStr::new("for-each-ref"),
874 OsStr::new(SNAPSHOT_FORMAT),
875 OsStr::new("refs/"),
876 ],
877 )
878 .await?;
879
880 Ok(parse_ref_snapshot(&output.stdout))
881 }
882
883 async fn log_at_path(
884 &self,
885 handle: &OrgName,
886 name: &RepoName,
887 rev: &RefName,
888 path: &RepoPath,
889 follow: bool,
890 offset: usize,
891 limit: usize,
892 ) -> Result<Vec<CommitSummary>, GitQueryError> {
893 let repo = self.repo_path(handle, name);
894
895 // Resolved first, for [`log`]'s reason: a log of a revision that names nothing
896 // is fatal, and the port promises an empty list rather than a failure.
897 let Some(info) = self.commit_info(&repo, rev).await? else {
898 return Ok(Vec::new());
899 };
900
901 if limit == 0 {
902 return Ok(Vec::new());
903 }
904
905 let count = format!("--max-count={limit}");
906 let skip = format!("--skip={offset}");
907 let mut args: Vec<&OsStr> = vec![
908 OsStr::new("log"),
909 OsStr::new("-z"),
910 OsStr::new(&count),
911 OsStr::new(&skip),
912 OsStr::new(LOG_FORMAT),
913 ];
914
915 // `--follow` before the revision, and only for a file: git refuses it for a
916 // directory and for more than one pathspec, and the refusal is a fatal exit
917 // rather than an empty answer.
918 if follow {
919 args.push(OsStr::new("--follow"));
920 }
921
922 args.push(OsStr::new(info.id.as_str()));
923 // Everything after `--` is a path, which is what stops a path that looks like a
924 // flag being read as one — `RepoPath` refuses a leading `-` as well, so this is
925 // the second of two locks on the same door.
926 args.push(OsStr::new("--"));
927 args.push(OsStr::new(path.as_str()));
928
929 let output = run(&repo, args).await?;
930
931 parse_log(&output.stdout)
932 }
933
934 async fn count_commits_at_path(
935 &self,
936 handle: &OrgName,
937 name: &RepoName,
938 rev: &RefName,
939 path: &RepoPath,
940 follow: bool,
941 ) -> Result<CommitCount, GitQueryError> {
942 let repo = self.repo_path(handle, name);
943
944 let Some(info) = self.commit_info(&repo, rev).await? else {
945 return Ok(CommitCount::default());
946 };
947
948 // One more than the cap, so "there are more" is a fact the walk reports rather
949 // than something inferred from hitting the limit exactly.
950 let scan = format!("-n{}", FOLLOWED_LOG_SCAN + 1);
951
952 // **`rev-list` has no `--follow`.** It is a `git log` option, and `rev-list`
953 // answers a usage error rather than ignoring it — so a followed count is a log
954 // of ids, counted here. Only the ids: `%H` alone keeps what git writes
955 // proportional to the number of commits rather than to their messages.
956 let mut args: Vec<&OsStr> = if follow {
957 vec![
958 OsStr::new("log"),
959 OsStr::new("--follow"),
960 OsStr::new("--format=%H"),
961 OsStr::new(&scan),
962 ]
963 } else {
964 vec![OsStr::new("rev-list"), OsStr::new("--count")]
965 };
966
967 args.push(OsStr::new(info.id.as_str()));
968 args.push(OsStr::new("--"));
969 args.push(OsStr::new(path.as_str()));
970
971 let output = run(&repo, args).await?;
972
973 if follow {
974 let counted = output.stdout.iter().filter(|byte| **byte == b'\n').count();
975
976 return Ok(CommitCount {
977 total: counted.min(FOLLOWED_LOG_SCAN) as u64,
978 capped: counted > FOLLOWED_LOG_SCAN,
979 });
980 }
981
982 let count = String::from_utf8_lossy(&output.stdout);
983 let count = count.trim();
984
985 Ok(CommitCount {
986 total: count.parse().map_err(|_| {
987 GitQueryError::new(format!(
988 "git counted commits as {count:?}, which is not a number"
989 ))
990 })?,
991 capped: false,
992 })
993 }
994
995 async fn symlink_targets(
996 &self,
997 handle: &OrgName,
998 name: &RepoName,
999 ids: &[ObjectId],
1000 ) -> Result<HashMap<ObjectId, String>, GitQueryError> {
1001 let repo = self.repo_path(handle, name);
1002 let mut targets = HashMap::new();
1003
1004 if ids.is_empty() {
1005 return Ok(targets);
1006 }
1007
1008 // Sized in bulk first, because `contents` reads an object the batch-check has
1009 // already described — the same two steps a tree listing takes, and for the same
1010 // reason: the reply header is then a check rather than a parse.
1011 let specs: Vec<String> = ids.iter().map(|id| id.as_str().to_owned()).collect();
1012
1013 for info in self
1014 .pool
1015 .info_many(&repo, &specs)
1016 .await?
1017 .into_iter()
1018 .flatten()
1019 {
1020 if info.kind != ObjectKind::Blob {
1021 continue;
1022 }
1023
1024 let bytes = self.pool.contents(&repo, &info).await?;
1025
1026 // A target that is not UTF-8 is left out rather than lossily rendered: the
1027 // row simply says nothing about where the link goes, which is honest.
1028 if let Ok(target) = String::from_utf8(bytes) {
1029 targets.insert(info.id, target);
1030 }
1031 }
1032
1033 Ok(targets)
1034 }
1035
1036 async fn merge_preview(
1037 &self,
1038 handle: &OrgName,
1039 name: &RepoName,
1040 target: &ObjectId,
1041 source: &ObjectId,
1042 ) -> Result<MergePreview, GitQueryError> {
1043 // Asked of the cache first. The pair of commit ids determines the answer
1044 // completely — git objects are content-addressed — so a hit is the same answer
1045 // this would compute, and it saves both the merge and the unreferenced objects
1046 // `--write-tree` writes on every run.
1047 if let Some(cached) = self.merges.get(target, source) {
1048 return Ok(cached);
1049 }
1050
1051 let repo = self.repo_path(handle, name);
1052
1053 // **The third exception to this module's rule that a non-zero exit is a
1054 // fault**, and the last: `git merge-tree` documents exit 1 as "the merge has
1055 // conflicts" and reserves 128 and above for what actually went wrong. A
1056 // conflict is the answer the page came for, not a failure — a pull request
1057 // whose branches disagree is an ordinary pull request.
1058 //
1059 // Both arguments are object ids git resolved, so there is nothing else exit 1
1060 // can mean here.
1061 let output = run_allowing(
1062 &repo,
1063 [
1064 OsStr::new("merge-tree"),
1065 OsStr::new("--write-tree"),
1066 OsStr::new(target.as_str()),
1067 OsStr::new(source.as_str()),
1068 ],
1069 &[MERGE_CONFLICTED],
1070 )
1071 .await?;
1072
1073 let preview = parse_merge_tree(
1074 &output.stdout,
1075 output.status.code() == Some(MERGE_CONFLICTED),
1076 )?;
1077
1078 self.merges.put(target, source, preview.clone());
1079
1080 Ok(preview)
1081 }
1082}
1083
1084/// How far back a directory's last-commit column looks.
1085///
1086/// The walk is already narrowed to the directory by a pathspec, so this is 500 commits
1087/// *that touched this directory* — deep enough that a real listing is fully attributed
1088/// long before it, and shallow enough that a page has a bound on a repository of any
1089/// age. An entry still unattributed at the cap shows nothing, which is the honest answer:
1090/// the alternative is guessing, and a wrong commit beside a filename is worse than a
1091/// blank.
1092const LAST_COMMIT_SCAN: usize = 500;
1093
1094/// How far back a followed path history counts.
1095///
1096/// The last-commit column's cap, for the same reason and the same number. A followed
1097/// walk is the expensive one — `--follow` reads a tree per commit looking for the rename
1098/// that gave the file its name, and `rev-list` cannot do it at all — so on a long
1099/// history this is the read likeliest to meet the 20 s timeout, and a timeout is a page
1100/// with nothing on it. Past the cap the page says `500+`, which is what a reader deciding
1101/// whether they have seen the whole history actually needs to know.
1102pub(crate) const FOLLOWED_LOG_SCAN: usize = 500;
1103
1104/// A unix timestamp as a `SystemTime`, including the negative ones.
1105///
1106/// A commit dated before 1970 is either a lie or an import from something older than
1107/// git, and both exist in real repositories. `UNIX_EPOCH + Duration` would panic on the
1108/// subtraction it cannot do.
1109fn unix_time(seconds: i64) -> SystemTime {
1110 match u64::try_from(seconds) {
1111 Ok(seconds) => UNIX_EPOCH + Duration::from_secs(seconds),
1112 Err(_) => UNIX_EPOCH - Duration::from_secs(seconds.unsigned_abs()),
1113 }
1114}
1115
1116/// Runs a git command inside a repository and fails on a non-zero exit.
1117///
1118/// Only ever used for commands whose subject has already been confirmed to exist, so a
1119/// failure really is a failure. Built from [`git_command`] so the host isolation 0006
1120/// insists on cannot drift out of this module.
1121/// How long one read-side `git` process may run before it is killed.
1122///
1123/// Every read here is a subprocess on a request path, and nothing bounded it before
1124/// blame and grep arrived — either can run for a long time on a large repository, and
1125/// a request that never finishes holds a worker for as long as the client waits.
1126/// Twenty seconds is far above any read a page should make and far below "hung".
1127const GIT_TIMEOUT: Duration = Duration::from_secs(20);
1128
1129/// How much of a plain read's output one request may collect.
1130///
1131/// `run` used to hand git an unbounded `Vec` — the last uncapped read on the request
1132/// path once grep and diff had theirs, and the reason it was left is that every command
1133/// that goes through here is *already* bounded by its own arguments: `log` by
1134/// `--max-count`, `cat-file` by an object size read from its header first,
1135/// `for-each-ref` by how many refs exist. None of those is a hole in the shape grep's
1136/// `?q=e` was. This is the backstop for the day one of them stops being true, so it is
1137/// set where no honest answer ever reaches it: 32 MiB is eight times the grep cap and
1138/// something like a hundred thousand refs' worth of `for-each-ref`.
1139///
1140/// Exceeding it is [`GitQueryError::too_large`] rather than a truncation, because these
1141/// outputs are parsed whole — see that constructor.
1142const MAX_RUN_BYTES: u64 = 32 * 1024 * 1024;
1143
1144async fn run<I, S>(repo: &Path, args: I) -> Result<Output, GitQueryError>
1145where
1146 I: IntoIterator<Item = S>,
1147 S: AsRef<OsStr>,
1148{
1149 run_bounded(repo, args, MAX_RUN_BYTES).await
1150}
1151
1152/// [`run`] with an explicit cap, so the too-large path can be tested without asking git
1153/// for 32 MiB of anything.
1154async fn run_bounded<I, S>(repo: &Path, args: I, max_bytes: u64) -> Result<Output, GitQueryError>
1155where
1156 I: IntoIterator<Item = S>,
1157 S: AsRef<OsStr>,
1158{
1159 let (stdout, truncated) = run_capped(repo, args, max_bytes).await?;
1160
1161 if truncated {
1162 return Err(GitQueryError::too_large(max_bytes));
1163 }
1164
1165 // Only `stdout` is ever read off this — the status rule and stderr are consumed
1166 // inside `run_capped_allowing`, which returns `Err` for a non-zero exit before this
1167 // line, so a synthesised success is the state that actually held.
1168 Ok(Output {
1169 status: std::process::ExitStatus::default(),
1170 stdout,
1171 stderr: Vec::new(),
1172 })
1173}
1174
1175// The two exit statuses this module reads as answers rather than as faults. Both are 1
1176// and they are separate constants on purpose: what makes each of them legible is the
1177// question it answers, not the number. See [`run_allowing`], which is the only way
1178// either reaches a command.
1179
1180/// What `git grep` exits with when it matched nothing.
1181const NO_MATCHES: i32 = 1;
1182
1183/// How much of `git grep`'s output one search may read.
1184///
1185/// Generous against any search worth showing — the page keeps at most
1186/// [`SEARCH_MAX_MATCHES`](crate::application::SEARCH_MAX_MATCHES) hits of at most
1187/// [`MAX_LINE_CHARS`](crate::application::MAX_LINE_CHARS) each, which is two orders of
1188/// magnitude below this — and a hard ceiling against the one that is not: a
1189/// single-character query matches nearly every line in the repository, and every one of
1190/// them used to be collected before being discarded.
1191const MAX_GREP_BYTES: u64 = 4 * 1024 * 1024;
1192
1193/// What `git merge-base` exits with for two commits that share no ancestor — documented
1194/// as an answer, with 128 reserved for real errors.
1195const NO_COMMON_ANCESTOR: i32 = 1;
1196
1197/// What `git merge-tree` exits with when the merge has conflicts — documented as an
1198/// answer, with 128 and above reserved for what actually went wrong.
1199const MERGE_CONFLICTED: i32 = 1;
1200
1201/// [`run`] for a command whose exit status is partly an answer.
1202///
1203/// Exists for `git grep`, `git merge-base` and `git merge-tree` alone — grep's 1 is
1204/// "matched nothing", merge-base's is "no common ancestor" and merge-tree's is "the
1205/// merge has conflicts", all three promised by git's manual. Every other command here is
1206/// asked about something `cat-file --batch-check` has already confirmed exists, which is
1207/// what makes the module's "a non-zero exit is always a fault" rule hold. These three are
1208/// asked questions whose answer can legitimately be "there is none".
1209async fn run_allowing<I, S>(repo: &Path, args: I, allowed: &[i32]) -> Result<Output, GitQueryError>
1210where
1211 I: IntoIterator<Item = S>,
1212 S: AsRef<OsStr>,
1213{
1214 run_within_allowing(repo, args, GIT_TIMEOUT, allowed).await
1215}
1216
1217/// [`run_allowing`] with an explicit limit, so the timeout path can be tested without
1218/// waiting twenty seconds for it.
1219///
1220/// Test-only since `run` was capped: the plain read now goes through
1221/// [`run_capped`], and this is the remaining door onto [`run_within_allowing`], which
1222/// is still what `run_allowing` uses.
1223#[cfg(test)]
1224async fn run_within<I, S>(repo: &Path, args: I, limit: Duration) -> Result<Output, GitQueryError>
1225where
1226 I: IntoIterator<Item = S>,
1227 S: AsRef<OsStr>,
1228{
1229 run_within_allowing(repo, args, limit, &[]).await
1230}
1231
1232/// The whole of running git: isolation, the timeout, and the status rule.
1233async fn run_within_allowing<I, S>(
1234 repo: &Path,
1235 args: I,
1236 limit: Duration,
1237 allowed: &[i32],
1238) -> Result<Output, GitQueryError>
1239where
1240 I: IntoIterator<Item = S>,
1241 S: AsRef<OsStr>,
1242{
1243 let mut command = git_command();
1244 command
1245 .arg("-C")
1246 .arg(repo)
1247 .args(args)
1248 .stdin(Stdio::null())
1249 // Dropping the future on timeout must take the process with it, or a killed
1250 // request leaves git running to completion for nobody.
1251 .kill_on_drop(true);
1252 count_spawn(&command);
1253
1254 let output = match tokio::time::timeout(limit, command.output()).await {
1255 Ok(result) => {
1256 result.map_err(|error| GitQueryError::new(format!("could not run git: {error}")))?
1257 }
1258 Err(_elapsed) => return Err(GitQueryError::timed_out(limit)),
1259 };
1260
1261 let expected = output
1262 .status
1263 .code()
1264 .is_some_and(|code| allowed.contains(&code));
1265
1266 if !output.status.success() && !expected {
1267 return Err(GitQueryError::new(format!(
1268 "git exited with {}: {}",
1269 output.status,
1270 String::from_utf8_lossy(&output.stderr).trim()
1271 )));
1272 }
1273
1274 Ok(output)
1275}
1276
1277/// Runs a git command and reads at most `max_bytes` of its output.
1278///
1279/// [`run`] collects everything git writes, which is right for a tree listing and wrong
1280/// for a patch: a single commit can legitimately carry hundreds of megabytes of diff,
1281/// and a page must not be able to pull that into memory. So this one reads through a
1282/// pipe and stops, killing the process rather than draining it — an abandoned `git
1283/// diff-tree` writing into a closed pipe is exactly what SIGPIPE is for.
1284///
1285/// Returns the bytes and whether the cap was hit. **The exit status is only checked
1286/// when it was not**: a process killed part-way through has a status that says so, and
1287/// treating that as a failure would turn every oversized diff into a 500.
1288async fn run_capped<I, S>(
1289 repo: &Path,
1290 args: I,
1291 max_bytes: u64,
1292) -> Result<(Vec<u8>, bool), GitQueryError>
1293where
1294 I: IntoIterator<Item = S>,
1295 S: AsRef<OsStr>,
1296{
1297 run_capped_allowing(repo, args, max_bytes, &[]).await
1298}
1299
1300/// [`run_capped`] for a command whose exit status is partly an answer.
1301///
1302/// The capped counterpart of [`run_allowing`], and it exists for `git grep`: exit 1
1303/// means "matched nothing", and the search page is the one capped read whose command
1304/// says that.
1305async fn run_capped_allowing<I, S>(
1306 repo: &Path,
1307 args: I,
1308 max_bytes: u64,
1309 allowed: &[i32],
1310) -> Result<(Vec<u8>, bool), GitQueryError>
1311where
1312 I: IntoIterator<Item = S>,
1313 S: AsRef<OsStr>,
1314{
1315 let mut command = git_command();
1316 command
1317 .arg("-C")
1318 .arg(repo)
1319 .args(args)
1320 .stdin(Stdio::null())
1321 .stdout(Stdio::piped())
1322 .stderr(Stdio::piped())
1323 .kill_on_drop(true);
1324 count_spawn(&command);
1325
1326 let read = async {
1327 let mut child = command
1328 .spawn()
1329 .map_err(|error| GitQueryError::new(format!("could not run git: {error}")))?;
1330
1331 let mut stdout = child.stdout.take().expect("stdout was piped");
1332 let mut bytes = Vec::new();
1333
1334 // One byte past the cap, so hitting it exactly is not mistaken for exceeding
1335 // it. The surplus byte is dropped below.
1336 let limit = max_bytes.saturating_add(1);
1337
1338 (&mut stdout)
1339 .take(limit)
1340 .read_to_end(&mut bytes)
1341 .await
1342 .map_err(|error| GitQueryError::new(format!("could not read from git: {error}")))?;
1343
1344 if bytes.len() as u64 > max_bytes {
1345 bytes.truncate(max_bytes as usize);
1346 // Nothing waits for the exit status: git is still writing, and the whole
1347 // point is not to read the rest. `kill_on_drop` reaps it.
1348 let _ = child.start_kill();
1349
1350 return Ok((bytes, true));
1351 }
1352
1353 // stdout is already drained, so this collects stderr and the status. stderr is
1354 // git's own diagnostics — small by construction, and only read on failure.
1355 let output = child
1356 .wait_with_output()
1357 .await
1358 .map_err(|error| GitQueryError::new(format!("could not wait for git: {error}")))?;
1359
1360 let expected = output
1361 .status
1362 .code()
1363 .is_some_and(|code| allowed.contains(&code));
1364
1365 if !output.status.success() && !expected {
1366 return Err(GitQueryError::new(format!(
1367 "git exited with {}: {}",
1368 output.status,
1369 String::from_utf8_lossy(&output.stderr).trim()
1370 )));
1371 }
1372
1373 Ok((bytes, false))
1374 };
1375
1376 match tokio::time::timeout(GIT_TIMEOUT, read).await {
1377 Ok(result) => result,
1378 Err(_elapsed) => Err(GitQueryError::timed_out(GIT_TIMEOUT)),
1379 }
1380}
1381
1382#[cfg(test)]
1383#[path = "git_query_tests.rs"]
1384mod tests;