steid

@jamesgill /

1//! The `git` binary, behind the ports the application declares.
2//!
3//! One module owns *how* Steid invokes git — see [`run_git`] — so that isolation and
4//! error handling cannot drift between call sites. Milestone 4's protocol commands
5//! belong here too rather than growing a second recipe.
6
7use std::{
8 collections::{HashMap, HashSet},
9 ffi::OsStr,
10 io,
11 path::{Path, PathBuf},
12 process::{Output, Stdio},
13 sync::{Arc, Mutex},
14 time::SystemTime,
15};
16
17use tokio::{
18 fs,
19 io::{AsyncBufReadExt, AsyncReadExt, BufReader},
20 process::{ChildStdout, Command},
21};
22
23use crate::{
24 application::{
25 blame::Blame,
26 port::{
27 ArchiveRequest, Blob, ByteStream, CommitCount, CommitTreeRequest, GitArchive,
28 GitArchiveError, GitImport, GitImportError, GitMerge, GitMergeError, GitMethod,
29 GitProtocolError, GitProtocolServer, GitQuery, GitQueryError, GitRequest, GitResponse,
30 GitStorage, GitStorageError, MergePreview, RawDiff, RepoDir,
31 },
32 },
33 domain::{
34 BranchRow, CommitDetail, CommitEntry, CommitSummary, EntryCommit, GitRef, GrepHit,
35 ImportSource, ObjectId, OrgName, RefKind, RefName, RepoName, RepoPath, TagRow, TagSummary,
36 TreeEntry, is_public,
37 },
38 infrastructure::git_query::FOLLOWED_LOG_SCAN,
39};
40
41/// The most CGI headers `git http-backend` will ever emit, with room to spare.
42///
43/// A guard rather than a real expectation: the header block is read before anything is
44/// streamed, and an unbounded read of a subprocess's stdout is a hang waiting to happen.
45const MAX_CGI_HEADERS: usize = 64;
46
47/// Environment variables that redirect where git reads and writes data.
48///
49/// Steid's own environment must not reach into a repository's layout. These are set
50/// whenever a process is spawned from inside a git hook, which is exactly the shape
51/// Milestone 5 will have, and the failure is silent — objects land somewhere else and
52/// the repository looks empty.
53const REDIRECTING_VARS: &[&str] = &[
54 "GIT_ALTERNATE_OBJECT_DIRECTORIES",
55 "GIT_DIR",
56 "GIT_INDEX_FILE",
57 "GIT_OBJECT_DIRECTORY",
58 "GIT_WORK_TREE",
59];
60
61/// Bare repositories on disk, laid out as `{data_dir}/{handle}/{name}.git`.
62#[derive(Debug, Clone)]
63pub struct DiskGitStorage {
64 data_dir: PathBuf,
65}
66
67impl DiskGitStorage {
68 pub fn new(data_dir: impl Into<PathBuf>) -> Self {
69 Self {
70 data_dir: data_dir.into(),
71 }
72 }
73}
74
75impl GitStorage for DiskGitStorage {
76 async fn init_bare(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> {
77 let path = self.repo_path(handle, name);
78
79 // `git init` on an existing repository exits 0 and re-initialises in silence,
80 // so this check has to be ours. A directory with no matching record is an
81 // orphan from a create that died between the two writes; adopting it would
82 // resurface a private repository's objects under a fresh record.
83 if path.exists() {
84 return Err(GitStorageError::AlreadyExists);
85 }
86
87 // No `create_dir_all` for the parent: `git init` creates missing directories.
88 run_git([
89 OsStr::new("init"),
90 OsStr::new("--bare"),
91 OsStr::new("--quiet"),
92 // Skip the template directory, which otherwise seeds every repository with
93 // sixteen `.sample` hooks. Steid installs its own hooks later, and they
94 // would be noise to work around.
95 OsStr::new("--template="),
96 // Explicit, so the host's `init.defaultBranch` cannot decide what the
97 // default branch of a Steid repository is.
98 OsStr::new("--initial-branch=main"),
99 // `RepoName` already forbids a leading hyphen; this makes it impossible for
100 // a path to be read as a flag at the boundary where it costs nothing.
101 OsStr::new("--"),
102 path.as_os_str(),
103 ])
104 .await?;
105
106 // A second process, once per repository ever created — creation is not a hot
107 // path. `git init --bare` leaves `core.logAllRefUpdates` off, so a bare
108 // repository keeps no reflog at all and `REMOTE_USER` has nowhere to be
109 // recorded: `git reflog show main` answers nothing, and who moved a ref is
110 // unknowable even though Steid knew at the time.
111 //
112 // Set here rather than passed as `git -c … init`, because `-c` configures that
113 // one invocation and is not written into the repository it creates.
114 //
115 // Repositories created before this stay without one. `git config
116 // core.logAllRefUpdates true` in the bare repo is the whole of the fix.
117 run_git([
118 OsStr::new("--git-dir"),
119 path.as_os_str(),
120 OsStr::new("config"),
121 OsStr::new("core.logAllRefUpdates"),
122 OsStr::new("true"),
123 ])
124 .await
125 .map(|_| ())
126 }
127
128 async fn remove(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> {
129 let path = self.repo_path(handle, name);
130
131 // `tokio::fs` rather than `std::fs`: removing a repository with real history
132 // walks every loose object, which is long enough to stall a runtime worker.
133 match tokio::fs::remove_dir_all(&path).await {
134 Ok(()) => Ok(()),
135 // Compensation must not fail because there was nothing left to undo.
136 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
137 Err(error) => Err(GitStorageError::backend(error)),
138 }
139 }
140
141 async fn rename(
142 &self,
143 handle: &OrgName,
144 from: &RepoName,
145 to: &RepoName,
146 ) -> Result<(), GitStorageError> {
147 let source = self.repo_path(handle, from);
148 let destination = self.repo_path(handle, to);
149
150 // Checked rather than left to `rename`, which on Unix replaces an existing
151 // empty directory and refuses a non-empty one with a bare `ENOTEMPTY`. Neither
152 // is an answer a use case can explain, and the first one loses a repository.
153 if destination.exists() {
154 return Err(GitStorageError::AlreadyExists);
155 }
156
157 // A rename within one handle's directory, so both sides are on the same
158 // filesystem and this is a metadata update rather than a copy — which is why
159 // the record write can be compensated by moving it straight back.
160 tokio::fs::rename(&source, &destination)
161 .await
162 .map_err(GitStorageError::backend)
163 }
164
165 async fn set_default_branch(
166 &self,
167 handle: &OrgName,
168 name: &RepoName,
169 branch: &RefName,
170 ) -> Result<(), GitStorageError> {
171 let path = self.repo_path(handle, name);
172
173 // `symbolic-ref` writes `HEAD` without needing the branch to exist, which is
174 // exactly why the use case checks that first. The full `refs/heads/` spelling is
175 // built here rather than accepted from the caller, so nothing can point `HEAD`
176 // at a tag or at some other ref namespace.
177 run_git([
178 OsStr::new("--git-dir"),
179 path.as_os_str(),
180 OsStr::new("symbolic-ref"),
181 OsStr::new("HEAD"),
182 OsStr::new(&format!("refs/heads/{branch}")),
183 ])
184 .await
185 .map(|_| ())
186 }
187
188 async fn enable_reflogs(&self) -> Result<u64, GitStorageError> {
189 let mut fixed = 0;
190
191 // The data directory is two levels of our own making — `{data_dir}/{handle}/
192 // {name}.git` — so the walk is two `read_dir`s rather than a recursive one, and
193 // anything else that has found its way in there is skipped instead of being
194 // configured. A missing data directory is not an error: a fresh instance has not
195 // created it yet.
196 let Ok(mut handles) = fs::read_dir(&self.data_dir).await else {
197 return Ok(0);
198 };
199
200 while let Some(handle) = handles.next_entry().await.map_err(|error| {
201 GitStorageError::backend(format!("could not read data dir: {error}"))
202 })? {
203 let Ok(mut repos) = fs::read_dir(handle.path()).await else {
204 continue;
205 };
206
207 while let Some(repo) = repos.next_entry().await.map_err(|error| {
208 GitStorageError::backend(format!("could not read data dir: {error}"))
209 })? {
210 let path = repo.path();
211
212 if path.extension() != Some(OsStr::new("git")) {
213 continue;
214 }
215
216 if enable_reflog(&path).await? {
217 fixed += 1;
218 }
219 }
220 }
221
222 Ok(fixed)
223 }
224
225 async fn list_repo_dirs(&self) -> Result<Vec<RepoDir>, GitStorageError> {
226 let mut found = Vec::new();
227
228 // Two `read_dir`s rather than a recursive walk, for the reason `enable_reflogs`
229 // gives: `{data_dir}/{handle}/{name}.git` is a shape of our own making, and
230 // anything else in there is skipped rather than interpreted.
231 let Ok(mut handles) = fs::read_dir(&self.data_dir).await else {
232 return Ok(found);
233 };
234
235 while let Some(handle) = handles.next_entry().await.map_err(|error| {
236 GitStorageError::backend(format!("could not read data dir: {error}"))
237 })? {
238 let handle_path = handle.path();
239
240 let Some(handle_name) = file_name_of(&handle_path) else {
241 continue;
242 };
243
244 // Where quarantined directories live, so a sweep cannot find its own output
245 // and quarantine it again on every boot. A handle by this name cannot exist —
246 // the reserved-handle list refuses it, pinned by a test below — so nothing
247 // real is skipped by this.
248 if handle_name == QUARANTINE {
249 continue;
250 }
251
252 let Ok(mut repos) = fs::read_dir(&handle_path).await else {
253 continue;
254 };
255
256 while let Some(repo) = repos.next_entry().await.map_err(|error| {
257 GitStorageError::backend(format!("could not read data dir: {error}"))
258 })? {
259 let path = repo.path();
260
261 if path.extension() != Some(OsStr::new("git")) {
262 continue;
263 }
264
265 let Some(name) = path.file_stem().and_then(OsStr::to_str) else {
266 continue;
267 };
268
269 found.push(RepoDir {
270 handle: handle_name.to_owned(),
271 name: name.to_owned(),
272 path,
273 });
274 }
275 }
276
277 Ok(found)
278 }
279
280 async fn quarantine(&self, dir: &RepoDir, label: &str) -> Result<PathBuf, GitStorageError> {
281 let into = self.data_dir.join(QUARANTINE);
282
283 fs::create_dir_all(&into)
284 .await
285 .map_err(GitStorageError::backend)?;
286
287 let destination = into.join(label);
288
289 // Refused rather than overwritten, exactly as `rename` refuses: the thing being
290 // moved may be the only copy of somebody's objects, and this whole operation
291 // exists to avoid losing one.
292 if fs::metadata(&destination).await.is_ok() {
293 return Err(GitStorageError::AlreadyExists);
294 }
295
296 // Within the data directory, so this is a metadata update rather than a copy —
297 // the same reason a rename is safe to compensate.
298 fs::rename(&dir.path, &destination)
299 .await
300 .map_err(GitStorageError::backend)?;
301
302 Ok(destination)
303 }
304
305 fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf {
306 // Nothing is sanitised here. `OrgName` and `RepoName` already made traversal
307 // impossible, and re-checking at the call site is how that responsibility gets
308 // diffused until nobody owns it.
309 self.data_dir
310 .join(handle.as_str())
311 .join(format!("{name}.git"))
312 }
313}
314
315/// The directory under the data directory that quarantined repositories are moved into.
316///
317/// A sibling of the handle directories rather than a hidden name, so an operator listing
318/// the data directory sees it. `OrgName` does not reserve it — a handle by this name would
319/// simply never be swept, which loses nothing and cannot lose data.
320const QUARANTINE: &str = "orphaned";
321
322/// The last component of a path, as UTF-8. `None` for a name that is neither.
323fn file_name_of(path: &Path) -> Option<&str> {
324 path.file_name().and_then(OsStr::to_str)
325}
326
327/// Turns the reflog on in one bare repository, reporting whether it had to.
328///
329/// **Reads before it writes**, which is what makes the boot sweep cheap enough to run
330/// unconditionally: `git config --get` is a local file read and answers 1 — not a fault —
331/// when the key is absent, so a repository that already has a reflog costs one short-lived
332/// process and no write at all. Only a repository that lacks it is written to, once ever.
333///
334/// A value that is present but *false* is left alone. Somebody turned it off on purpose,
335/// and a boot sweep that overrules a deliberate setting is worse than one that misses a
336/// repository.
337async fn enable_reflog(path: &Path) -> Result<bool, GitStorageError> {
338 let existing = git_command()
339 .args([
340 OsStr::new("--git-dir"),
341 path.as_os_str(),
342 OsStr::new("config"),
343 OsStr::new("--get"),
344 OsStr::new("core.logAllRefUpdates"),
345 ])
346 .stdin(Stdio::null())
347 .output()
348 .await
349 .map_err(|error| GitStorageError::backend(format!("could not run git: {error}")))?;
350
351 // 1 is "no such key", which is the whole reason this runs. Anything else — a
352 // directory that is not a repository, a permission problem — is left to the caller
353 // to log, having read nothing into it.
354 match existing.status.code() {
355 Some(0) => return Ok(false),
356 Some(1) => {}
357 _ => {
358 return Err(GitStorageError::backend(format!(
359 "git config --get exited with {} in {}: {}",
360 existing.status,
361 path.display(),
362 String::from_utf8_lossy(&existing.stderr).trim()
363 )));
364 }
365 }
366
367 run_git([
368 OsStr::new("--git-dir"),
369 path.as_os_str(),
370 OsStr::new("config"),
371 OsStr::new("core.logAllRefUpdates"),
372 OsStr::new("true"),
373 ])
374 .await?;
375
376 Ok(true)
377}
378
379/// A `git` command isolated from the host.
380///
381/// The one place that decides what git inherits: no ambient configuration, no
382/// redirected object storage. Both the lifecycle commands and the protocol backend
383/// build on this, which is the point — 0006 exists because these flags are exactly what
384/// drifts silently between call sites.
385pub(crate) fn git_command() -> Command {
386 let mut command = Command::new("git");
387
388 // Host configuration must not leak into repositories Steid creates, for the same
389 // reason `--initial-branch` is passed explicitly.
390 command
391 .env("GIT_CONFIG_GLOBAL", "/dev/null")
392 .env("GIT_CONFIG_SYSTEM", "/dev/null");
393
394 for variable in REDIRECTING_VARS {
395 command.env_remove(variable);
396 }
397
398 command
399}
400
401/// Runs `git` and fails on a non-zero exit.
402///
403/// The single place that decides how Steid invokes git, so every call site gets the
404/// same isolation from the host: no ambient configuration, no redirected object
405/// storage, no inherited stdin. Never depends on the working directory — callers pass
406/// absolute paths.
407async fn run_git<I, S>(args: I) -> Result<Output, GitStorageError>
408where
409 I: IntoIterator<Item = S>,
410 S: AsRef<OsStr>,
411{
412 let mut command = git_command();
413 command.args(args).stdin(Stdio::null());
414
415 // `output()` pipes stdout and stderr and waits without blocking the runtime.
416 let output = command
417 .output()
418 .await
419 .map_err(|error| GitStorageError::backend(format!("could not run git: {error}")))?;
420
421 if !output.status.success() {
422 // Carry git's own words. "command failed" sends the next person to read this
423 // code instead of reading the error.
424 return Err(GitStorageError::backend(format!(
425 "git exited with {}: {}",
426 output.status,
427 String::from_utf8_lossy(&output.stderr).trim()
428 )));
429 }
430
431 Ok(output)
432}
433
434/// Bare repositories tracked in memory, for testing use cases without touching disk.
435///
436/// The counterpart to [`DiskGitStorage`], the way `StubHasher` is the counterpart to
437/// the real Argon2 hasher. It enforces the same `AlreadyExists` rule, because a use
438/// case that only passes against a permissive fake proves nothing about the real one.
439#[derive(Debug, Default, Clone)]
440pub struct InMemoryGitStorage {
441 created: Arc<Mutex<HashSet<PathBuf>>>,
442 /// Where each repository's `HEAD` points, for asserting on a default-branch change.
443 heads: Arc<Mutex<HashMap<PathBuf, RefName>>>,
444}
445
446impl InMemoryGitStorage {
447 pub fn new() -> Self {
448 Self::default()
449 }
450
451 /// Whether a repository exists, for assertions.
452 pub fn contains(&self, handle: &OrgName, name: &RepoName) -> bool {
453 self.created
454 .lock()
455 .expect("lock poisoned")
456 .contains(&self.repo_path(handle, name))
457 }
458
459 /// Which branch `HEAD` names, for assertions. `None` until something sets it.
460 pub fn head(&self, handle: &OrgName, name: &RepoName) -> Option<RefName> {
461 self.heads
462 .lock()
463 .expect("lock poisoned")
464 .get(&self.repo_path(handle, name))
465 .cloned()
466 }
467
468 /// How many repositories exist, for asserting that nothing was created.
469 pub fn len(&self) -> usize {
470 self.created.lock().expect("lock poisoned").len()
471 }
472
473 pub fn is_empty(&self) -> bool {
474 self.len() == 0
475 }
476}
477
478impl GitStorage for InMemoryGitStorage {
479 async fn init_bare(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> {
480 let mut created = self.created.lock().expect("lock poisoned");
481
482 if !created.insert(self.repo_path(handle, name)) {
483 return Err(GitStorageError::AlreadyExists);
484 }
485
486 Ok(())
487 }
488
489 async fn remove(&self, handle: &OrgName, name: &RepoName) -> Result<(), GitStorageError> {
490 self.created
491 .lock()
492 .expect("lock poisoned")
493 .remove(&self.repo_path(handle, name));
494
495 Ok(())
496 }
497
498 async fn rename(
499 &self,
500 handle: &OrgName,
501 from: &RepoName,
502 to: &RepoName,
503 ) -> Result<(), GitStorageError> {
504 let mut created = self.created.lock().expect("lock poisoned");
505 let destination = self.repo_path(handle, to);
506
507 // The same refusal `DiskGitStorage` makes, so a use case cannot pass here and
508 // clobber a directory there.
509 if created.contains(&destination) {
510 return Err(GitStorageError::AlreadyExists);
511 }
512
513 let source = self.repo_path(handle, from);
514 created.remove(&source);
515 created.insert(destination.clone());
516
517 // `HEAD` travels with the directory, as it does on disk.
518 let mut heads = self.heads.lock().expect("lock poisoned");
519 if let Some(head) = heads.remove(&source) {
520 heads.insert(destination, head);
521 }
522
523 Ok(())
524 }
525
526 async fn set_default_branch(
527 &self,
528 handle: &OrgName,
529 name: &RepoName,
530 branch: &RefName,
531 ) -> Result<(), GitStorageError> {
532 self.heads
533 .lock()
534 .expect("lock poisoned")
535 .insert(self.repo_path(handle, name), branch.clone());
536
537 Ok(())
538 }
539
540 /// Nothing to enable: an in-memory repository has no config file, and no test asserts
541 /// on a reflog it cannot have. Reported as zero fixed rather than as unsupported, so a
542 /// use case that sweeps on boot can be exercised against this at all.
543 async fn enable_reflogs(&self) -> Result<u64, GitStorageError> {
544 Ok(0)
545 }
546
547 async fn list_repo_dirs(&self) -> Result<Vec<RepoDir>, GitStorageError> {
548 let created = self.created.lock().expect("lock poisoned");
549
550 let mut found: Vec<RepoDir> = created
551 .iter()
552 .filter_map(|path| {
553 let name = path.file_stem().and_then(OsStr::to_str)?;
554 let handle = path.parent().and_then(|parent| file_name_of(parent))?;
555
556 Some(RepoDir {
557 handle: handle.to_owned(),
558 name: name.to_owned(),
559 path: path.clone(),
560 })
561 })
562 .collect();
563
564 // A `HashSet` behind it, so the order would otherwise vary between runs and make
565 // a sweep's log — and any test of it — non-deterministic.
566 found.sort_by(|a, b| (&a.handle, &a.name).cmp(&(&b.handle, &b.name)));
567
568 Ok(found)
569 }
570
571 /// Moves the directory to a path under `/in-memory/orphaned`, so `contains` stops
572 /// finding it under its old name and the name is free to reuse — which is the whole
573 /// of what the on-disk move buys.
574 async fn quarantine(&self, dir: &RepoDir, label: &str) -> Result<PathBuf, GitStorageError> {
575 let destination = PathBuf::from("/in-memory").join(QUARANTINE).join(label);
576
577 let mut created = self.created.lock().expect("lock poisoned");
578
579 if created.contains(&destination) {
580 return Err(GitStorageError::AlreadyExists);
581 }
582
583 created.remove(&dir.path);
584 created.insert(destination.clone());
585
586 Ok(destination)
587 }
588
589 fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf {
590 PathBuf::from("/in-memory")
591 .join(handle.as_str())
592 .join(format!("{name}.git"))
593 }
594}
595
596/// The git smart-HTTP protocol, served by `git http-backend`.
597///
598/// The binary is a CGI: it takes an environment and a request body on stdin, and writes
599/// CRLF-terminated headers, a blank line, then the response body. Its contract was
600/// probed rather than assumed — see `plans/progress.md` under Milestone 4a.
601#[derive(Debug, Clone)]
602pub struct GitHttpBackend {
603 data_dir: PathBuf,
604}
605
606impl GitHttpBackend {
607 pub fn new(data_dir: impl Into<PathBuf>) -> Self {
608 Self {
609 data_dir: data_dir.into(),
610 }
611 }
612}
613
614impl GitProtocolServer for GitHttpBackend {
615 async fn serve(&self, request: GitRequest) -> Result<GitResponse, GitProtocolError> {
616 let mut command = git_command();
617
618 // Before the subcommand: `git -c … http-backend`. Pushes are refused by the
619 // backend unless this says otherwise, and it is set only for a request the use
620 // case already authorized — so a bug in Steid's rules meets git's refusal rather
621 // than an open door.
622 if request.allow_receive_pack {
623 command.arg("-c").arg("http.receivepack=true");
624 }
625
626 command
627 .arg("http-backend")
628 .env("GIT_PROJECT_ROOT", &self.data_dir)
629 // Steid decides visibility from the `repositories` table, in the use case.
630 // Without this, git applies its own rule and refuses everything lacking a
631 // `git-daemon-export-ok` marker file — a second source of truth for the same
632 // question, free to drift from the first.
633 .env("GIT_HTTP_EXPORT_ALL", "1")
634 .env("PATH_INFO", &request.path_info)
635 .env("QUERY_STRING", &request.query)
636 .env("REQUEST_METHOD", request.method.as_str())
637 .stdin(Stdio::piped())
638 .stdout(Stdio::piped())
639 .stderr(Stdio::piped());
640
641 // CGI gives only Content-Type and Content-Length unprefixed names; every other
642 // request header arrives `HTTP_`-prefixed. Passing `CONTENT_ENCODING` instead of
643 // `HTTP_CONTENT_ENCODING` makes the backend hand a still-gzipped body to
644 // upload-pack, and the client reports `expected 'packfile'` with nothing naming
645 // the cause. Measured, not guessed.
646 // `REMOTE_USER` is CGI's name for the authenticated caller, and git reads it to
647 // write `pusher <name>` into the reflog. Unprefixed like `CONTENT_TYPE`, because
648 // it is a CGI variable rather than a forwarded request header — and it comes
649 // from Steid's own authentication, never from anything the client sent.
650 for (variable, value) in [
651 ("CONTENT_TYPE", &request.content_type),
652 ("CONTENT_LENGTH", &request.content_length),
653 ("HTTP_CONTENT_ENCODING", &request.content_encoding),
654 ("HTTP_GIT_PROTOCOL", &request.git_protocol),
655 ("REMOTE_USER", &request.remote_user),
656 ] {
657 if let Some(value) = value {
658 command.env(variable, value);
659 }
660 }
661
662 let mut child = command
663 .spawn()
664 .map_err(|error| GitProtocolError::new(format!("could not run git: {error}")))?;
665
666 let mut stdin = child.stdin.take().expect("stdin was piped");
667 let stdout = child.stdout.take().expect("stdout was piped");
668 let mut stderr = child.stderr.take().expect("stderr was piped");
669 let mut body = request.body;
670
671 // The request body streams in while the response streams out; a push is far too
672 // large to buffer, and a fetch would otherwise wait for a body it already has.
673 // Dropping stdin closes the pipe, which is what tells the backend the request is
674 // complete — an error here is the client having gone away, which the backend
675 // then sees as EOF.
676 tokio::spawn(async move {
677 let _ = tokio::io::copy(&mut body, &mut stdin).await;
678 });
679
680 // Reaps the child and surfaces its complaint. This cannot gate the response: a
681 // protocol failure exits non-zero *after* a complete, successful-looking header
682 // block has already been written, so by the time the status is known it has been
683 // sent. Draining stderr is not optional either — an unread pipe fills and blocks
684 // the backend mid-transfer.
685 tokio::spawn(async move {
686 let mut complaint = String::new();
687 let _ = stderr.read_to_string(&mut complaint).await;
688
689 match child.wait().await {
690 Ok(status) if status.success() => {}
691 Ok(status) => eprintln!(
692 "steid: git http-backend exited with {status}: {}",
693 complaint.trim()
694 ),
695 Err(error) => eprintln!("steid: could not wait for git http-backend: {error}"),
696 }
697 });
698
699 // `BufReader` keeps whatever it read past the header block, and handing the
700 // reader itself back as the body is what makes that safe — the first bytes of
701 // the pack are already buffered inside it.
702 let mut reader = BufReader::new(stdout);
703 let (status, headers) = read_cgi_headers(&mut reader).await?;
704
705 Ok(GitResponse {
706 status,
707 headers,
708 body: Box::pin(reader),
709 })
710 }
711}
712
713/// Reads the CGI header block, stopping at the blank line that ends it.
714///
715/// `Status:` is git's way of reporting failure and appears only then, so its absence
716/// means 200. It is translated into the response status rather than forwarded as a
717/// header, which would be meaningless to a client.
718async fn read_cgi_headers(
719 reader: &mut BufReader<ChildStdout>,
720) -> Result<(u16, Vec<(String, String)>), GitProtocolError> {
721 let mut status = 200;
722 let mut headers = Vec::new();
723 let mut line = Vec::new();
724
725 loop {
726 line.clear();
727
728 let read = reader
729 .read_until(b'\n', &mut line)
730 .await
731 .map_err(|error| GitProtocolError::new(format!("reading git's headers: {error}")))?;
732
733 if read == 0 {
734 return Err(GitProtocolError::new(
735 "git http-backend produced no headers before closing",
736 ));
737 }
738
739 // Tolerates a bare LF as well as the CRLF actually observed: a header reader
740 // that hangs on an unexpected line ending is a bad way to find out.
741 let text = String::from_utf8_lossy(&line);
742 let text = text.trim_end_matches(['\r', '\n']);
743
744 if text.is_empty() {
745 return Ok((status, headers));
746 }
747
748 let Some((name, value)) = text.split_once(": ") else {
749 return Err(GitProtocolError::new(format!(
750 "git http-backend wrote an unparseable header: {text:?}"
751 )));
752 };
753
754 if name.eq_ignore_ascii_case("status") {
755 status = value
756 .split_whitespace()
757 .next()
758 .and_then(|code| code.parse().ok())
759 .ok_or_else(|| {
760 GitProtocolError::new(format!("git http-backend wrote a bad status: {value:?}"))
761 })?;
762 } else {
763 headers.push((name.to_owned(), value.to_owned()));
764 }
765
766 if headers.len() > MAX_CGI_HEADERS {
767 return Err(GitProtocolError::new(
768 "git http-backend wrote more headers than a CGI response can plausibly have",
769 ));
770 }
771 }
772}
773
774/// What a [`InMemoryGitProtocol`] was asked for, minus the body.
775///
776/// The body is a stream and comparing it would mean draining it; every rule worth
777/// asserting on lives in the metadata anyway.
778#[derive(Debug, Clone, PartialEq, Eq)]
779pub struct RecordedGitRequest {
780 pub method: GitMethod,
781 pub path_info: String,
782 pub query: String,
783 pub git_protocol: Option<String>,
784 pub content_encoding: Option<String>,
785 pub allow_receive_pack: bool,
786 pub remote_user: Option<String>,
787}
788
789/// A git protocol that records what it was asked and never runs git.
790///
791/// The counterpart to [`GitHttpBackend`]. What it is really for is proving a negative:
792/// that a use case refused *before* reaching the protocol. `was_called` is how a test
793/// says "and no bytes flowed".
794#[derive(Debug, Default, Clone)]
795pub struct InMemoryGitProtocol {
796 requests: Arc<Mutex<Vec<RecordedGitRequest>>>,
797}
798
799impl InMemoryGitProtocol {
800 pub fn new() -> Self {
801 Self::default()
802 }
803
804 pub fn requests(&self) -> Vec<RecordedGitRequest> {
805 self.requests.lock().expect("lock poisoned").clone()
806 }
807
808 /// Whether the protocol was reached at all.
809 pub fn was_called(&self) -> bool {
810 !self.requests.lock().expect("lock poisoned").is_empty()
811 }
812}
813
814impl GitProtocolServer for InMemoryGitProtocol {
815 async fn serve(&self, request: GitRequest) -> Result<GitResponse, GitProtocolError> {
816 self.requests
817 .lock()
818 .expect("lock poisoned")
819 .push(RecordedGitRequest {
820 method: request.method,
821 path_info: request.path_info,
822 query: request.query,
823 git_protocol: request.git_protocol,
824 content_encoding: request.content_encoding,
825 allow_receive_pack: request.allow_receive_pack,
826 remote_user: request.remote_user,
827 });
828
829 Ok(GitResponse {
830 status: 200,
831 headers: vec![(
832 "Content-Type".to_owned(),
833 "application/x-git-upload-pack-advertisement".to_owned(),
834 )],
835 body: Box::pin(std::io::Cursor::new(b"0000".to_vec())),
836 })
837 }
838}
839
840/// `git archive`, streamed.
841///
842/// Beside the protocol server rather than beside the read queries because it has the
843/// protocol's shape, not theirs: the output is as large as the repository and is handed
844/// on as it arrives. `DiskGitQuery`'s contract — bounded bytes, collected — is exactly
845/// what an archive must not do.
846#[derive(Debug, Clone)]
847pub struct DiskGitArchive {
848 data_dir: PathBuf,
849}
850
851impl DiskGitArchive {
852 pub fn new(data_dir: impl Into<PathBuf>) -> Self {
853 Self {
854 data_dir: data_dir.into(),
855 }
856 }
857
858 /// Where a repository lives, matching `DiskGitStorage`'s layout.
859 fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf {
860 self.data_dir
861 .join(handle.as_str())
862 .join(format!("{name}.git"))
863 }
864}
865
866impl GitArchive for DiskGitArchive {
867 async fn archive(&self, request: ArchiveRequest) -> Result<ByteStream, GitArchiveError> {
868 let repo = self.repo_path(&request.handle, &request.name);
869
870 // Both values are the use case's own construction — a resolved object id and a
871 // prefix built from the repository's name — so nothing from a URL reaches git's
872 // revision parser here. They are still written `--flag=value` rather than as
873 // separate arguments, so neither can be read as a flag of its own.
874 let mut command = git_command();
875 command
876 .arg("-C")
877 .arg(&repo)
878 .arg("archive")
879 .arg(format!("--format={}", request.format.as_str()))
880 .arg(format!("--prefix={}", request.prefix))
881 .arg(request.commit.as_str())
882 .stdin(Stdio::null())
883 .stdout(Stdio::piped())
884 .stderr(Stdio::piped())
885 // A client that gives up mid-download must take the packing with it;
886 // without this, git finishes compressing a repository for nobody.
887 .kill_on_drop(true);
888
889 let mut child = command
890 .spawn()
891 .map_err(|error| GitArchiveError::new(format!("could not run git: {error}")))?;
892
893 let stdout = child.stdout.take().expect("stdout was piped");
894 let mut stderr = child.stderr.take().expect("stderr was piped");
895
896 // The child is reaped in its own task, exactly as the protocol server's is, and
897 // for the same two reasons: dropping a `Child` with `kill_on_drop` would kill
898 // the process the response body is still reading from, and an unread stderr pipe
899 // eventually fills and stalls the transfer. The exit status cannot gate the
900 // response — by the time it is known, bytes have been sent — so a late failure
901 // is a truncated download and a line in the log.
902 tokio::spawn(async move {
903 let mut complaint = String::new();
904 let _ = stderr.read_to_string(&mut complaint).await;
905
906 match child.wait().await {
907 Ok(status) if status.success() => {}
908 Ok(status) => {
909 eprintln!(
910 "steid: git archive exited with {status}: {}",
911 complaint.trim()
912 )
913 }
914 Err(error) => eprintln!("steid: could not wait for git archive: {error}"),
915 }
916 });
917
918 Ok(Box::pin(stdout))
919 }
920}
921
922/// What an [`InMemoryGitArchive`] was asked for.
923///
924/// The request minus nothing: unlike a protocol request there is no body, so every
925/// field is worth asserting on.
926#[derive(Debug, Clone, PartialEq, Eq)]
927pub struct RecordedArchive {
928 pub handle: OrgName,
929 pub name: RepoName,
930 pub format: crate::application::port::ArchiveFormat,
931 pub commit: ObjectId,
932 pub prefix: String,
933}
934
935/// An archive port that records what it was asked and never runs git.
936///
937/// Like [`InMemoryGitProtocol`], what it is really for is proving a negative: that a
938/// use case refused before a single byte was packed.
939#[derive(Debug, Default, Clone)]
940pub struct InMemoryGitArchive {
941 requests: Arc<Mutex<Vec<RecordedArchive>>>,
942}
943
944impl InMemoryGitArchive {
945 pub fn new() -> Self {
946 Self::default()
947 }
948
949 pub fn requests(&self) -> Vec<RecordedArchive> {
950 self.requests.lock().expect("lock poisoned").clone()
951 }
952
953 /// Whether anything was ever packed.
954 pub fn was_called(&self) -> bool {
955 !self.requests.lock().expect("lock poisoned").is_empty()
956 }
957}
958
959impl GitArchive for InMemoryGitArchive {
960 async fn archive(&self, request: ArchiveRequest) -> Result<ByteStream, GitArchiveError> {
961 self.requests
962 .lock()
963 .expect("lock poisoned")
964 .push(RecordedArchive {
965 handle: request.handle,
966 name: request.name,
967 format: request.format,
968 commit: request.commit,
969 prefix: request.prefix,
970 });
971
972 Ok(Box::pin(std::io::Cursor::new(b"archive".to_vec())))
973 }
974}
975
976/// A repository's contents, held in memory, for testing use cases and pages.
977///
978/// The counterpart to `DiskGitQuery`. Seeded with exactly what a test needs rather than
979/// pretending to be a git implementation: it answers the questions the port asks and
980/// knows nothing about how a real repository stores them.
981#[derive(Debug, Default, Clone)]
982pub struct InMemoryGitQuery {
983 default_branch: Option<RefName>,
984 /// Keyed `rev\0path`, because a tree only means anything at a revision.
985 trees: HashMap<String, Vec<TreeEntry>>,
986 blobs: HashMap<String, Vec<u8>>,
987 commits: Vec<CommitSummary>,
988 /// Branches and tags, in whatever order a test seeded them — the real adapter makes
989 /// no ordering promise either.
990 refs: Vec<GitRef>,
991 /// Overrides the count derived from the seeded log, for a test that wants a
992 /// repository with more history than it wants to write out.
993 commit_count: Option<u64>,
994 latest_tag: Option<TagSummary>,
995 /// The branches and tags pages' richer rows, seeded separately from `refs`: the two
996 /// answer different questions and a test usually wants only one of them.
997 branch_rows: Vec<BranchRow>,
998 tag_rows: Vec<TagRow>,
999 /// What any grep answers with, regardless of the query — a fake that matched text
1000 /// would be a second, worse implementation of `git grep`.
1001 grep_hits: Vec<GrepHit>,
1002 /// Makes the next grep report the read timeout, which is a page state rather than
1003 /// a failure and therefore worth a test.
1004 slow_grep: bool,
1005 /// The one commit `commit` answers with, whatever revision it is asked for. A fake
1006 /// of git's object store is not what these tests are about.
1007 detail: Option<CommitDetail>,
1008 /// The raw patch `diff` answers with, and whether the fake should call it truncated.
1009 diff: Option<RawDiff>,
1010 /// The merge base of any two commits, because a fake has no graph to walk.
1011 merge_base: Option<ObjectId>,
1012 /// What a merge preview answers with, or `None` for the clean default. A fake that
1013 /// really merged two trees would be a second, worse `git merge-tree`; what a use
1014 /// case test needs is to choose which of the two answers it gets.
1015 merge_preview: Option<MergePreview>,
1016 /// What a ref snapshot answers with. Seeded separately from `refs`, and mutable
1017 /// through [`InMemoryGitQuery::set_ref_snapshot`], because the whole point of a
1018 /// snapshot is that it differs before and after a push.
1019 snapshot: Arc<Mutex<Vec<(RefName, ObjectId)>>>,
1020
1021 /// Keyed the same way trees and blobs are, because a blame only means anything at a
1022 /// revision either.
1023 blames: HashMap<String, Blame>,
1024
1025 /// Message bodies, keyed by commit id. Kept beside `commits` rather than inside
1026 /// them so `log` and `log_entries` can never disagree about a commit's subject —
1027 /// one list of commits, and a body looked up for the reading that wants one.
1028 bodies: HashMap<String, String>,
1029 /// The last-commit column's answers, keyed the same way trees are — the column is a
1030 /// fact about a directory at a revision.
1031 last_commits: HashMap<String, HashMap<String, EntryCommit>>,
1032
1033 /// The commits a path's own log reports, keyed the same way trees are.
1034 ///
1035 /// Seeded per path rather than filtered out of `commits`, because a fake with no
1036 /// trees to walk cannot know which commit touched what — and a test about a
1037 /// followed rename is a test about exactly that.
1038 path_logs: HashMap<String, Vec<CommitSummary>>,
1039
1040 /// What a symlink blob points at, by the id the listing carries.
1041 symlink_targets: HashMap<ObjectId, String>,
1042
1043 /// Revisions that resolve to something other than the default id.
1044 ///
1045 /// Every revision resolves to the same commit unless one is named here, which is
1046 /// what makes a comparison of two revisions come back as `Identical` by default —
1047 /// convenient for most tests and useless for the one that wants a real comparison.
1048 resolved: HashMap<String, ObjectId>,
1049}
1050
1051impl InMemoryGitQuery {
1052 /// An empty repository: no default branch, so nothing has been pushed.
1053 pub fn empty() -> Self {
1054 Self::default()
1055 }
1056
1057 /// A repository whose default branch is `main`.
1058 pub fn new() -> Self {
1059 Self {
1060 default_branch: Some(RefName::from_trusted("main")),
1061 ..Self::default()
1062 }
1063 }
1064
1065 fn key(rev: &RefName, path: &RepoPath) -> String {
1066 format!("{}\0{}", rev.as_str(), path.as_str())
1067 }
1068
1069 pub fn with_tree(mut self, rev: &str, path: &str, entries: Vec<TreeEntry>) -> Self {
1070 self.trees.insert(
1071 Self::key(&RefName::from_trusted(rev), &RepoPath::from_trusted(path)),
1072 entries,
1073 );
1074 self
1075 }
1076
1077 pub fn with_blob(mut self, rev: &str, path: &str, content: impl Into<Vec<u8>>) -> Self {
1078 self.blobs.insert(
1079 Self::key(&RefName::from_trusted(rev), &RepoPath::from_trusted(path)),
1080 content.into(),
1081 );
1082 self
1083 }
1084
1085 /// Seeds the last-commit column for one directory.
1086 pub fn with_last_commits(
1087 mut self,
1088 rev: &str,
1089 path: &str,
1090 commits: Vec<(&str, EntryCommit)>,
1091 ) -> Self {
1092 self.last_commits.insert(
1093 Self::key(&RefName::from_trusted(rev), &RepoPath::from_trusted(path)),
1094 commits
1095 .into_iter()
1096 .map(|(name, commit)| (name.to_owned(), commit))
1097 .collect(),
1098 );
1099 self
1100 }
1101
1102 pub fn with_log(mut self, commits: Vec<CommitSummary>) -> Self {
1103 self.commits = commits;
1104 self
1105 }
1106
1107 /// Seeds the log of one path at one revision.
1108 pub fn with_path_log(mut self, rev: &str, path: &str, commits: Vec<CommitSummary>) -> Self {
1109 self.path_logs.insert(
1110 Self::key(&RefName::from_trusted(rev), &RepoPath::from_trusted(path)),
1111 commits,
1112 );
1113 self
1114 }
1115
1116 /// Seeds what a symlink blob points at.
1117 pub fn with_symlink_target(mut self, id: &ObjectId, target: &str) -> Self {
1118 self.symlink_targets.insert(id.clone(), target.to_owned());
1119 self
1120 }
1121
1122 pub fn with_branch(self, name: &str) -> Self {
1123 self.with_ref(name, RefKind::Branch)
1124 }
1125
1126 pub fn with_tag(self, name: &str) -> Self {
1127 self.with_ref(name, RefKind::Tag)
1128 }
1129
1130 /// Makes one revision resolve to an id of its own.
1131 pub fn with_resolved(mut self, rev: &str, id: &str) -> Self {
1132 self.resolved
1133 .insert(rev.to_owned(), ObjectId::from_trusted(format!("{id:0>40}")));
1134 self
1135 }
1136
1137 pub fn with_commit_count(mut self, count: u64) -> Self {
1138 self.commit_count = Some(count);
1139 self
1140 }
1141
1142 pub fn with_latest_tag(mut self, name: &str, created_at: SystemTime) -> Self {
1143 self.latest_tag = Some(TagSummary {
1144 name: RefName::from_trusted(name),
1145 created_at,
1146 });
1147 self
1148 }
1149
1150 /// One row of the branches page. `is_default` is what git's `%(HEAD)` marks.
1151 pub fn with_branch_row(
1152 mut self,
1153 name: &str,
1154 is_default: bool,
1155 committed_at: SystemTime,
1156 ) -> Self {
1157 self.branch_rows.push(BranchRow {
1158 name: RefName::from_trusted(name),
1159 is_default,
1160 commit: ObjectId::from_trusted("2".repeat(40)),
1161 summary: format!("work on {name}"),
1162 committed_at,
1163 });
1164 self
1165 }
1166
1167 /// One row of the tags page. An annotated tag carries a message; a lightweight one
1168 /// has none of its own.
1169 pub fn with_tag_row(mut self, name: &str, annotated: bool, created_at: SystemTime) -> Self {
1170 self.tag_rows.push(TagRow {
1171 name: RefName::from_trusted(name),
1172 commit: ObjectId::from_trusted("3".repeat(40)),
1173 message: annotated.then(|| format!("release {name}")),
1174 annotated,
1175 created_at,
1176 });
1177 self
1178 }
1179
1180 /// Seeds what a search finds. Order is kept, because grouping by file depends on
1181 /// git's ordering and a fake that reordered would hide that.
1182 pub fn with_grep_hits(mut self, hits: Vec<GrepHit>) -> Self {
1183 self.grep_hits = hits;
1184 self
1185 }
1186
1187 /// A repository whose grep is killed by the timeout.
1188 pub fn with_slow_grep(mut self) -> Self {
1189 self.slow_grep = true;
1190 self
1191 }
1192
1193 /// Gives a seeded commit a message body, for the feed reading of a log.
1194 pub fn with_commit_body(mut self, id: &str, body: &str) -> Self {
1195 self.bodies.insert(id.to_owned(), body.to_owned());
1196 self
1197 }
1198
1199 pub fn with_commit(mut self, detail: CommitDetail) -> Self {
1200 self.detail = Some(detail);
1201 self
1202 }
1203
1204 pub fn with_diff(mut self, patch: impl Into<Vec<u8>>, numstat: impl Into<Vec<u8>>) -> Self {
1205 self.diff = Some(RawDiff {
1206 numstat: numstat.into(),
1207 patch: patch.into(),
1208 truncated: false,
1209 });
1210 self
1211 }
1212
1213 pub fn with_merge_base(mut self, id: &str) -> Self {
1214 self.merge_base = Some(ObjectId::from_trusted(id));
1215 self
1216 }
1217
1218 /// Makes every merge preview report a conflict in these paths.
1219 pub fn with_conflicts(mut self, paths: &[&str]) -> Self {
1220 self.merge_preview = Some(MergePreview::Conflicted {
1221 paths: paths.iter().map(|path| (*path).to_owned()).collect(),
1222 });
1223 self
1224 }
1225
1226 pub fn with_blame(mut self, rev: &str, path: &str, blame: Blame) -> Self {
1227 self.blames.insert(
1228 Self::key(&RefName::from_trusted(rev), &RepoPath::from_trusted(path)),
1229 blame,
1230 );
1231 self
1232 }
1233
1234 /// Seeds the refs a snapshot reports.
1235 pub fn with_ref_snapshot(self, refs: &[(&str, &str)]) -> Self {
1236 self.set_ref_snapshot(refs);
1237 self
1238 }
1239
1240 /// Replaces what a snapshot reports, standing in for a push having landed.
1241 ///
1242 /// Takes `&self` so a test can move the refs *between* two reads of the same fake,
1243 /// which is the sequence the real push path performs.
1244 pub fn set_ref_snapshot(&self, refs: &[(&str, &str)]) {
1245 *self.snapshot.lock().expect("lock poisoned") = refs
1246 .iter()
1247 .map(|(name, id)| {
1248 (
1249 RefName::from_trusted(*name),
1250 ObjectId::from_trusted(format!("{id:0>40}")),
1251 )
1252 })
1253 .collect();
1254 }
1255
1256 fn with_ref(mut self, name: &str, kind: RefKind) -> Self {
1257 self.refs.push(GitRef {
1258 name: RefName::from_trusted(name),
1259 kind,
1260 });
1261 self
1262 }
1263}
1264
1265impl GitQuery for InMemoryGitQuery {
1266 async fn default_branch(
1267 &self,
1268 _handle: &OrgName,
1269 _name: &RepoName,
1270 ) -> Result<Option<RefName>, GitQueryError> {
1271 Ok(self.default_branch.clone())
1272 }
1273
1274 async fn resolve(
1275 &self,
1276 _handle: &OrgName,
1277 _name: &RepoName,
1278 rev: &RefName,
1279 ) -> Result<Option<ObjectId>, GitQueryError> {
1280 if let Some(id) = self.resolved.get(rev.as_str()) {
1281 return Ok(Some(id.clone()));
1282 }
1283
1284 Ok(self
1285 .default_branch
1286 .as_ref()
1287 .map(|_| ObjectId::from_trusted("0".repeat(40))))
1288 }
1289
1290 async fn list_tree(
1291 &self,
1292 _handle: &OrgName,
1293 _name: &RepoName,
1294 rev: &RefName,
1295 path: &RepoPath,
1296 ) -> Result<Option<Vec<TreeEntry>>, GitQueryError> {
1297 Ok(self.trees.get(&Self::key(rev, path)).cloned())
1298 }
1299
1300 async fn last_commits(
1301 &self,
1302 _handle: &OrgName,
1303 _name: &RepoName,
1304 rev: &RefName,
1305 path: &RepoPath,
1306 entries: &[String],
1307 ) -> Result<HashMap<String, EntryCommit>, GitQueryError> {
1308 let Some(seeded) = self.last_commits.get(&Self::key(rev, path)) else {
1309 return Ok(HashMap::new());
1310 };
1311
1312 // Filtered to what was asked about, like the real adapter: an entry that is not
1313 // in the listing is not in the answer, whatever a test seeded.
1314 Ok(seeded
1315 .iter()
1316 .filter(|(name, _)| entries.iter().any(|entry| entry == *name))
1317 .map(|(name, commit)| (name.clone(), commit.clone()))
1318 .collect())
1319 }
1320
1321 async fn read_blob(
1322 &self,
1323 _handle: &OrgName,
1324 _name: &RepoName,
1325 rev: &RefName,
1326 path: &RepoPath,
1327 max_bytes: u64,
1328 ) -> Result<Option<Blob>, GitQueryError> {
1329 Ok(self.blobs.get(&Self::key(rev, path)).map(|content| {
1330 let size = content.len() as u64;
1331
1332 Blob {
1333 id: ObjectId::from_trusted("1".repeat(40)),
1334 size,
1335 // The same cap the real adapter applies, so a test can exercise the
1336 // too-large path without a megabyte of fixture.
1337 content: (size <= max_bytes).then(|| content.clone()),
1338 }
1339 }))
1340 }
1341
1342 async fn log(
1343 &self,
1344 _handle: &OrgName,
1345 _name: &RepoName,
1346 _rev: &RefName,
1347 offset: usize,
1348 limit: usize,
1349 ) -> Result<Vec<CommitSummary>, GitQueryError> {
1350 Ok(self
1351 .commits
1352 .iter()
1353 .skip(offset)
1354 .take(limit)
1355 .cloned()
1356 .collect())
1357 }
1358
1359 async fn log_entries(
1360 &self,
1361 _handle: &OrgName,
1362 _name: &RepoName,
1363 _rev: &RefName,
1364 limit: usize,
1365 ) -> Result<Vec<CommitEntry>, GitQueryError> {
1366 Ok(self
1367 .commits
1368 .iter()
1369 .take(limit)
1370 .map(|commit| CommitEntry {
1371 body: self
1372 .bodies
1373 .get(commit.id.as_str())
1374 .cloned()
1375 .unwrap_or_default(),
1376 commit: commit.clone(),
1377 })
1378 .collect())
1379 }
1380
1381 async fn list_refs(
1382 &self,
1383 _handle: &OrgName,
1384 _name: &RepoName,
1385 ) -> Result<Vec<GitRef>, GitQueryError> {
1386 Ok(self.refs.clone())
1387 }
1388
1389 async fn count_commits(
1390 &self,
1391 _handle: &OrgName,
1392 _name: &RepoName,
1393 _rev: &RefName,
1394 ) -> Result<u64, GitQueryError> {
1395 Ok(self.commit_count.unwrap_or(self.commits.len() as u64))
1396 }
1397
1398 async fn latest_tag(
1399 &self,
1400 _handle: &OrgName,
1401 _name: &RepoName,
1402 ) -> Result<Option<TagSummary>, GitQueryError> {
1403 Ok(self.latest_tag.clone())
1404 }
1405
1406 async fn branches(
1407 &self,
1408 _handle: &OrgName,
1409 _name: &RepoName,
1410 ) -> Result<Vec<BranchRow>, GitQueryError> {
1411 Ok(self.branch_rows.clone())
1412 }
1413
1414 async fn tags(
1415 &self,
1416 _handle: &OrgName,
1417 _name: &RepoName,
1418 ) -> Result<Vec<TagRow>, GitQueryError> {
1419 Ok(self.tag_rows.clone())
1420 }
1421
1422 async fn grep(
1423 &self,
1424 _handle: &OrgName,
1425 _name: &RepoName,
1426 _commit: &ObjectId,
1427 _query: &str,
1428 limit: usize,
1429 ) -> Result<Vec<GrepHit>, GitQueryError> {
1430 if self.slow_grep {
1431 return Err(GitQueryError::timed_out(std::time::Duration::from_secs(20)));
1432 }
1433
1434 Ok(self.grep_hits.iter().take(limit).cloned().collect())
1435 }
1436
1437 async fn commit(
1438 &self,
1439 _handle: &OrgName,
1440 _name: &RepoName,
1441 _rev: &RefName,
1442 ) -> Result<Option<CommitDetail>, GitQueryError> {
1443 Ok(self.detail.clone())
1444 }
1445
1446 async fn diff(
1447 &self,
1448 _handle: &OrgName,
1449 _name: &RepoName,
1450 _base: Option<&ObjectId>,
1451 _head: &ObjectId,
1452 _max_bytes: u64,
1453 ) -> Result<RawDiff, GitQueryError> {
1454 Ok(self.diff.clone().unwrap_or_default())
1455 }
1456
1457 async fn merge_base(
1458 &self,
1459 _handle: &OrgName,
1460 _name: &RepoName,
1461 _base: &ObjectId,
1462 _head: &ObjectId,
1463 ) -> Result<Option<ObjectId>, GitQueryError> {
1464 Ok(self.merge_base.clone())
1465 }
1466
1467 async fn log_between(
1468 &self,
1469 _handle: &OrgName,
1470 _name: &RepoName,
1471 _base: Option<&ObjectId>,
1472 _head: &ObjectId,
1473 offset: usize,
1474 limit: usize,
1475 ) -> Result<Vec<CommitSummary>, GitQueryError> {
1476 Ok(self
1477 .commits
1478 .iter()
1479 .skip(offset)
1480 .take(limit)
1481 .cloned()
1482 .collect())
1483 }
1484
1485 async fn count_between(
1486 &self,
1487 _handle: &OrgName,
1488 _name: &RepoName,
1489 _base: Option<&ObjectId>,
1490 _head: &ObjectId,
1491 ) -> Result<usize, GitQueryError> {
1492 Ok(self.commits.len())
1493 }
1494
1495 async fn blame(
1496 &self,
1497 _handle: &OrgName,
1498 _name: &RepoName,
1499 rev: &RefName,
1500 path: &RepoPath,
1501 ) -> Result<Option<Blame>, GitQueryError> {
1502 Ok(self.blames.get(&Self::key(rev, path)).cloned())
1503 }
1504
1505 async fn ref_snapshot(
1506 &self,
1507 _handle: &OrgName,
1508 _name: &RepoName,
1509 ) -> Result<Vec<(RefName, ObjectId)>, GitQueryError> {
1510 Ok(self.snapshot.lock().expect("lock poisoned").clone())
1511 }
1512
1513 async fn log_at_path(
1514 &self,
1515 _handle: &OrgName,
1516 _name: &RepoName,
1517 rev: &RefName,
1518 path: &RepoPath,
1519 _follow: bool,
1520 offset: usize,
1521 limit: usize,
1522 ) -> Result<Vec<CommitSummary>, GitQueryError> {
1523 let Some(commits) = self.path_logs.get(&Self::key(rev, path)) else {
1524 return Ok(Vec::new());
1525 };
1526
1527 Ok(commits.iter().skip(offset).take(limit).cloned().collect())
1528 }
1529
1530 async fn count_commits_at_path(
1531 &self,
1532 _handle: &OrgName,
1533 _name: &RepoName,
1534 rev: &RefName,
1535 path: &RepoPath,
1536 follow: bool,
1537 ) -> Result<CommitCount, GitQueryError> {
1538 let counted = self
1539 .path_logs
1540 .get(&Self::key(rev, path))
1541 .map(Vec::len)
1542 .unwrap_or(0);
1543
1544 // The real adapter's cap, reproduced here rather than left out: a fake that
1545 // never caps would let a use case test pass on a case the page cannot reach.
1546 // Only a followed walk is capped, which is the adapter's rule too.
1547 Ok(match follow {
1548 true => CommitCount {
1549 total: counted.min(FOLLOWED_LOG_SCAN) as u64,
1550 capped: counted > FOLLOWED_LOG_SCAN,
1551 },
1552 false => CommitCount {
1553 total: counted as u64,
1554 capped: false,
1555 },
1556 })
1557 }
1558
1559 async fn symlink_targets(
1560 &self,
1561 _handle: &OrgName,
1562 _name: &RepoName,
1563 ids: &[ObjectId],
1564 ) -> Result<HashMap<ObjectId, String>, GitQueryError> {
1565 Ok(ids
1566 .iter()
1567 .filter_map(|id| Some((id.clone(), self.symlink_targets.get(id)?.clone())))
1568 .collect())
1569 }
1570
1571 async fn merge_preview(
1572 &self,
1573 _handle: &OrgName,
1574 _name: &RepoName,
1575 _target: &ObjectId,
1576 _source: &ObjectId,
1577 ) -> Result<MergePreview, GitQueryError> {
1578 // Clean unless a test said otherwise, which is the answer that lets a merge
1579 // test be about the merge rather than about seeding a preview first.
1580 Ok(self
1581 .merge_preview
1582 .clone()
1583 .unwrap_or_else(|| MergePreview::Clean {
1584 tree: ObjectId::from_trusted("7".repeat(40)),
1585 }))
1586 }
1587}
1588
1589// --- Importing from elsewhere -----------------------------------------------------
1590
1591/// How long a `git clone --mirror` may run before it is killed.
1592///
1593/// Ten minutes, far above the read timeout in `git_query.rs` and for the opposite
1594/// reason: this is a network transfer of a whole repository with nobody waiting on a
1595/// page, so the cost of being generous is a background task, not a held worker. It is
1596/// bounded at all because a stalled TLS connection to a host that accepts and then says
1597/// nothing would otherwise hold a task for the life of the process.
1598const IMPORT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600);
1599
1600/// The port git connects to when a URL does not name one. Used only to resolve the
1601/// host — nothing dials this socket directly.
1602const HTTPS_PORT: u16 = 443;
1603
1604/// `git clone --mirror` into the same layout [`DiskGitStorage`] uses.
1605///
1606/// **This adapter is where the second half of the server-side request forgery check
1607/// lives.** [`ImportSource`] refused a literal address that is not on the public
1608/// internet, but `evil.example.com` resolving to `127.0.0.1` passes every syntactic
1609/// rule there is. Only the thing about to open the connection can look, so it looks
1610/// here, immediately before spawning git.
1611#[derive(Debug, Clone)]
1612pub struct DiskGitImport {
1613 data_dir: PathBuf,
1614}
1615
1616impl DiskGitImport {
1617 pub fn new(data_dir: impl Into<PathBuf>) -> Self {
1618 Self {
1619 data_dir: data_dir.into(),
1620 }
1621 }
1622
1623 /// Where a repository lives, matching `DiskGitStorage`'s layout.
1624 fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf {
1625 self.data_dir
1626 .join(handle.as_str())
1627 .join(format!("{name}.git"))
1628 }
1629}
1630
1631impl GitImport for DiskGitImport {
1632 async fn mirror(
1633 &self,
1634 handle: &OrgName,
1635 name: &RepoName,
1636 source: &ImportSource,
1637 ) -> Result<(), GitImportError> {
1638 resolve_public_host(source.host()).await?;
1639
1640 let path = self.repo_path(handle, name);
1641
1642 // `git clone` refuses a non-empty destination, so an orphan left by an earlier
1643 // attempt surfaces as a failed import rather than being adopted. Checked here
1644 // as well so the message says something a person can act on.
1645 if path.exists() {
1646 return Err(GitImportError::new(
1647 "something is already on disk at this repository's path",
1648 ));
1649 }
1650
1651 // `--mirror` is the whole reason this is one command: it fetches every ref into
1652 // the same name it has on the source, sets `HEAD` to the source's default
1653 // branch, and makes the result bare. A plain `--bare` clone would bring one
1654 // branch and lose every tag.
1655 run_import(
1656 [
1657 OsStr::new("clone"),
1658 OsStr::new("--mirror"),
1659 OsStr::new("--quiet"),
1660 // Everything after this is data. The URL is already https-only and
1661 // space-free, but a destination that could be read as a flag is exactly
1662 // the class of bug `RepoName` exists to prevent, so it is closed here
1663 // too where it costs nothing.
1664 OsStr::new("--"),
1665 OsStr::new(source.as_str()),
1666 path.as_os_str(),
1667 ],
1668 None,
1669 )
1670 .await?;
1671
1672 finish_mirror(&path).await
1673 }
1674}
1675
1676/// Turns a fresh `--mirror` clone into an ordinary Steid repository.
1677///
1678/// Split out from [`DiskGitImport::mirror`] so it can be tested against a fixture: the
1679/// clone itself needs a public HTTPS host, and everything that could plausibly be wrong
1680/// is on this side of it.
1681async fn finish_mirror(path: &std::path::Path) -> Result<(), GitImportError> {
1682 // A mirror keeps its remote and its `remote.origin.mirror` flag, so the result
1683 // would be a repository that fetches from somewhere else on the next `git remote
1684 // update`. Removing it is what turns the clone into an ordinary Steid repository,
1685 // and it takes the mirror refspec with it.
1686 run_import(
1687 [
1688 OsStr::new("remote"),
1689 OsStr::new("remove"),
1690 OsStr::new("origin"),
1691 ],
1692 Some(path),
1693 )
1694 .await?;
1695
1696 // **`git clone` leaves no reflog either**, exactly as `git init --bare` does, and an
1697 // import never goes through `init_bare` — so without this an imported repository
1698 // records nobody as having pushed to it until the next boot sweep picks it up. Found
1699 // by that sweep reporting six repositories on a development instance where every
1700 // repository had been created by the current code: the six were the imports.
1701 run_import(
1702 [
1703 OsStr::new("config"),
1704 OsStr::new("core.logAllRefUpdates"),
1705 OsStr::new("true"),
1706 ],
1707 Some(path),
1708 )
1709 .await?;
1710
1711 // `--mirror` puts branches under `refs/heads` already. This is the belt to that
1712 // braces: a source whose own layout is unusual — itself a mirror of a mirror — can
1713 // leave `refs/remotes`, and a branch nobody can see is worse than one moved to
1714 // where every other page expects it.
1715 promote_remote_refs(path).await
1716}
1717
1718/// Moves anything under `refs/remotes/origin/` to `refs/heads/`, and drops the rest.
1719///
1720/// A no-op for every ordinary mirror, which is why it is written to cost one `git`
1721/// process and stop: `for-each-ref` on a prefix with nothing under it exits 0 with no
1722/// output.
1723///
1724/// Object ids are read alongside the names and written back as ids. `update-ref` takes
1725/// a value, not a reference, and asking it to resolve one is how this was got wrong the
1726/// first time.
1727async fn promote_remote_refs(path: &std::path::Path) -> Result<(), GitImportError> {
1728 let listed = run_import(
1729 [
1730 OsStr::new("for-each-ref"),
1731 OsStr::new("--format=%(objectname) %(refname)"),
1732 OsStr::new("refs/remotes/"),
1733 ],
1734 Some(path),
1735 )
1736 .await?;
1737
1738 let listed = String::from_utf8_lossy(&listed.stdout);
1739
1740 for line in listed.lines() {
1741 let Some((id, reference)) = line.trim().split_once(' ') else {
1742 continue;
1743 };
1744
1745 // `origin/HEAD` is a symbolic pointer, not a branch, and `--mirror` has already
1746 // set the real `HEAD` from the source. Anything under another remote's name is
1747 // somebody else's tracking ref and means nothing here. Both are simply dropped.
1748 if let Some(branch) = reference
1749 .strip_prefix("refs/remotes/origin/")
1750 .filter(|branch| *branch != "HEAD")
1751 {
1752 run_import(
1753 [
1754 OsStr::new("update-ref"),
1755 OsStr::new(&format!("refs/heads/{branch}")),
1756 OsStr::new(id),
1757 ],
1758 Some(path),
1759 )
1760 .await?;
1761 }
1762
1763 run_import(
1764 [
1765 OsStr::new("update-ref"),
1766 OsStr::new("-d"),
1767 OsStr::new(reference),
1768 ],
1769 Some(path),
1770 )
1771 .await?;
1772 }
1773
1774 Ok(())
1775}
1776
1777/// Resolves a host and refuses it unless every address it answers with is on the public
1778/// internet.
1779///
1780/// **Every address, not the first.** A host that answers with one public address and
1781/// one loopback address is a host that can be made to connect to loopback, because
1782/// which one git picks is not ours to decide.
1783///
1784/// This leaves one hole, deliberately and knowingly: git resolves the name again when
1785/// it connects, so a record whose TTL expires between the two lookups can change
1786/// underneath us. Closing that means resolving here and handing git a literal address
1787/// with the hostname forced for TLS and SNI, which is a larger change than this step —
1788/// recorded rather than pretended away.
1789async fn resolve_public_host(host: &str) -> Result<(), GitImportError> {
1790 let refused = || {
1791 GitImportError::new(format!(
1792 "{host} resolves to an address that is not on the public internet"
1793 ))
1794 };
1795
1796 let addresses = tokio::net::lookup_host((host, HTTPS_PORT))
1797 .await
1798 .map_err(|error| GitImportError::new(format!("could not resolve {host}: {error}")))?;
1799
1800 let mut any = false;
1801
1802 for address in addresses {
1803 any = true;
1804
1805 if !is_public(address.ip()) {
1806 return Err(refused());
1807 }
1808 }
1809
1810 if !any {
1811 return Err(GitImportError::new(format!("{host} resolves to nothing")));
1812 }
1813
1814 Ok(())
1815}
1816
1817/// Runs one `git` command on behalf of an import.
1818///
1819/// Separate from [`run_git`] for two reasons rather than one: the timeout is ten
1820/// minutes instead of unbounded, and `GIT_TERMINAL_PROMPT=0` turns a private repository
1821/// into a failed import instead of a subprocess sitting forever on a username prompt
1822/// nobody can answer.
1823async fn run_import<I, S>(args: I, repo: Option<&std::path::Path>) -> Result<Output, GitImportError>
1824where
1825 I: IntoIterator<Item = S>,
1826 S: AsRef<OsStr>,
1827{
1828 let mut command = git_command();
1829
1830 if let Some(repo) = repo {
1831 command.arg("-C").arg(repo);
1832 }
1833
1834 command
1835 .args(args)
1836 .stdin(Stdio::null())
1837 // Without this git blocks on a credential prompt for anything that asks for
1838 // authentication — a private repository, or a typo'd path on a host that
1839 // challenges rather than 404s.
1840 .env("GIT_TERMINAL_PROMPT", "0")
1841 // A killed clone must take the process with it, or a timed-out import keeps
1842 // pulling a repository nobody is waiting for.
1843 .kill_on_drop(true);
1844
1845 let output = match tokio::time::timeout(IMPORT_TIMEOUT, command.output()).await {
1846 Ok(result) => {
1847 result.map_err(|error| GitImportError::new(format!("could not run git: {error}")))?
1848 }
1849 Err(_elapsed) => {
1850 return Err(GitImportError::new(format!(
1851 "the import did not finish within {IMPORT_TIMEOUT:?}"
1852 )));
1853 }
1854 };
1855
1856 if !output.status.success() {
1857 // git's own words, trimmed to the last line: the earlier lines of a clone
1858 // failure are progress, and the last one is the reason.
1859 let stderr = String::from_utf8_lossy(&output.stderr);
1860 let reason = stderr.lines().rev().find(|line| !line.trim().is_empty());
1861
1862 return Err(GitImportError::new(match reason {
1863 Some(reason) => reason.trim().to_owned(),
1864 None => format!("git exited with {}", output.status),
1865 }));
1866 }
1867
1868 Ok(output)
1869}
1870
1871/// Imports recorded in memory, for testing use cases without a network.
1872///
1873/// The counterpart to [`DiskGitImport`], the way [`InMemoryGitStorage`] is to
1874/// [`DiskGitStorage`]. It can be told to fail, because the failure path — recording the
1875/// reason and removing the half-clone — is the half most worth testing.
1876#[derive(Debug, Default, Clone)]
1877pub struct InMemoryGitImport {
1878 requests: Arc<Mutex<Vec<(String, String, String)>>>,
1879 failure: Option<String>,
1880}
1881
1882impl InMemoryGitImport {
1883 pub fn new() -> Self {
1884 Self::default()
1885 }
1886
1887 /// One that always fails with `reason`.
1888 pub fn failing(reason: impl Into<String>) -> Self {
1889 Self {
1890 requests: Arc::default(),
1891 failure: Some(reason.into()),
1892 }
1893 }
1894
1895 /// What was asked for, as `(handle, name, source)`.
1896 pub fn requests(&self) -> Vec<(String, String, String)> {
1897 self.requests.lock().expect("lock poisoned").clone()
1898 }
1899}
1900
1901impl GitImport for InMemoryGitImport {
1902 async fn mirror(
1903 &self,
1904 handle: &OrgName,
1905 name: &RepoName,
1906 source: &ImportSource,
1907 ) -> Result<(), GitImportError> {
1908 self.requests.lock().expect("lock poisoned").push((
1909 handle.to_string(),
1910 name.to_string(),
1911 source.as_str().to_owned(),
1912 ));
1913
1914 match &self.failure {
1915 Some(reason) => Err(GitImportError::new(reason.clone())),
1916 None => Ok(()),
1917 }
1918 }
1919}
1920
1921// --- Merging ------------------------------------------------------------------------
1922
1923/// The oldest git that can merge inside a bare repository.
1924///
1925/// `git merge-tree --write-tree` arrived in 2.38. Before that, `merge-tree` meant
1926/// something else entirely — a three-way *diff* that wrote nothing — so an older git
1927/// does not fail with a clear message, it succeeds at the wrong thing. That is why the
1928/// version is read at boot and the merge box is absent rather than broken where it is
1929/// too old: a check that only fired at merge time would be a check nobody sees until
1930/// they have already written the pull request.
1931const MERGE_TREE_SINCE: (u32, u32) = (2, 38);
1932
1933/// What this machine's `git` can do, read once at boot.
1934///
1935/// One struct rather than a bare version number, because a version is a fact about git
1936/// and this is a fact about what Steid may offer — and the pages only ever ask the
1937/// second question. Adding a capability later is a field here, not a comparison
1938/// scattered across use cases.
1939#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1940pub struct GitFeatures {
1941 /// Whether `git merge-tree --write-tree` is available, and therefore whether a pull
1942 /// request can be merged from the web at all.
1943 pub merge_tree: bool,
1944}
1945
1946impl GitFeatures {
1947 /// Asks git what version it is and decides what that allows.
1948 ///
1949 /// **Never fails.** A git that cannot be run or whose output cannot be parsed
1950 /// reports no capabilities, which degrades the merge box into its "this server
1951 /// cannot merge" state rather than refusing to boot. Steid needs git for everything
1952 /// else too, so a truly missing binary announces itself within one request anyway.
1953 pub async fn detect() -> Self {
1954 let Ok(output) = git_command()
1955 .arg("--version")
1956 .stdin(Stdio::null())
1957 .output()
1958 .await
1959 else {
1960 return Self::default();
1961 };
1962
1963 let version = parse_git_version(&String::from_utf8_lossy(&output.stdout));
1964
1965 Self {
1966 merge_tree: version.is_some_and(|version| version >= MERGE_TREE_SINCE),
1967 }
1968 }
1969}
1970
1971/// Reads `git version 2.47.1` — and `git version 2.39.5 (Apple Git-154)` — as `(2, 47)`.
1972///
1973/// Only the first two components, because that is the whole of what a feature floor is
1974/// ever expressed in. A patch release has never added a subcommand.
1975fn parse_git_version(output: &str) -> Option<(u32, u32)> {
1976 let version = output.split_whitespace().nth(2)?;
1977 let mut parts = version.split('.');
1978
1979 Some((parts.next()?.parse().ok()?, parts.next()?.parse().ok()?))
1980}
1981
1982/// Merges written into bare repositories under a data directory.
1983///
1984/// The write half of a merge, whose read half — "would this even merge?" — is
1985/// [`GitQuery::merge_preview`]. They are separate ports for the reason
1986/// [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md) separates
1987/// everything else: asking is safe and idempotent, and moving a branch is neither.
1988#[derive(Debug, Clone)]
1989pub struct DiskGitMerge {
1990 data_dir: PathBuf,
1991}
1992
1993impl DiskGitMerge {
1994 pub fn new(data_dir: impl Into<PathBuf>) -> Self {
1995 Self {
1996 data_dir: data_dir.into(),
1997 }
1998 }
1999
2000 /// Where a repository lives, matching `DiskGitStorage`'s layout.
2001 fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf {
2002 self.data_dir
2003 .join(handle.as_str())
2004 .join(format!("{name}.git"))
2005 }
2006
2007 /// Moves or deletes a ref, guarded on where it is now.
2008 ///
2009 /// One function for both because they differ only by a `-d` and by whether a new
2010 /// value is passed, and the interesting half — telling "somebody pushed" apart from
2011 /// "git broke" — is identical and worth having in one place.
2012 async fn guarded_update(
2013 &self,
2014 handle: &OrgName,
2015 name: &RepoName,
2016 branch: &RefName,
2017 new: Option<&ObjectId>,
2018 old: &ObjectId,
2019 ) -> Result<(), GitMergeError> {
2020 let path = self.repo_path(handle, name);
2021 let full = format!("refs/heads/{branch}");
2022
2023 let mut command = git_command();
2024 command
2025 .arg("--git-dir")
2026 .arg(&path)
2027 .arg("update-ref")
2028 .stdin(Stdio::null());
2029
2030 match new {
2031 Some(new) => {
2032 command.arg(&full).arg(new.as_str()).arg(old.as_str());
2033 }
2034 None => {
2035 command.arg("-d").arg(&full).arg(old.as_str());
2036 }
2037 }
2038
2039 let output = command
2040 .output()
2041 .await
2042 .map_err(|error| GitMergeError::backend(format!("could not run git: {error}")))?;
2043
2044 if output.status.success() {
2045 return Ok(());
2046 }
2047
2048 let stderr = String::from_utf8_lossy(&output.stderr);
2049
2050 // git has no distinct exit status for "the old value did not match" — it is 1,
2051 // and so is everything else — so the sentence is what tells them apart. It is
2052 // matched loosely on purpose: the two spellings git has used are "is at … but
2053 // expected …" for a move and "is at … but expected …" for a delete, and a
2054 // future third would still contain "expected".
2055 if stderr.contains("but expected") {
2056 return Err(GitMergeError::Stale);
2057 }
2058
2059 Err(GitMergeError::backend(format!(
2060 "git update-ref exited with {}: {}",
2061 output.status,
2062 stderr.trim()
2063 )))
2064 }
2065}
2066
2067impl GitMerge for DiskGitMerge {
2068 async fn commit_tree(
2069 &self,
2070 handle: &OrgName,
2071 name: &RepoName,
2072 request: &CommitTreeRequest,
2073 ) -> Result<ObjectId, GitMergeError> {
2074 let path = self.repo_path(handle, name);
2075
2076 let mut command = git_command();
2077 command
2078 .arg("--git-dir")
2079 .arg(&path)
2080 .arg("commit-tree")
2081 .arg(request.tree.as_str());
2082
2083 for parent in &request.parents {
2084 command.arg("-p").arg(parent.as_str());
2085 }
2086
2087 // `-m` rather than the message on stdin: a commit message is bounded by the
2088 // pull request's own body cap, and passing it as an argument keeps this one
2089 // process with no plumbing to get wrong.
2090 command.arg("-m").arg(&request.message);
2091
2092 let stamp = git_timestamp(request.now);
2093
2094 // Author *and* committer, both the person who pressed Merge. Nobody else is
2095 // more the author of a merge commit than whoever decided to make it, and a
2096 // commit whose author git had to invent from the host's hostname is a commit
2097 // nobody can attribute later.
2098 //
2099 // The date is passed rather than left to git's own clock so that a use case
2100 // taking a `now` actually controls the commit it makes — the same rule every
2101 // other timestamp in Steid follows.
2102 command
2103 .env("GIT_AUTHOR_NAME", &request.author_name)
2104 .env("GIT_AUTHOR_EMAIL", &request.author_email)
2105 .env("GIT_AUTHOR_DATE", &stamp)
2106 .env("GIT_COMMITTER_NAME", &request.author_name)
2107 .env("GIT_COMMITTER_EMAIL", &request.author_email)
2108 .env("GIT_COMMITTER_DATE", &stamp)
2109 .stdin(Stdio::null());
2110
2111 let output = command
2112 .output()
2113 .await
2114 .map_err(|error| GitMergeError::backend(format!("could not run git: {error}")))?;
2115
2116 if !output.status.success() {
2117 return Err(GitMergeError::backend(format!(
2118 "git commit-tree exited with {}: {}",
2119 output.status,
2120 String::from_utf8_lossy(&output.stderr).trim()
2121 )));
2122 }
2123
2124 let id = String::from_utf8_lossy(&output.stdout);
2125
2126 ObjectId::new(id.trim())
2127 .map_err(|error| GitMergeError::backend(format!("git named a bad commit: {error}")))
2128 }
2129
2130 async fn update_ref(
2131 &self,
2132 handle: &OrgName,
2133 name: &RepoName,
2134 branch: &RefName,
2135 new: &ObjectId,
2136 old: &ObjectId,
2137 ) -> Result<(), GitMergeError> {
2138 self.guarded_update(handle, name, branch, Some(new), old)
2139 .await
2140 }
2141
2142 async fn delete_ref(
2143 &self,
2144 handle: &OrgName,
2145 name: &RepoName,
2146 branch: &RefName,
2147 old: &ObjectId,
2148 ) -> Result<(), GitMergeError> {
2149 self.guarded_update(handle, name, branch, None, old).await
2150 }
2151}
2152
2153/// A time in the one date format git will not try to be clever about.
2154///
2155/// `@<seconds> <zone>` is git's raw form, and the `@` is load-bearing: without it git
2156/// runs the value through its human-date parser, which reads a bare `1700000000` as an
2157/// epoch by luck and refuses `0` outright — so a commit made at the epoch failed while
2158/// every other one worked.
2159///
2160/// `+0000` always. Steid stores every time as an instant and has nowhere to get a
2161/// person's zone from, and a made-up offset would be a claim about where somebody was.
2162fn git_timestamp(now: SystemTime) -> String {
2163 let seconds = now
2164 .duration_since(SystemTime::UNIX_EPOCH)
2165 .map(|elapsed| elapsed.as_secs())
2166 .unwrap_or(0);
2167
2168 format!("@{seconds} +0000")
2169}
2170
2171/// Merges recorded in memory, for testing use cases without a repository.
2172///
2173/// Records what it was asked to do and answers with ids a test seeded, so a use case
2174/// test can assert the *sequence* — commit, then move the target, then delete the
2175/// source — which is the part that has to be right and the part a disk fixture makes
2176/// slow to check.
2177#[derive(Debug, Default, Clone)]
2178pub struct InMemoryGitMerge {
2179 commits: Arc<Mutex<Vec<CommitTreeRequest>>>,
2180 updates: Arc<Mutex<Vec<RecordedRefUpdate>>>,
2181 /// The id every `commit_tree` answers with.
2182 written: Option<ObjectId>,
2183 /// Makes every ref update report that somebody else pushed first.
2184 stale: bool,
2185}
2186
2187/// One ref update a fake merge was asked to make. `new` is `None` for a delete.
2188#[derive(Debug, Clone, PartialEq, Eq)]
2189pub struct RecordedRefUpdate {
2190 pub branch: RefName,
2191 pub new: Option<ObjectId>,
2192 pub old: ObjectId,
2193}
2194
2195impl InMemoryGitMerge {
2196 pub fn new() -> Self {
2197 Self::default()
2198 }
2199
2200 /// What `commit_tree` will answer with.
2201 pub fn writing(id: &str) -> Self {
2202 Self {
2203 written: Some(ObjectId::from_trusted(format!("{id:0>40}"))),
2204 ..Self::default()
2205 }
2206 }
2207
2208 /// A repository where every ref moved under the merge's feet.
2209 pub fn stale() -> Self {
2210 Self {
2211 stale: true,
2212 ..Self::default()
2213 }
2214 }
2215
2216 /// The commits it was asked to write, in order.
2217 pub fn commits(&self) -> Vec<CommitTreeRequest> {
2218 self.commits.lock().expect("lock poisoned").clone()
2219 }
2220
2221 /// The ref updates it was asked to make, in order.
2222 pub fn updates(&self) -> Vec<RecordedRefUpdate> {
2223 self.updates.lock().expect("lock poisoned").clone()
2224 }
2225}
2226
2227impl GitMerge for InMemoryGitMerge {
2228 async fn commit_tree(
2229 &self,
2230 _handle: &OrgName,
2231 _name: &RepoName,
2232 request: &CommitTreeRequest,
2233 ) -> Result<ObjectId, GitMergeError> {
2234 self.commits
2235 .lock()
2236 .expect("lock poisoned")
2237 .push(request.clone());
2238
2239 Ok(self
2240 .written
2241 .clone()
2242 .unwrap_or_else(|| ObjectId::from_trusted("c".repeat(40))))
2243 }
2244
2245 async fn update_ref(
2246 &self,
2247 _handle: &OrgName,
2248 _name: &RepoName,
2249 branch: &RefName,
2250 new: &ObjectId,
2251 old: &ObjectId,
2252 ) -> Result<(), GitMergeError> {
2253 if self.stale {
2254 return Err(GitMergeError::Stale);
2255 }
2256
2257 self.updates
2258 .lock()
2259 .expect("lock poisoned")
2260 .push(RecordedRefUpdate {
2261 branch: branch.clone(),
2262 new: Some(new.clone()),
2263 old: old.clone(),
2264 });
2265
2266 Ok(())
2267 }
2268
2269 async fn delete_ref(
2270 &self,
2271 _handle: &OrgName,
2272 _name: &RepoName,
2273 branch: &RefName,
2274 old: &ObjectId,
2275 ) -> Result<(), GitMergeError> {
2276 if self.stale {
2277 return Err(GitMergeError::Stale);
2278 }
2279
2280 self.updates
2281 .lock()
2282 .expect("lock poisoned")
2283 .push(RecordedRefUpdate {
2284 branch: branch.clone(),
2285 new: None,
2286 old: old.clone(),
2287 });
2288
2289 Ok(())
2290 }
2291}
2292
2293#[cfg(test)]
2294mod tests {
2295 use std::path::Path;
2296
2297 use tempfile::TempDir;
2298
2299 use tokio::io::AsyncReadExt;
2300
2301 use super::*;
2302 use crate::application::port::ArchiveFormat;
2303
2304 /// The `TempDir` is returned alongside the storage because dropping it deletes the
2305 /// data directory — binding it to `_` would remove the fixture mid-test.
2306 fn storage() -> (TempDir, DiskGitStorage) {
2307 let dir = TempDir::new().expect("temp dir");
2308 let storage = DiskGitStorage::new(dir.path());
2309 (dir, storage)
2310 }
2311
2312 fn handle() -> OrgName {
2313 OrgName::new("jamesgill").expect("valid handle")
2314 }
2315
2316 fn repo_name(value: &str) -> RepoName {
2317 RepoName::new(value).expect("valid repository name")
2318 }
2319
2320 /// Asks git about a repository, so assertions test what git believes rather than
2321 /// what the directory looks like.
2322 fn git_says(path: &Path, args: &[&str]) -> String {
2323 let output = std::process::Command::new("git")
2324 .arg("-C")
2325 .arg(path)
2326 .args(args)
2327 .output()
2328 .expect("git should be on PATH");
2329
2330 assert!(
2331 output.status.success(),
2332 "git {args:?} failed: {}",
2333 String::from_utf8_lossy(&output.stderr)
2334 );
2335
2336 String::from_utf8_lossy(&output.stdout).trim().to_owned()
2337 }
2338
2339 // --- Reconciling the data directory ----------------------------------------------
2340
2341 #[tokio::test]
2342 async fn every_repository_directory_is_listed_and_the_quarantine_is_not() {
2343 let (dir, storage) = storage();
2344 let handle = handle();
2345
2346 for name in ["steid", "notes"] {
2347 storage
2348 .init_bare(&handle, &repo_name(name))
2349 .await
2350 .expect("init bare");
2351 }
2352
2353 // Something that is not a repository, beside them.
2354 fs::create_dir_all(dir.path().join(handle.as_str()).join("scratch"))
2355 .await
2356 .expect("make a stray directory");
2357
2358 let mut listed = storage.list_repo_dirs().await.expect("should list");
2359 listed.sort_by(|a, b| a.name.cmp(&b.name));
2360
2361 assert_eq!(
2362 listed
2363 .iter()
2364 .map(|found| (found.handle.as_str(), found.name.as_str()))
2365 .collect::<Vec<_>>(),
2366 vec![("jamesgill", "notes"), ("jamesgill", "steid")],
2367 "only `.git` directories, and the extension is stripped"
2368 );
2369 assert!(listed[0].path.is_dir());
2370 }
2371
2372 #[tokio::test]
2373 async fn an_orphan_is_moved_aside_rather_than_deleted_and_frees_its_name() {
2374 let (dir, storage) = storage();
2375 let handle = handle();
2376 let name = repo_name("half-made");
2377
2378 storage.init_bare(&handle, &name).await.expect("init bare");
2379
2380 // Something identifiable inside it, so "moved rather than deleted" is a claim
2381 // about the contents rather than about the directory existing.
2382 let marker = storage.repo_path(&handle, &name).join("HEAD");
2383 assert!(marker.exists());
2384
2385 let found = storage.list_repo_dirs().await.expect("should list");
2386 let moved = storage
2387 .quarantine(&found[0], "1757000000-half-made")
2388 .await
2389 .expect("should move it aside");
2390
2391 assert_eq!(
2392 moved,
2393 dir.path().join("orphaned").join("1757000000-half-made")
2394 );
2395 assert!(moved.join("HEAD").exists(), "the objects came with it");
2396 assert!(!storage.repo_path(&handle, &name).exists());
2397
2398 // The whole point: the name is usable again.
2399 storage
2400 .init_bare(&handle, &name)
2401 .await
2402 .expect("the name is free");
2403
2404 // And the sweep does not find its own output on the next boot.
2405 assert_eq!(
2406 storage
2407 .list_repo_dirs()
2408 .await
2409 .expect("should list")
2410 .iter()
2411 .map(|found| found.name.clone())
2412 .collect::<Vec<_>>(),
2413 vec!["half-made".to_owned()]
2414 );
2415 }
2416
2417 #[test]
2418 fn the_quarantine_directory_can_never_be_a_real_handle() {
2419 // `list_repo_dirs` skips this name so a sweep cannot re-quarantine its own
2420 // output. That skip is only safe because no owner can hold the handle; if the
2421 // two ever drift apart, one person's repositories silently stop being swept.
2422 assert!(
2423 OrgName::new(QUARANTINE).is_err(),
2424 "{QUARANTINE} must stay a reserved handle"
2425 );
2426 }
2427
2428 #[tokio::test]
2429 async fn a_quarantine_never_overwrites_what_is_already_there() {
2430 let (dir, storage) = storage();
2431 let handle = handle();
2432
2433 storage
2434 .init_bare(&handle, &repo_name("thing"))
2435 .await
2436 .expect("init bare");
2437
2438 fs::create_dir_all(dir.path().join("orphaned").join("1757000000-thing"))
2439 .await
2440 .expect("stage a collision");
2441
2442 let found = storage.list_repo_dirs().await.expect("should list");
2443
2444 assert!(matches!(
2445 storage.quarantine(&found[0], "1757000000-thing").await,
2446 Err(GitStorageError::AlreadyExists)
2447 ));
2448 assert!(
2449 storage.repo_path(&handle, &repo_name("thing")).exists(),
2450 "nothing was moved, so nothing was lost"
2451 );
2452 }
2453
2454 // --- Importing ------------------------------------------------------------------
2455
2456 /// A source repository on disk with two branches and an annotated tag, so a mirror
2457 /// has something to lose.
2458 fn source_repo() -> (TempDir, PathBuf) {
2459 let dir = TempDir::new().expect("temp dir");
2460 let path = dir.path().join("source");
2461
2462 std::fs::create_dir(&path).expect("create");
2463
2464 let run = |args: &[&str]| {
2465 let output = std::process::Command::new("git")
2466 .arg("-C")
2467 .arg(&path)
2468 .args(args)
2469 .env("GIT_CONFIG_GLOBAL", "/dev/null")
2470 .env("GIT_CONFIG_SYSTEM", "/dev/null")
2471 .env("GIT_AUTHOR_NAME", "Ada")
2472 .env("GIT_AUTHOR_EMAIL", "ada@example.com")
2473 .env("GIT_COMMITTER_NAME", "Ada")
2474 .env("GIT_COMMITTER_EMAIL", "ada@example.com")
2475 .output()
2476 .expect("git should be on PATH");
2477 assert!(
2478 output.status.success(),
2479 "git {args:?} failed: {}",
2480 String::from_utf8_lossy(&output.stderr)
2481 );
2482 };
2483
2484 run(&["init", "--quiet", "--initial-branch=main"]);
2485 std::fs::write(path.join("README.md"), "# source\n").expect("write");
2486 run(&["add", "README.md"]);
2487 run(&["commit", "--quiet", "-m", "first"]);
2488 run(&["tag", "-a", "v0.1.0", "-m", "first"]);
2489 run(&["checkout", "--quiet", "-b", "side"]);
2490 std::fs::write(path.join("more.md"), "more\n").expect("write");
2491 run(&["add", "more.md"]);
2492 run(&["commit", "--quiet", "-m", "second"]);
2493 run(&["checkout", "--quiet", "main"]);
2494
2495 (dir, path)
2496 }
2497
2498 /// The shape an import has to leave behind, exercised end to end minus the network.
2499 ///
2500 /// The clone is run against a local path because `ImportSource` allows only public
2501 /// HTTPS, which cannot be stood up in a unit test. Everything the adapter decides
2502 /// after the transfer — the refs, `HEAD`, and the remote — is the same either way,
2503 /// and it is the half that could plausibly be wrong.
2504 #[tokio::test]
2505 async fn a_mirror_lands_as_an_ordinary_bare_repository() {
2506 let (_source_dir, source) = source_repo();
2507 let (dest_dir, _storage) = storage();
2508 let destination = dest_dir.path().join("mirrored.git");
2509
2510 run_import(
2511 [
2512 OsStr::new("clone"),
2513 OsStr::new("--mirror"),
2514 OsStr::new("--quiet"),
2515 OsStr::new("--"),
2516 source.as_os_str(),
2517 destination.as_os_str(),
2518 ],
2519 None,
2520 )
2521 .await
2522 .expect("the clone should succeed");
2523
2524 finish_mirror(&destination)
2525 .await
2526 .expect("the mirror should finish");
2527
2528 // Every branch, under `refs/heads` — where every other page in Steid looks.
2529 let branches = git_says(
2530 &destination,
2531 &["for-each-ref", "--format=%(refname)", "refs/heads/"],
2532 );
2533 assert_eq!(branches, "refs/heads/main\nrefs/heads/side");
2534
2535 // Tags too, annotated ones included.
2536 assert_eq!(
2537 git_says(
2538 &destination,
2539 &["for-each-ref", "--format=%(refname)", "refs/tags/"]
2540 ),
2541 "refs/tags/v0.1.0"
2542 );
2543
2544 // Nothing left under `refs/remotes`, and no remote to fetch from.
2545 assert_eq!(
2546 git_says(
2547 &destination,
2548 &["for-each-ref", "--format=%(refname)", "refs/remotes/"]
2549 ),
2550 ""
2551 );
2552 assert_eq!(git_says(&destination, &["remote"]), "");
2553
2554 // `HEAD` follows the source's default branch, so the landing page opens on it.
2555 assert_eq!(
2556 git_says(&destination, &["symbolic-ref", "HEAD"]),
2557 "refs/heads/main"
2558 );
2559 assert_eq!(
2560 git_says(&destination, &["rev-parse", "--is-bare-repository"]),
2561 "true"
2562 );
2563
2564 // And a reflog, so the first push into an imported repository records who made
2565 // it. `git clone` leaves this off exactly as `git init --bare` does, and an
2566 // import never goes through `init_bare`.
2567 assert_eq!(
2568 git_says(&destination, &["config", "--get", "core.logAllRefUpdates"]),
2569 "true"
2570 );
2571 }
2572
2573 /// A source whose branches arrived under `refs/remotes` — the case `--mirror`
2574 /// normally makes impossible, which is exactly why nothing else would catch it.
2575 #[tokio::test]
2576 async fn branches_left_under_refs_remotes_are_moved_to_refs_heads() {
2577 let (_source_dir, source) = source_repo();
2578 let (dest_dir, _storage) = storage();
2579 let destination = dest_dir.path().join("remotes.git");
2580
2581 // A plain `--bare` clone with a fetch refspec that writes remote-tracking refs,
2582 // which is what a non-mirror clone of a mirror can leave.
2583 run_import(
2584 [
2585 OsStr::new("clone"),
2586 OsStr::new("--bare"),
2587 OsStr::new("--quiet"),
2588 OsStr::new("--"),
2589 source.as_os_str(),
2590 destination.as_os_str(),
2591 ],
2592 None,
2593 )
2594 .await
2595 .expect("clone");
2596
2597 // Stage the shape by hand: a branch only under `refs/remotes`.
2598 run_import(
2599 [
2600 OsStr::new("update-ref"),
2601 OsStr::new("refs/remotes/origin/side"),
2602 OsStr::new("refs/heads/main"),
2603 ],
2604 Some(&destination),
2605 )
2606 .await
2607 .expect("stage a remote-tracking ref");
2608 run_import(
2609 [
2610 OsStr::new("symbolic-ref"),
2611 OsStr::new("refs/remotes/origin/HEAD"),
2612 OsStr::new("refs/remotes/origin/side"),
2613 ],
2614 Some(&destination),
2615 )
2616 .await
2617 .expect("stage origin/HEAD");
2618
2619 finish_mirror(&destination).await.expect("finish");
2620
2621 let branches = git_says(
2622 &destination,
2623 &["for-each-ref", "--format=%(refname)", "refs/heads/"],
2624 );
2625 assert!(
2626 branches.contains("refs/heads/side"),
2627 "expected the remote-tracking branch to become a branch, got {branches:?}"
2628 );
2629 assert_eq!(
2630 git_says(
2631 &destination,
2632 &["for-each-ref", "--format=%(refname)", "refs/remotes/"]
2633 ),
2634 "",
2635 "origin/HEAD is a pointer, not a branch, and must not survive either"
2636 );
2637 }
2638
2639 /// The DNS half of the server-side request forgery check, which `ImportSource`
2640 /// cannot make: `localhost` is a name, and only resolving it says where it goes.
2641 #[tokio::test]
2642 async fn a_host_that_resolves_to_loopback_is_refused() {
2643 let error = resolve_public_host("localhost")
2644 .await
2645 .expect_err("localhost must never be dialled");
2646
2647 assert!(
2648 error.message().contains("not on the public internet"),
2649 "{error}"
2650 );
2651 }
2652
2653 #[tokio::test]
2654 async fn a_host_that_does_not_resolve_is_a_failed_import_not_a_panic() {
2655 let error = resolve_public_host("no-such-host.invalid")
2656 .await
2657 .expect_err("`.invalid` never resolves");
2658
2659 assert!(error.message().contains("no-such-host.invalid"), "{error}");
2660 }
2661
2662 /// git's last line is the reason; the lines before it are progress.
2663 #[tokio::test]
2664 async fn a_failed_git_command_carries_gits_own_last_word() {
2665 let (dir, _storage) = storage();
2666
2667 let error = run_import(
2668 [OsStr::new("rev-parse"), OsStr::new("HEAD")],
2669 Some(dir.path()),
2670 )
2671 .await
2672 .expect_err("an empty directory is not a repository");
2673
2674 assert!(
2675 error.message().contains("not a git repository"),
2676 "expected git's own words, got {error}"
2677 );
2678 }
2679
2680 #[tokio::test]
2681 async fn an_import_refuses_a_path_that_is_already_occupied() {
2682 let (dir, storage) = storage();
2683 let importer = DiskGitImport::new(dir.path());
2684
2685 storage
2686 .init_bare(&handle(), &repo_name("taken"))
2687 .await
2688 .expect("seed");
2689
2690 let error = importer
2691 .mirror(
2692 &handle(),
2693 &repo_name("taken"),
2694 &ImportSource::new("https://example.com/taken.git").expect("valid"),
2695 )
2696 .await
2697 .expect_err("must not adopt what is already there");
2698
2699 assert!(error.message().contains("already on disk"), "{error}");
2700 }
2701
2702 #[tokio::test]
2703 async fn the_in_memory_importer_records_what_it_was_asked_for() {
2704 let importer = InMemoryGitImport::new();
2705 let source = ImportSource::new("https://example.com/thing.git").expect("valid");
2706
2707 importer
2708 .mirror(&handle(), &repo_name("thing"), &source)
2709 .await
2710 .expect("succeeds");
2711
2712 assert_eq!(
2713 importer.requests(),
2714 vec![(
2715 "jamesgill".to_owned(),
2716 "thing".to_owned(),
2717 "https://example.com/thing.git".to_owned()
2718 )]
2719 );
2720 }
2721
2722 #[tokio::test]
2723 async fn a_created_repository_keeps_a_reflog() {
2724 // Without this, `REMOTE_USER` has nowhere to land: a bare repository logs no ref
2725 // updates by default, so who moved a branch is unknowable even though Steid knew.
2726 let dir = TempDir::new().expect("temp dir");
2727 let storage = DiskGitStorage::new(dir.path());
2728
2729 storage
2730 .init_bare(&handle(), &repo_name("steid"))
2731 .await
2732 .expect("should create");
2733
2734 let config = std::fs::read_to_string(
2735 storage
2736 .repo_path(&handle(), &repo_name("steid"))
2737 .join("config"),
2738 )
2739 .expect("read config");
2740
2741 assert!(
2742 config.to_lowercase().contains("logallrefupdates = true"),
2743 "a bare repository needs reflogs turned on: {config}"
2744 );
2745 }
2746
2747 #[tokio::test]
2748 async fn the_boot_sweep_gives_an_older_repository_a_reflog() {
2749 // The state every repository created before 2026-09-06 is in. Reproduced by
2750 // unsetting the key rather than by hand-building a repository, so the test is
2751 // about the sweep and not about how `git init` used to behave.
2752 let (_dir, storage) = storage();
2753 let path = storage.repo_path(&handle(), &repo_name("steid"));
2754
2755 storage
2756 .init_bare(&handle(), &repo_name("steid"))
2757 .await
2758 .expect("should create");
2759
2760 git_command()
2761 .args([
2762 OsStr::new("--git-dir"),
2763 path.as_os_str(),
2764 OsStr::new("config"),
2765 OsStr::new("--unset"),
2766 OsStr::new("core.logAllRefUpdates"),
2767 ])
2768 .output()
2769 .await
2770 .expect("unset");
2771
2772 assert_eq!(storage.enable_reflogs().await.expect("should sweep"), 1);
2773
2774 let config = std::fs::read_to_string(path.join("config")).expect("read config");
2775 assert!(
2776 config.to_lowercase().contains("logallrefupdates = true"),
2777 "the sweep should have turned reflogs on: {config}"
2778 );
2779
2780 // Idempotent, which is what makes running it on every boot cheap: nothing is
2781 // written the second time, and the count says so.
2782 assert_eq!(storage.enable_reflogs().await.expect("should sweep"), 0);
2783 }
2784
2785 #[tokio::test]
2786 async fn the_boot_sweep_leaves_a_deliberate_false_alone() {
2787 // Somebody turned it off on purpose. A sweep that overrules a chosen setting is
2788 // worse than one that misses a repository.
2789 let (_dir, storage) = storage();
2790 let path = storage.repo_path(&handle(), &repo_name("steid"));
2791
2792 storage
2793 .init_bare(&handle(), &repo_name("steid"))
2794 .await
2795 .expect("should create");
2796
2797 run_git([
2798 OsStr::new("--git-dir"),
2799 path.as_os_str(),
2800 OsStr::new("config"),
2801 OsStr::new("core.logAllRefUpdates"),
2802 OsStr::new("false"),
2803 ])
2804 .await
2805 .expect("set false");
2806
2807 assert_eq!(storage.enable_reflogs().await.expect("should sweep"), 0);
2808
2809 let config = std::fs::read_to_string(path.join("config")).expect("read config");
2810 assert!(config.to_lowercase().contains("logallrefupdates = false"));
2811 }
2812
2813 #[tokio::test]
2814 async fn the_boot_sweep_ignores_what_is_not_a_repository() {
2815 // A fresh instance has no data directory at all, and a stray file under one is not
2816 // something to run `git config` against.
2817 let dir = TempDir::new().expect("temp dir");
2818 let missing = DiskGitStorage::new(dir.path().join("not-created-yet"));
2819
2820 assert_eq!(missing.enable_reflogs().await.expect("should sweep"), 0);
2821
2822 let (_dir, storage) = storage();
2823 std::fs::create_dir_all(dir.path().join("jamesgill")).expect("mkdir");
2824 std::fs::write(dir.path().join("jamesgill").join("notes.txt"), b"hello").expect("write");
2825
2826 assert_eq!(storage.enable_reflogs().await.expect("should sweep"), 0);
2827 }
2828
2829 #[tokio::test]
2830 async fn init_bare_creates_a_bare_repository() {
2831 let (_dir, storage) = storage();
2832
2833 storage
2834 .init_bare(&handle(), &repo_name("steid"))
2835 .await
2836 .expect("should create");
2837
2838 let path = storage.repo_path(&handle(), &repo_name("steid"));
2839 assert!(path.is_dir(), "expected a repository at {path:?}");
2840 assert_eq!(
2841 git_says(&path, &["rev-parse", "--is-bare-repository"]),
2842 "true"
2843 );
2844 }
2845
2846 #[tokio::test]
2847 async fn a_new_repository_is_empty() {
2848 // Empty, like GitHub: no initial commit and no branch yet.
2849 let (_dir, storage) = storage();
2850 storage
2851 .init_bare(&handle(), &repo_name("steid"))
2852 .await
2853 .expect("should create");
2854
2855 let path = storage.repo_path(&handle(), &repo_name("steid"));
2856
2857 assert_eq!(git_says(&path, &["for-each-ref"]), "");
2858 }
2859
2860 #[tokio::test]
2861 async fn a_new_repository_defaults_to_main() {
2862 // Pinned so the host's `init.defaultBranch` cannot decide this. It currently
2863 // agrees on this machine, which is exactly why a drift would go unnoticed.
2864 let (_dir, storage) = storage();
2865 storage
2866 .init_bare(&handle(), &repo_name("steid"))
2867 .await
2868 .expect("should create");
2869
2870 let path = storage.repo_path(&handle(), &repo_name("steid"));
2871
2872 assert_eq!(
2873 git_says(&path, &["symbolic-ref", "HEAD"]),
2874 "refs/heads/main"
2875 );
2876 }
2877
2878 #[tokio::test]
2879 async fn no_sample_hooks_are_installed() {
2880 // Pins `--template=`. A default init seeds sixteen `.sample` files.
2881 let (_dir, storage) = storage();
2882 storage
2883 .init_bare(&handle(), &repo_name("steid"))
2884 .await
2885 .expect("should create");
2886
2887 let hooks = storage
2888 .repo_path(&handle(), &repo_name("steid"))
2889 .join("hooks");
2890
2891 let samples = std::fs::read_dir(&hooks)
2892 .map(|entries| entries.count())
2893 .unwrap_or(0);
2894 assert_eq!(samples, 0, "expected no templated hooks in {hooks:?}");
2895 }
2896
2897 #[tokio::test]
2898 async fn init_bare_creates_the_handle_directory() {
2899 let (dir, storage) = storage();
2900 assert!(!dir.path().join("jamesgill").exists());
2901
2902 storage
2903 .init_bare(&handle(), &repo_name("steid"))
2904 .await
2905 .expect("should create");
2906
2907 assert!(dir.path().join("jamesgill").is_dir());
2908 }
2909
2910 #[tokio::test]
2911 async fn one_handle_can_own_several_repositories() {
2912 let (_dir, storage) = storage();
2913
2914 for name in ["steid", "foo.js", ".github"] {
2915 storage
2916 .init_bare(&handle(), &repo_name(name))
2917 .await
2918 .unwrap_or_else(|error| panic!("{name} should create: {error}"));
2919 }
2920
2921 for name in ["steid", "foo.js", ".github"] {
2922 assert!(storage.repo_path(&handle(), &repo_name(name)).is_dir());
2923 }
2924 }
2925
2926 #[tokio::test]
2927 async fn init_bare_refuses_a_repository_that_already_exists() {
2928 let (_dir, storage) = storage();
2929 storage
2930 .init_bare(&handle(), &repo_name("steid"))
2931 .await
2932 .expect("should create");
2933
2934 let error = storage
2935 .init_bare(&handle(), &repo_name("steid"))
2936 .await
2937 .expect_err("should refuse");
2938
2939 assert!(matches!(error, GitStorageError::AlreadyExists));
2940 }
2941
2942 #[tokio::test]
2943 async fn a_refused_init_leaves_the_existing_repository_alone() {
2944 // git would happily re-initialise in place. The point of refusing is that
2945 // whatever is already there is not touched.
2946 let (_dir, storage) = storage();
2947 storage
2948 .init_bare(&handle(), &repo_name("steid"))
2949 .await
2950 .expect("should create");
2951
2952 let path = storage.repo_path(&handle(), &repo_name("steid"));
2953 let marker = path.join("objects").join("marker");
2954 std::fs::write(&marker, b"existing data").expect("write marker");
2955
2956 let _ = storage.init_bare(&handle(), &repo_name("steid")).await;
2957
2958 assert_eq!(
2959 std::fs::read(&marker).expect("marker should survive"),
2960 b"existing data"
2961 );
2962 }
2963
2964 #[tokio::test]
2965 async fn repo_path_creates_nothing() {
2966 let (dir, storage) = storage();
2967
2968 let path = storage.repo_path(&handle(), &repo_name("never-created"));
2969
2970 assert!(!path.exists());
2971 assert_eq!(
2972 std::fs::read_dir(dir.path())
2973 .expect("data dir should exist")
2974 .count(),
2975 0,
2976 "repo_path must be pure"
2977 );
2978 }
2979
2980 #[tokio::test]
2981 async fn repo_path_lands_under_the_data_directory() {
2982 let (dir, storage) = storage();
2983
2984 let path = storage.repo_path(&handle(), &repo_name("steid"));
2985
2986 assert_eq!(path, dir.path().join("jamesgill").join("steid.git"));
2987 }
2988
2989 #[tokio::test]
2990 async fn remove_deletes_the_repository() {
2991 let (_dir, storage) = storage();
2992 storage
2993 .init_bare(&handle(), &repo_name("steid"))
2994 .await
2995 .expect("should create");
2996
2997 storage
2998 .remove(&handle(), &repo_name("steid"))
2999 .await
3000 .expect("should remove");
3001
3002 assert!(!storage.repo_path(&handle(), &repo_name("steid")).exists());
3003 }
3004
3005 #[tokio::test]
3006 async fn removing_what_is_not_there_succeeds() {
3007 // Compensation runs when a create failed, which may be before anything landed.
3008 let (_dir, storage) = storage();
3009
3010 storage
3011 .remove(&handle(), &repo_name("never-created"))
3012 .await
3013 .expect("should succeed with nothing to do");
3014 }
3015
3016 #[tokio::test]
3017 async fn a_compensated_create_can_be_retried() {
3018 // The whole point of `remove`: create, fail to record it, undo, try again.
3019 let (_dir, storage) = storage();
3020
3021 storage
3022 .init_bare(&handle(), &repo_name("steid"))
3023 .await
3024 .expect("should create");
3025 storage
3026 .remove(&handle(), &repo_name("steid"))
3027 .await
3028 .expect("should remove");
3029 storage
3030 .init_bare(&handle(), &repo_name("steid"))
3031 .await
3032 .expect("should create again");
3033 }
3034
3035 #[tokio::test]
3036 async fn removing_one_repository_leaves_its_neighbours() {
3037 let (_dir, storage) = storage();
3038 storage
3039 .init_bare(&handle(), &repo_name("steid"))
3040 .await
3041 .expect("should create");
3042 storage
3043 .init_bare(&handle(), &repo_name("keeper"))
3044 .await
3045 .expect("should create");
3046
3047 storage
3048 .remove(&handle(), &repo_name("steid"))
3049 .await
3050 .expect("should remove");
3051
3052 assert!(storage.repo_path(&handle(), &repo_name("keeper")).is_dir());
3053 }
3054
3055 #[tokio::test]
3056 async fn a_failing_git_invocation_carries_gits_own_message() {
3057 let error = run_git(["not-a-real-subcommand"])
3058 .await
3059 .expect_err("should fail");
3060
3061 let message = error.to_string();
3062 assert!(
3063 message.contains("not-a-real-subcommand"),
3064 "expected git's own words, got: {message}"
3065 );
3066 }
3067
3068 // --- GitHttpBackend --------------------------------------------------------
3069
3070 /// A data directory holding one bare repository at `acme/steid.git`.
3071 async fn backend() -> (TempDir, GitHttpBackend) {
3072 let dir = TempDir::new().expect("temp dir");
3073 let storage = DiskGitStorage::new(dir.path());
3074
3075 let acme = OrgName::new("acme").expect("valid handle");
3076 storage
3077 .init_bare(&acme, &repo_name("steid"))
3078 .await
3079 .expect("init bare");
3080
3081 let backend = GitHttpBackend::new(dir.path());
3082 (dir, backend)
3083 }
3084
3085 fn advertisement(path_info: &str) -> GitRequest {
3086 GitRequest {
3087 method: GitMethod::Get,
3088 path_info: path_info.to_owned(),
3089 query: "service=git-upload-pack".to_owned(),
3090 content_type: None,
3091 content_encoding: None,
3092 content_length: None,
3093 git_protocol: None,
3094 allow_receive_pack: false,
3095 remote_user: None,
3096 body: Box::pin(tokio::io::empty()),
3097 }
3098 }
3099
3100 async fn drain(response: GitResponse) -> Vec<u8> {
3101 let mut body = response.body;
3102 let mut bytes = Vec::new();
3103 body.read_to_end(&mut bytes).await.expect("read body");
3104 bytes
3105 }
3106
3107 #[tokio::test]
3108 async fn the_backend_advertises_refs() {
3109 let (_dir, backend) = backend().await;
3110
3111 let response = backend
3112 .serve(advertisement("/acme/steid.git/info/refs"))
3113 .await
3114 .expect("should serve");
3115
3116 assert_eq!(response.status, 200);
3117 assert!(
3118 response
3119 .headers
3120 .iter()
3121 .any(|(name, value)| name == "Content-Type"
3122 && value == "application/x-git-upload-pack-advertisement"),
3123 "git sets its own content type and we forward it: {:?}",
3124 response.headers
3125 );
3126
3127 // The pkt-line the smart protocol opens with. Getting this from git rather than
3128 // writing it is the whole reason the backend is a subprocess.
3129 let body = drain(response).await;
3130 assert!(
3131 body.starts_with(b"001e# service=git-upload-pack\n"),
3132 "unexpected advertisement: {:?}",
3133 String::from_utf8_lossy(&body[..body.len().min(40)])
3134 );
3135 }
3136
3137 #[tokio::test]
3138 async fn a_missing_repository_is_reported_as_404_not_as_a_failure() {
3139 // Failure arrives in the CGI stream, not the exit code: git exits 0 here and
3140 // says 404 in a header. Keying off the exit code instead would answer 200.
3141 let (_dir, backend) = backend().await;
3142
3143 let response = backend
3144 .serve(advertisement("/acme/nothing-here.git/info/refs"))
3145 .await
3146 .expect("serving should not itself fail");
3147
3148 assert_eq!(response.status, 404);
3149 }
3150
3151 #[tokio::test]
3152 async fn the_status_header_is_translated_rather_than_forwarded() {
3153 let (_dir, backend) = backend().await;
3154
3155 let response = backend
3156 .serve(advertisement("/acme/nothing-here.git/info/refs"))
3157 .await
3158 .expect("should serve");
3159
3160 assert!(
3161 !response
3162 .headers
3163 .iter()
3164 .any(|(name, _)| name.eq_ignore_ascii_case("status")),
3165 "Status: is CGI's, and means nothing to an HTTP client: {:?}",
3166 response.headers
3167 );
3168 }
3169
3170 #[tokio::test]
3171 async fn the_protocol_version_reaches_upload_pack() {
3172 // Protocol v2 answers an advertisement with a capability list rather than refs.
3173 // If `HTTP_GIT_PROTOCOL` is dropped the exchange silently falls back to v0, which
3174 // still works — so nothing fails, it just quietly gets worse.
3175 let (_dir, backend) = backend().await;
3176
3177 let mut request = advertisement("/acme/steid.git/info/refs");
3178 request.git_protocol = Some("version=2".to_owned());
3179
3180 let body = drain(backend.serve(request).await.expect("should serve")).await;
3181
3182 assert!(
3183 String::from_utf8_lossy(&body).contains("version 2"),
3184 "expected a v2 capability advertisement: {:?}",
3185 String::from_utf8_lossy(&body[..body.len().min(80)])
3186 );
3187 }
3188
3189 #[tokio::test]
3190 async fn the_in_memory_protocol_records_what_it_was_asked() {
3191 let protocol = InMemoryGitProtocol::new();
3192
3193 protocol
3194 .serve(advertisement("/acme/steid.git/info/refs"))
3195 .await
3196 .expect("should serve");
3197
3198 assert_eq!(
3199 protocol.requests(),
3200 vec![RecordedGitRequest {
3201 method: GitMethod::Get,
3202 path_info: "/acme/steid.git/info/refs".to_owned(),
3203 query: "service=git-upload-pack".to_owned(),
3204 git_protocol: None,
3205 content_encoding: None,
3206 allow_receive_pack: false,
3207 remote_user: None,
3208 }]
3209 );
3210 assert!(protocol.was_called());
3211 }
3212
3213 // --- git archive ---------------------------------------------------------------
3214
3215 /// A bare repository with one commit in it, packed the way a real one is.
3216 ///
3217 /// Built by pushing from a working copy rather than by writing objects directly,
3218 /// for the same reason `git_query`'s fixture is: it is what actually happens.
3219 fn archivable() -> (TempDir, DiskGitArchive, ObjectId) {
3220 let dir = TempDir::new().expect("temp dir");
3221 let storage = DiskGitStorage::new(dir.path());
3222 let repo = storage.repo_path(&handle(), &repo_name("steid"));
3223 let work = dir.path().join("work");
3224
3225 let git = |at: &Path, args: &[&str]| {
3226 let output = std::process::Command::new("git")
3227 .arg("-C")
3228 .arg(at)
3229 .args(args)
3230 .env("GIT_CONFIG_GLOBAL", "/dev/null")
3231 .env("GIT_CONFIG_SYSTEM", "/dev/null")
3232 .env("GIT_AUTHOR_NAME", "Ada Lovelace")
3233 .env("GIT_AUTHOR_EMAIL", "ada@example.com")
3234 .env("GIT_COMMITTER_NAME", "Ada Lovelace")
3235 .env("GIT_COMMITTER_EMAIL", "ada@example.com")
3236 .output()
3237 .expect("git should be on PATH");
3238
3239 assert!(
3240 output.status.success(),
3241 "git {args:?} failed: {}",
3242 String::from_utf8_lossy(&output.stderr)
3243 );
3244
3245 String::from_utf8_lossy(&output.stdout).trim().to_owned()
3246 };
3247
3248 std::fs::create_dir_all(&work).expect("create work tree");
3249 git(
3250 dir.path(),
3251 &[
3252 "init",
3253 "--bare",
3254 "--quiet",
3255 "--template=",
3256 "--initial-branch=main",
3257 "--",
3258 repo.to_str().expect("utf-8 fixture path"),
3259 ],
3260 );
3261 git(&work, &["init", "--quiet", "-b", "main"]);
3262 std::fs::write(work.join("README.md"), b"hello\n").expect("write");
3263 git(&work, &["add", "-A"]);
3264 git(&work, &["commit", "--quiet", "-m", "first"]);
3265 git(
3266 &work,
3267 &["push", "--quiet", repo.to_str().expect("utf-8"), "main"],
3268 );
3269
3270 let head = git(&repo, &["rev-parse", "main"]);
3271 let archives = DiskGitArchive::new(dir.path());
3272
3273 (
3274 dir,
3275 archives,
3276 ObjectId::new(head).expect("a real object id"),
3277 )
3278 }
3279
3280 async fn packed(format: ArchiveFormat) -> Vec<u8> {
3281 let (dir, archives, commit) = archivable();
3282
3283 let mut stream = archives
3284 .archive(ArchiveRequest {
3285 handle: handle(),
3286 name: repo_name("steid"),
3287 format,
3288 commit,
3289 prefix: "steid-main/".to_owned(),
3290 })
3291 .await
3292 .expect("should pack");
3293
3294 let mut bytes = Vec::new();
3295 stream.read_to_end(&mut bytes).await.expect("should stream");
3296
3297 // Held until the bytes are read: dropping the fixture deletes the repository
3298 // git is still reading from.
3299 drop(dir);
3300
3301 bytes
3302 }
3303
3304 #[tokio::test]
3305 async fn a_tarball_carries_the_prefix_directory() {
3306 let bytes = packed(ArchiveFormat::TarGz).await;
3307
3308 // The gzip magic number, so the format flag is doing something rather than
3309 // silently producing an uncompressed tar.
3310 assert_eq!(&bytes[..2], &[0x1f, 0x8b], "expected gzip");
3311 assert!(bytes.len() > 100, "expected a real archive");
3312 }
3313
3314 #[tokio::test]
3315 async fn a_zip_is_a_zip() {
3316 let bytes = packed(ArchiveFormat::Zip).await;
3317
3318 assert_eq!(&bytes[..2], b"PK", "expected a zip");
3319 // The prefix is stored as part of every entry name, uncompressed in the
3320 // central directory, so it is readable in the raw bytes.
3321 assert!(
3322 bytes.windows(11).any(|window| window == b"steid-main/"),
3323 "expected the prefix directory in the archive"
3324 );
3325 }
3326
3327 // --- Merging ----------------------------------------------------------------------
3328
3329 /// A bare repository with `main` and a `tidy` branch off it, and the merge adapter
3330 /// pointed at the same data directory.
3331 ///
3332 /// Returns the repository path too, because every assertion here is "what does git
3333 /// believe now" rather than "what did the adapter say".
3334 fn mergeable() -> (TempDir, DiskGitMerge, PathBuf) {
3335 let dir = TempDir::new().expect("temp dir");
3336 let repo = dir.path().join("jamesgill").join("steid.git");
3337 let work = dir.path().join("work");
3338
3339 let git = |path: &Path, args: &[&str]| -> String {
3340 let output = std::process::Command::new("git")
3341 .arg("-C")
3342 .arg(path)
3343 .args(args)
3344 .env("GIT_CONFIG_GLOBAL", "/dev/null")
3345 .env("GIT_CONFIG_SYSTEM", "/dev/null")
3346 .env("GIT_AUTHOR_NAME", "Ada Lovelace")
3347 .env("GIT_AUTHOR_EMAIL", "ada@example.com")
3348 .env("GIT_COMMITTER_NAME", "Ada Lovelace")
3349 .env("GIT_COMMITTER_EMAIL", "ada@example.com")
3350 .output()
3351 .expect("git should be on PATH");
3352
3353 assert!(
3354 output.status.success(),
3355 "git {args:?} failed: {}",
3356 String::from_utf8_lossy(&output.stderr)
3357 );
3358
3359 String::from_utf8_lossy(&output.stdout).trim().to_owned()
3360 };
3361
3362 std::fs::create_dir_all(&work).expect("create work tree");
3363 git(
3364 dir.path(),
3365 &[
3366 "init",
3367 "--bare",
3368 "--quiet",
3369 "--template=",
3370 "--initial-branch=main",
3371 "--",
3372 repo.to_str().expect("utf-8 fixture path"),
3373 ],
3374 );
3375
3376 git(&work, &["init", "--quiet", "-b", "main"]);
3377 std::fs::write(work.join("README.md"), b"hello\n").expect("write");
3378 git(&work, &["add", "-A"]);
3379 git(&work, &["commit", "--quiet", "-m", "first"]);
3380
3381 git(&work, &["checkout", "--quiet", "-b", "tidy"]);
3382 std::fs::write(work.join("other.txt"), b"tidy\n").expect("write");
3383 git(&work, &["add", "-A"]);
3384 git(&work, &["commit", "--quiet", "-m", "tidy"]);
3385
3386 git(
3387 &work,
3388 &[
3389 "push",
3390 "--quiet",
3391 repo.to_str().expect("utf-8"),
3392 "main",
3393 "tidy",
3394 ],
3395 );
3396
3397 let merges = DiskGitMerge::new(dir.path());
3398
3399 (dir, merges, repo)
3400 }
3401
3402 /// What a revision resolves to in the fixture.
3403 fn head(repo: &Path, revision: &str) -> ObjectId {
3404 ObjectId::new(git_says(repo, &["rev-parse", revision])).expect("a real object id")
3405 }
3406
3407 #[tokio::test]
3408 async fn a_merge_commit_carries_both_parents_and_the_person_who_pressed_merge() {
3409 let (_dir, merges, repo) = mergeable();
3410 let main = head(&repo, "main");
3411 let tidy = head(&repo, "tidy");
3412 let tree = ObjectId::new(git_says(&repo, &["rev-parse", "tidy^{tree}"])).expect("a tree");
3413
3414 let commit = merges
3415 .commit_tree(
3416 &handle(),
3417 &repo_name("steid"),
3418 &CommitTreeRequest {
3419 tree,
3420 parents: vec![main.clone(), tidy.clone()],
3421 message: "Merge pull request #7 from tidy\n\nTidy things up.".to_owned(),
3422 author_name: "Ada Lovelace".to_owned(),
3423 author_email: "ada@example.com".to_owned(),
3424 now: SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000),
3425 },
3426 )
3427 .await
3428 .expect("should write a commit");
3429
3430 // The target first, so the first-parent line stays the target's history.
3431 assert_eq!(
3432 git_says(
3433 &repo,
3434 &["rev-list", "--parents", "-n", "1", commit.as_str()]
3435 ),
3436 format!("{commit} {main} {tidy}")
3437 );
3438 assert_eq!(
3439 git_says(
3440 &repo,
3441 &["log", "-1", "--format=%an <%ae> %at", commit.as_str()]
3442 ),
3443 "Ada Lovelace <ada@example.com> 1700000000",
3444 "the caller's `now` decides the commit's date, not git's clock"
3445 );
3446 // Written, and *not* referenced: the ref update is a separate, later step.
3447 assert_eq!(git_says(&repo, &["rev-parse", "main"]), main.as_str());
3448 }
3449
3450 #[tokio::test]
3451 async fn a_squash_commit_has_one_parent() {
3452 let (_dir, merges, repo) = mergeable();
3453 let main = head(&repo, "main");
3454 let tree = ObjectId::new(git_says(&repo, &["rev-parse", "tidy^{tree}"])).expect("a tree");
3455
3456 let commit = merges
3457 .commit_tree(
3458 &handle(),
3459 &repo_name("steid"),
3460 &CommitTreeRequest {
3461 tree,
3462 parents: vec![main.clone()],
3463 message: "Tidy things up (#7)".to_owned(),
3464 author_name: "Ada Lovelace".to_owned(),
3465 author_email: "ada@example.com".to_owned(),
3466 now: SystemTime::UNIX_EPOCH,
3467 },
3468 )
3469 .await
3470 .expect("should write a commit");
3471
3472 assert_eq!(
3473 git_says(
3474 &repo,
3475 &["rev-list", "--parents", "-n", "1", commit.as_str()]
3476 ),
3477 format!("{commit} {main}")
3478 );
3479 }
3480
3481 #[tokio::test]
3482 async fn moving_a_branch_from_where_it_is_moves_it() {
3483 let (_dir, merges, repo) = mergeable();
3484 let main = head(&repo, "main");
3485 let tidy = head(&repo, "tidy");
3486
3487 merges
3488 .update_ref(
3489 &handle(),
3490 &repo_name("steid"),
3491 &RefName::from_trusted("main"),
3492 &tidy,
3493 &main,
3494 )
3495 .await
3496 .expect("should move the branch");
3497
3498 assert_eq!(git_says(&repo, &["rev-parse", "main"]), tidy.as_str());
3499 }
3500
3501 #[tokio::test]
3502 async fn moving_a_branch_from_where_it_is_not_changes_nothing() {
3503 // The compare-and-swap that makes a concurrent push lose cleanly rather than
3504 // being silently discarded.
3505 let (_dir, merges, repo) = mergeable();
3506 let main = head(&repo, "main");
3507 let tidy = head(&repo, "tidy");
3508
3509 let error = merges
3510 .update_ref(
3511 &handle(),
3512 &repo_name("steid"),
3513 &RefName::from_trusted("main"),
3514 &main,
3515 &tidy,
3516 )
3517 .await
3518 .expect_err("expected the guard to refuse");
3519
3520 assert!(error.is_stale(), "expected staleness, got {error:?}");
3521 assert_eq!(git_says(&repo, &["rev-parse", "main"]), main.as_str());
3522 }
3523
3524 #[tokio::test]
3525 async fn deleting_a_branch_is_guarded_the_same_way() {
3526 let (_dir, merges, repo) = mergeable();
3527 let main = head(&repo, "main");
3528 let tidy = head(&repo, "tidy");
3529
3530 let refused = merges
3531 .delete_ref(
3532 &handle(),
3533 &repo_name("steid"),
3534 &RefName::from_trusted("tidy"),
3535 &main,
3536 )
3537 .await
3538 .expect_err("expected the guard to refuse");
3539 assert!(refused.is_stale(), "expected staleness, got {refused:?}");
3540
3541 merges
3542 .delete_ref(
3543 &handle(),
3544 &repo_name("steid"),
3545 &RefName::from_trusted("tidy"),
3546 &tidy,
3547 )
3548 .await
3549 .expect("should delete the branch");
3550
3551 assert_eq!(
3552 git_says(
3553 &repo,
3554 &["for-each-ref", "--format=%(refname)", "refs/heads/"]
3555 ),
3556 "refs/heads/main"
3557 );
3558 }
3559
3560 // --- What this git can do ----------------------------------------------------------
3561
3562 #[test]
3563 fn a_version_reads_as_major_and_minor() {
3564 assert_eq!(parse_git_version("git version 2.47.1\n"), Some((2, 47)));
3565 // Apple's git appends a build, which must not stop the parse.
3566 assert_eq!(
3567 parse_git_version("git version 2.39.5 (Apple Git-154)\n"),
3568 Some((2, 39))
3569 );
3570 assert_eq!(parse_git_version(""), None);
3571 assert_eq!(parse_git_version("git version banana"), None);
3572 }
3573
3574 #[tokio::test]
3575 async fn this_machine_reports_what_its_git_can_do() {
3576 // Not an assertion about the answer — a developer may be on an old git — but
3577 // about detection producing one rather than panicking or hanging.
3578 let features = GitFeatures::detect().await;
3579
3580 assert_eq!(
3581 features.merge_tree,
3582 parse_git_version(&git_says(Path::new("."), &["--version"]))
3583 .is_some_and(|version| version >= MERGE_TREE_SINCE)
3584 );
3585 }
3586}