forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.08.8 MiB197fa34Tahinli1 month ago68 commits

pulls.rs1283 lines, 43.2 KiBHistoryRawDownload
1//! Pull request plumbing: PR head refs, merge checks, merge commits and compare-and-swap ref
2//! updates. Every object id is validated as a full hex id and every ref name against a strict
3//! allowlist before it reaches git. User values follow `--end-of-options` where git allows it.
4
5use std::path::Path;
6use std::process::{Output, Stdio};
7
8use tokio::io::AsyncWriteExt;
9
10use crate::browse::{CommitInfo, validate_repo_path};
11use crate::command::{GitCommand, GitEnv, ObjectSource};
12use crate::error::{Error, Result};
13use crate::history::{
14 CommitDiff, DiffLimits, diff_between, empty_tree_for, git, new_commits_with, validate_oid,
15};
16
17/// Outcome of a merge check between a base tip and a head commit.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum MergeCheck {
20 /// The merge would be clean; `tree` is the id of the resulting tree.
21 Clean { tree: String },
22 /// The merge would conflict; `files` are the conflicted paths, deduplicated.
23 Conflict { files: Vec<String> },
24 /// The head is already contained in the base.
25 UpToDate,
26}
27
28/// Author or committer identity for [`commit_tree`]. `time_unix` is written as `<unix> +0000`.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct Signature {
31 pub name: String,
32 pub email: String,
33 pub time_unix: i64,
34}
35
36/// Runs a command without turning a non-zero exit into an error, optionally feeding stdin.
37async fn run_raw(cmd: GitCommand, stdin: Option<&[u8]>) -> Result<Output> {
38 let mut command = cmd.into_tokio();
39 command.stdout(Stdio::piped()).stderr(Stdio::piped());
40 if stdin.is_some() {
41 command.stdin(Stdio::piped());
42 }
43 let mut child = command.spawn()?;
44 if let (Some(data), Some(mut pipe)) = (stdin, child.stdin.take()) {
45 pipe.write_all(data).await?;
46 // `pipe` is dropped here, which closes git's stdin.
47 }
48 Ok(child.wait_with_output().await?)
49}
50
51fn failed(subcommand: &str, out: &Output) -> Error {
52 Error::Failed(format!(
53 "git {subcommand} exited with {}: {}",
54 out.status,
55 String::from_utf8_lossy(&out.stderr).trim()
56 ))
57}
58
59fn stdout_trimmed(out: &Output) -> String {
60 String::from_utf8_lossy(&out.stdout).trim().to_owned()
61}
62
63/// Accepts `refs/heads/<name>` and `refs/pull/<N>/head`, with a conservative character set.
64fn validate_ref(refname: &str) -> Result<()> {
65 let heads_ok = refname
66 .strip_prefix("refs/heads/")
67 .is_some_and(valid_branch_rest);
68 let pull_ok = refname
69 .strip_prefix("refs/pull/")
70 .and_then(|r| r.strip_suffix("/head"))
71 .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()));
72 if heads_ok || pull_ok {
73 Ok(())
74 } else {
75 Err(Error::InvalidInput(format!(
76 "invalid ref name: {refname:?}"
77 )))
78 }
79}
80
81fn valid_branch_rest(rest: &str) -> bool {
82 !rest.is_empty()
83 && !rest.contains("..")
84 && !rest.contains("@{")
85 && !rest.contains("//")
86 && !rest.ends_with(['/', '.'])
87 && !rest.ends_with(".lock")
88 && rest
89 .split('/')
90 .all(|c| !c.is_empty() && !c.starts_with(['.', '-']))
91 && rest
92 .bytes()
93 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'.' | b'_' | b'-' | b'+'))
94}
95
96/// Rejects identity fields git would refuse or misparse.
97fn validate_signature(sig: &Signature) -> Result<()> {
98 let bad = |s: &str| s.is_empty() || s.contains(['<', '>', '\n', '\0']);
99 if bad(&sig.name) || bad(&sig.email) {
100 return Err(Error::InvalidInput("invalid identity name or email".into()));
101 }
102 Ok(())
103}
104
105/// True when both paths name the same repository (equal, or equal after canonicalization).
106fn same_repo(a: &Path, b: &Path) -> bool {
107 if a == b {
108 return true;
109 }
110 match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
111 (Ok(x), Ok(y)) => x == y,
112 _ => false,
113 }
114}
115
116/// Fetches `oid` from `head_repo` into `base_repo`'s object store. The first attempt uses a plain
117/// fetch of the raw id. If git refuses it, the one call is retried with
118/// `uploadpack.allowAnySHA1InWant=true` for the local upload-pack process.
119async fn fetch_object(env: &GitEnv, base_repo: &Path, head_repo: &Path, oid: &str) -> Result<()> {
120 let head_path = head_repo
121 .to_str()
122 .ok_or_else(|| Error::InvalidInput("repo path is not valid UTF-8".into()))?;
123 let build = |allow_any: bool| -> Result<GitCommand> {
124 // `head_repo` is a fork repo from repo_path(), so the local transport is allowed here only.
125 let cmd = git(env, "fetch")
126 .allow_local_transport()
127 .git_dir(base_repo)
128 .arg("--no-tags")
129 .arg("--no-write-fetch-head");
130 let cmd = if allow_any {
131 cmd.env("GIT_CONFIG_COUNT", "2")
132 .env("GIT_CONFIG_KEY_1", "uploadpack.allowAnySHA1InWant")
133 .env("GIT_CONFIG_VALUE_1", "true")
134 } else {
135 cmd
136 };
137 cmd.user_revs(&[head_path, oid])
138 };
139 match build(false)?.status().await {
140 Ok(()) => Ok(()),
141 Err(Error::Failed(_)) => build(true)?.status().await,
142 Err(e) => Err(e),
143 }
144}
145
146/// Points `refs/pull/<number>/head` at `head_oid` in `base_repo`. When the head lives in another
147/// repository, the object is fetched into `base_repo` first.
148pub async fn fetch_into_pull_ref(
149 env: &GitEnv,
150 base_repo: &Path,
151 head_repo: &Path,
152 head_oid: &str,
153 number: i64,
154) -> Result<()> {
155 validate_oid(head_oid)?;
156 if number < 1 {
157 return Err(Error::InvalidInput(format!(
158 "invalid pull number: {number}"
159 )));
160 }
161 let refname = format!("refs/pull/{number}/head");
162 validate_ref(&refname)?;
163 if !same_repo(base_repo, head_repo) {
164 fetch_object(env, base_repo, head_repo, head_oid).await?;
165 }
166 git(env, "update-ref")
167 .git_dir(base_repo)
168 .user_arg(&refname)?
169 .user_arg(head_oid)?
170 .status()
171 .await
172}
173
174/// Best common ancestor of `a` and `b`, or `None` when they share no history.
175pub async fn merge_base(env: &GitEnv, repo: &Path, a: &str, b: &str) -> Result<Option<String>> {
176 merge_base_with(env, repo, ObjectSource::default(), a, b).await
177}
178
179/// [`merge_base`], reading objects missing from `repo` (such as a fork's head commit) from `src`.
180/// Nothing is written to `repo`.
181pub async fn merge_base_with(
182 env: &GitEnv,
183 repo: &Path,
184 src: ObjectSource<'_>,
185 a: &str,
186 b: &str,
187) -> Result<Option<String>> {
188 validate_oid(a)?;
189 validate_oid(b)?;
190 let cmd = git(env, "merge-base")
191 .git_dir(repo)
192 .objects(src)?
193 .user_revs(&[a, b])?;
194 let out = run_raw(cmd, None).await?;
195 match out.status.code() {
196 Some(0) => {
197 let oid = stdout_trimmed(&out);
198 validate_oid(&oid)?;
199 Ok(Some(oid))
200 }
201 Some(1) => Ok(None),
202 _ => Err(failed("merge-base", &out)),
203 }
204}
205
206/// Blob id of `path` in `commit`, or `None` when the path is absent or is not a blob (a tree or a
207/// submodule). `commit` must be a full object id. `path` is a relative `/`-separated repo path.
208pub async fn blob_at(
209 env: &GitEnv,
210 repo: &Path,
211 commit: &str,
212 path: &str,
213) -> Result<Option<String>> {
214 blob_at_with(env, repo, ObjectSource::default(), commit, path).await
215}
216
217/// [`blob_at`], reading objects missing from `repo` (such as a fork's commit) from `src`.
218/// Nothing is written to `repo`.
219pub async fn blob_at_with(
220 env: &GitEnv,
221 repo: &Path,
222 src: ObjectSource<'_>,
223 commit: &str,
224 path: &str,
225) -> Result<Option<String>> {
226 validate_oid(commit)?;
227 validate_blob_path(path)?;
228 // `ls-tree` rather than `rev-parse <commit>:<path>`: the path is a pathspec after `--`, so it is
229 // never read as a revision. `:(literal)` stops globs and magic such as `:x` from matching
230 // other entries. Output is NUL-terminated and unquoted, so any name is safe to parse.
231 let spec = format!(":(literal){path}");
232 let out = git(env, "ls-tree")
233 .git_dir(repo)
234 .objects(src)?
235 .arg("-z")
236 .arg("--full-tree")
237 .user_arg(commit)?
238 .paths(&[spec.as_str()])
239 .output()
240 .await?;
241 // Pathspecs can match more than one entry, so keep only the exact path.
242 let entry = out.split(|&b| b == 0).find_map(|rec| {
243 let text = std::str::from_utf8(rec).ok()?;
244 let (meta, name) = text.split_once('\t')?;
245 if name != path {
246 return None;
247 }
248 let mut fields = meta.split(' ');
249 let _mode = fields.next()?;
250 let kind = fields.next()?;
251 let oid = fields.next()?;
252 Some((kind.to_owned(), oid.to_owned()))
253 });
254 match entry {
255 Some((kind, oid)) if kind == "blob" => {
256 validate_oid(&oid)?;
257 Ok(Some(oid))
258 }
259 _ => Ok(None),
260 }
261}
262
263/// Rules for the path argument of [`blob_at`]: non-empty, relative, no newline, and the segment
264/// rules of [`validate_repo_path`].
265fn validate_blob_path(path: &str) -> Result<()> {
266 if path.is_empty() {
267 return Err(Error::InvalidInput("empty path".into()));
268 }
269 if path.starts_with('/') {
270 return Err(Error::InvalidInput(format!("absolute path: {path:?}")));
271 }
272 if path.contains('\n') {
273 return Err(Error::InvalidInput("path contains newline".into()));
274 }
275 validate_repo_path(path)
276}
277
278/// True when `a` is an ancestor of `b` (or equal to it).
279pub async fn is_ancestor(env: &GitEnv, repo: &Path, a: &str, b: &str) -> Result<bool> {
280 validate_oid(a)?;
281 validate_oid(b)?;
282 let cmd = git(env, "merge-base")
283 .git_dir(repo)
284 .arg("--is-ancestor")
285 .user_revs(&[a, b])?;
286 let out = run_raw(cmd, None).await?;
287 match out.status.code() {
288 Some(0) => Ok(true),
289 Some(1) => Ok(false),
290 _ => Err(failed("merge-base --is-ancestor", &out)),
291 }
292}
293
294/// Checks whether `head` merges cleanly into `base`, without touching any ref.
295pub async fn check_merge(
296 env: &GitEnv,
297 repo: &Path,
298 base_oid: &str,
299 head_oid: &str,
300) -> Result<MergeCheck> {
301 validate_oid(base_oid)?;
302 validate_oid(head_oid)?;
303 if is_ancestor(env, repo, head_oid, base_oid).await? {
304 return Ok(MergeCheck::UpToDate);
305 }
306 let cmd = git(env, "merge-tree")
307 .git_dir(repo)
308 .arg("--write-tree")
309 .arg("--name-only")
310 .arg("--no-messages")
311 .user_revs(&[base_oid, head_oid])?;
312 let out = run_raw(cmd, None).await?;
313 let text = String::from_utf8_lossy(&out.stdout).into_owned();
314 match out.status.code() {
315 Some(0) => {
316 let tree = text.lines().next().unwrap_or_default().trim().to_owned();
317 validate_oid(&tree)?;
318 Ok(MergeCheck::Clean { tree })
319 }
320 Some(1) => {
321 let mut lines = text.lines();
322 let tree = lines.next().unwrap_or_default().trim().to_owned();
323 validate_oid(&tree)?;
324 let mut files: Vec<String> = Vec::new();
325 for line in lines.map(str::trim).filter(|l| !l.is_empty()) {
326 if !files.iter().any(|f| f == line) {
327 files.push(line.to_owned());
328 }
329 }
330 Ok(MergeCheck::Conflict { files })
331 }
332 _ => Err(failed("merge-tree", &out)),
333 }
334}
335
336/// Creates a commit for `tree` with the given parents and returns its id. The message is written
337/// to stdin. Author and committer come from `GIT_AUTHOR_*` and `GIT_COMMITTER_*`.
338pub async fn commit_tree(
339 env: &GitEnv,
340 repo: &Path,
341 tree: &str,
342 parents: &[&str],
343 message: &str,
344 author: &Signature,
345 committer: &Signature,
346) -> Result<String> {
347 validate_oid(tree)?;
348 for p in parents {
349 validate_oid(p)?;
350 }
351 validate_signature(author)?;
352 validate_signature(committer)?;
353 if message.contains('\0') {
354 return Err(Error::InvalidInput("commit message contains NUL".into()));
355 }
356 let mut cmd = git(env, "commit-tree").git_dir(repo);
357 for p in parents {
358 cmd = cmd.arg("-p").user_arg(p)?;
359 }
360 let cmd = cmd
361 .user_revs(&[tree])?
362 .env("GIT_AUTHOR_NAME", author.name.as_str())
363 .env("GIT_AUTHOR_EMAIL", author.email.as_str())
364 .env("GIT_AUTHOR_DATE", format!("{} +0000", author.time_unix))
365 .env("GIT_COMMITTER_NAME", committer.name.as_str())
366 .env("GIT_COMMITTER_EMAIL", committer.email.as_str())
367 .env(
368 "GIT_COMMITTER_DATE",
369 format!("{} +0000", committer.time_unix),
370 );
371 let out = run_raw(cmd, Some(message.as_bytes())).await?;
372 if !out.status.success() {
373 return Err(failed("commit-tree", &out));
374 }
375 let oid = stdout_trimmed(&out);
376 validate_oid(&oid)?;
377 Ok(oid)
378}
379
380/// Moves `refname` from `old` to `new` only if it still points at `old`. A stale `old` gives
381/// `Error::RefMoved`. Use the zero id as `old` to require that the ref does not exist yet.
382pub async fn update_ref_cas(
383 env: &GitEnv,
384 repo: &Path,
385 refname: &str,
386 new: &str,
387 old: &str,
388) -> Result<()> {
389 validate_ref(refname)?;
390 validate_oid(new)?;
391 validate_oid(old)?;
392 let cmd = git(env, "update-ref")
393 .git_dir(repo)
394 .user_arg(refname)?
395 .user_arg(new)?
396 .user_arg(old)?;
397 let out = run_raw(cmd, None).await?;
398 if out.status.success() {
399 return Ok(());
400 }
401 let stderr = String::from_utf8_lossy(&out.stderr);
402 if stderr.contains("but expected") || stderr.contains("unable to resolve reference") {
403 return Err(Error::RefMoved(refname.to_owned()));
404 }
405 Err(failed("update-ref", &out))
406}
407
408/// Deletes `refname` only if it still points at `old`. `git update-ref -d <ref> <old>` checks the
409/// old value itself, so a ref that moved, or one that is already gone, gives `Error::RefMoved`
410/// and is left alone. The zero id is not accepted as `old`: a deletion needs a real value to
411/// compare against.
412pub async fn delete_ref_cas(env: &GitEnv, repo: &Path, refname: &str, old: &str) -> Result<()> {
413 validate_ref(refname)?;
414 validate_oid(old)?;
415 let cmd = git(env, "update-ref")
416 .git_dir(repo)
417 .arg("-d")
418 .user_arg(refname)?
419 .user_arg(old)?;
420 let out = run_raw(cmd, None).await?;
421 if out.status.success() {
422 return Ok(());
423 }
424 let stderr = String::from_utf8_lossy(&out.stderr);
425 if stderr.contains("but expected") || stderr.contains("unable to resolve reference") {
426 return Err(Error::RefMoved(refname.to_owned()));
427 }
428 Err(failed("update-ref", &out))
429}
430
431/// The diff of the head side of a three-dot range: `merge-base(base, head)..head`. Parsed the same
432/// way as [`crate::history::commit_diff`]. With no common ancestor it is the diff from the empty tree.
433pub async fn range_diff_files(
434 env: &GitEnv,
435 repo: &Path,
436 base_oid: &str,
437 head_oid: &str,
438 limits: DiffLimits,
439) -> Result<CommitDiff> {
440 range_diff_files_with(
441 env,
442 repo,
443 ObjectSource::default(),
444 base_oid,
445 head_oid,
446 limits,
447 )
448 .await
449}
450
451/// [`range_diff_files`], reading objects missing from `repo` from `src`. Nothing is written.
452pub async fn range_diff_files_with(
453 env: &GitEnv,
454 repo: &Path,
455 src: ObjectSource<'_>,
456 base_oid: &str,
457 head_oid: &str,
458 limits: DiffLimits,
459) -> Result<CommitDiff> {
460 range_diff_files_ws(env, repo, src, base_oid, head_oid, limits, false).await
461}
462
463/// [`range_diff_files_with`], optionally ignoring whitespace changes.
464pub async fn range_diff_files_ws(
465 env: &GitEnv,
466 repo: &Path,
467 src: ObjectSource<'_>,
468 base_oid: &str,
469 head_oid: &str,
470 limits: DiffLimits,
471 ignore_ws: bool,
472) -> Result<CommitDiff> {
473 validate_oid(base_oid)?;
474 validate_oid(head_oid)?;
475 let from = match merge_base_with(env, repo, src, base_oid, head_oid).await? {
476 Some(b) => b,
477 None => empty_tree_for(head_oid).to_owned(),
478 };
479 diff_between(env, repo, src, &from, head_oid, limits, ignore_ws).await
480}
481
482/// Commits reachable from `head` but not from `base` (`log <head> ^<base>`), oldest first.
483/// At most `max` of the newest such commits are returned.
484pub async fn range_log(
485 env: &GitEnv,
486 repo: &Path,
487 base_oid: &str,
488 head_oid: &str,
489 max: usize,
490) -> Result<Vec<CommitInfo>> {
491 range_log_with(env, repo, ObjectSource::default(), base_oid, head_oid, max).await
492}
493
494/// [`range_log`], reading objects missing from `repo` from `src`. Nothing is written.
495pub async fn range_log_with(
496 env: &GitEnv,
497 repo: &Path,
498 src: ObjectSource<'_>,
499 base_oid: &str,
500 head_oid: &str,
501 max: usize,
502) -> Result<Vec<CommitInfo>> {
503 validate_oid(base_oid)?;
504 validate_oid(head_oid)?;
505 new_commits_with(env, repo, src, Some(base_oid), head_oid, max).await
506}
507
508/// Outcome of replaying head commits onto a base tip.
509#[derive(Debug, Clone, PartialEq, Eq)]
510pub enum RebaseResult {
511 /// The commits replay cleanly; `tip` is the new head (the base tip when every commit was
512 /// already applied) and `count` the number of commits created.
513 Clean { tip: String, count: usize },
514 /// A commit does not apply; `commit` is its id and `files` the conflicted paths.
515 Conflict { commit: String, files: Vec<String> },
516}
517
518/// Replays the commits reachable from `head_oid` but not from `base_oid` onto `base_oid`, oldest
519/// first, keeping each author and message. The committer is `committer`. Merge commits in the
520/// range are skipped and a commit whose changes the base already has is dropped. Nothing is
521/// written but objects: no ref moves.
522pub async fn rebase_commits(
523 env: &GitEnv,
524 repo: &Path,
525 base_oid: &str,
526 head_oid: &str,
527 committer: &Signature,
528) -> Result<RebaseResult> {
529 validate_oid(base_oid)?;
530 validate_oid(head_oid)?;
531 let negated = format!("^{base_oid}");
532 let cmd = git(env, "rev-list")
533 .git_dir(repo)
534 .arg("--reverse")
535 .arg("--topo-order")
536 .arg("--no-merges")
537 .user_revs(&[head_oid, negated.as_str()])?;
538 let out = run_raw(cmd, None).await?;
539 if !out.status.success() {
540 return Err(failed("rev-list", &out));
541 }
542 let commits: Vec<String> = String::from_utf8_lossy(&out.stdout)
543 .lines()
544 .map(str::to_owned)
545 .collect();
546 let mut tip = base_oid.to_owned();
547 let mut count = 0usize;
548 for commit in commits {
549 validate_oid(&commit)?;
550 let cmd = git(env, "log")
551 .git_dir(repo)
552 .arg("-1")
553 .arg("--format=%P%x00%an%x00%ae%x00%at%x00%B")
554 .user_revs(&[commit.as_str()])?;
555 let out = run_raw(cmd, None).await?;
556 if !out.status.success() {
557 return Err(failed("log", &out));
558 }
559 let text = String::from_utf8_lossy(&out.stdout).into_owned();
560 let mut parts = text.splitn(5, '\0');
561 let parents = parts.next().unwrap_or_default();
562 let name = parts.next().unwrap_or_default().to_owned();
563 let email = parts.next().unwrap_or_default().to_owned();
564 let time_unix = parts
565 .next()
566 .and_then(|t| t.trim().parse::<i64>().ok())
567 .unwrap_or(committer.time_unix);
568 let message = parts.next().unwrap_or_default().to_owned();
569 let Some(parent) = parents.split_whitespace().next() else {
570 return Err(Error::InvalidInput(
571 "cannot rebase a root commit onto the base".into(),
572 ));
573 };
574 validate_oid(parent)?;
575 let cmd = git(env, "merge-tree")
576 .git_dir(repo)
577 .arg("--write-tree")
578 .arg("--name-only")
579 .arg("--no-messages")
580 .user_opt("--merge-base", parent)?
581 .user_revs(&[tip.as_str(), commit.as_str()])?;
582 let out = run_raw(cmd, None).await?;
583 let text = String::from_utf8_lossy(&out.stdout).into_owned();
584 let tree = match out.status.code() {
585 Some(0) => text.lines().next().unwrap_or_default().trim().to_owned(),
586 Some(1) => {
587 let mut files: Vec<String> = Vec::new();
588 for line in text
589 .lines()
590 .skip(1)
591 .map(str::trim)
592 .filter(|l| !l.is_empty())
593 {
594 if !files.iter().any(|f| f == line) {
595 files.push(line.to_owned());
596 }
597 }
598 return Ok(RebaseResult::Conflict { commit, files });
599 }
600 _ => return Err(failed("merge-tree", &out)),
601 };
602 validate_oid(&tree)?;
603 let tip_tree = format!("{tip}^{{tree}}");
604 let cmd = git(env, "rev-parse")
605 .git_dir(repo)
606 .arg("--verify")
607 .user_revs(&[tip_tree.as_str()])?;
608 let out = run_raw(cmd, None).await?;
609 if !out.status.success() {
610 return Err(failed("rev-parse", &out));
611 }
612 if stdout_trimmed(&out) == tree {
613 continue;
614 }
615 let author = Signature {
616 name,
617 email,
618 time_unix,
619 };
620 tip = commit_tree(
621 env,
622 repo,
623 &tree,
624 &[tip.as_str()],
625 message.trim_end_matches('\n'),
626 &author,
627 committer,
628 )
629 .await?;
630 count += 1;
631 }
632 Ok(RebaseResult::Clean { tip, count })
633}
634
635#[cfg(test)]
636mod tests {
637 use super::*;
638 use crate::history::DiffStatus;
639 use std::path::PathBuf;
640 use std::process::Command;
641
642 const LIMITS: DiffLimits = DiffLimits {
643 max_files: 100,
644 max_lines_per_file: 1000,
645 max_total_lines: 10_000,
646 };
647
648 /// Runs git in `dir` with a cleared environment and fixed identities.
649 fn git_in(dir: &Path, home: &Path, args: &[&str]) -> String {
650 let out = Command::new("/usr/bin/git")
651 .arg("-C")
652 .arg(dir)
653 .args(["-c", "commit.gpgsign=false"])
654 .args(args)
655 .env_clear()
656 .env("PATH", "/usr/bin:/bin")
657 .env("HOME", home)
658 .env("GIT_CONFIG_NOSYSTEM", "1")
659 .env("GIT_CONFIG_GLOBAL", "/dev/null")
660 .env("GIT_AUTHOR_NAME", "Tester")
661 .env("GIT_AUTHOR_EMAIL", "tester@example.com")
662 .env("GIT_COMMITTER_NAME", "Tester")
663 .env("GIT_COMMITTER_EMAIL", "tester@example.com")
664 .output()
665 .expect("git runs");
666 assert!(
667 out.status.success(),
668 "git {args:?} failed: {}",
669 String::from_utf8_lossy(&out.stderr)
670 );
671 String::from_utf8_lossy(&out.stdout).trim().to_owned()
672 }
673
674 struct Sandbox {
675 _dir: tempfile::TempDir,
676 home: PathBuf,
677 }
678
679 impl Sandbox {
680 /// The data dir holds the real managed gitconfig, as written at boot, so these tests see
681 /// the same `protocol.file.allow = never` setting that the server runs with.
682 fn new() -> Self {
683 let dir = tempfile::tempdir().expect("tempdir");
684 let home = dir.path().join("home");
685 std::fs::create_dir(&home).expect("home dir");
686 crate::setup::write_managed_gitconfig(&home).expect("managed gitconfig");
687 Self { _dir: dir, home }
688 }
689
690 fn env(&self) -> GitEnv {
691 GitEnv {
692 git_bin: PathBuf::from("/usr/bin/git"),
693 data_dir: self.home.clone(),
694 }
695 }
696
697 /// A non-bare repo named `name` with `main` checked out.
698 fn repo(&self, name: &str) -> Work {
699 let work = self._dir.path().join(name);
700 std::fs::create_dir(&work).expect("work dir");
701 git_in(&work, &self.home, &["init", "-q", "-b", "main"]);
702 Work {
703 work,
704 home: self.home.clone(),
705 }
706 }
707 }
708
709 struct Work {
710 work: PathBuf,
711 home: PathBuf,
712 }
713
714 impl Work {
715 fn git_dir(&self) -> PathBuf {
716 self.work.join(".git")
717 }
718
719 fn git(&self, args: &[&str]) -> String {
720 git_in(&self.work, &self.home, args)
721 }
722
723 fn write(&self, name: &str, content: &str) {
724 std::fs::write(self.work.join(name), content).expect("write file");
725 }
726
727 /// Stages everything, commits, and returns the new full id.
728 fn commit(&self, msg: &str) -> String {
729 self.git(&["add", "-A"]);
730 self.git(&["commit", "-q", "--allow-empty", "-m", msg]);
731 self.git(&["rev-parse", "HEAD"])
732 }
733 }
734
735 #[tokio::test]
736 async fn clean_merge_builds_merge_commit_with_author() {
737 let sb = Sandbox::new();
738 let env = sb.env();
739 let w = sb.repo("repo");
740 w.write("a.txt", "1\n");
741 let c0 = w.commit("c0");
742 w.git(&["switch", "-q", "-c", "feature"]);
743 w.write("b.txt", "feature\n");
744 let head = w.commit("feature work");
745 w.git(&["switch", "-q", "main"]);
746 w.write("c.txt", "main\n");
747 let base = w.commit("main work");
748 let gd = w.git_dir();
749
750 assert_eq!(
751 merge_base(&env, &gd, &base, &head)
752 .await
753 .expect("merge-base"),
754 Some(c0)
755 );
756 let tree = match check_merge(&env, &gd, &base, &head).await.expect("check") {
757 MergeCheck::Clean { tree } => tree,
758 other => panic!("expected clean merge, got {other:?}"),
759 };
760 assert_eq!(tree.len(), 40);
761
762 let author = Signature {
763 name: "Tahinli Author".into(),
764 email: "tahinli@example.com".into(),
765 time_unix: 1_700_000_000,
766 };
767 let committer = Signature {
768 name: "Carol Committer".into(),
769 email: "carol@example.com".into(),
770 time_unix: 1_700_000_100,
771 };
772 let merge = commit_tree(
773 &env,
774 &gd,
775 &tree,
776 &[base.as_str(), head.as_str()],
777 "Merge pull request #1 from owner/feature\n\nFeature",
778 &author,
779 &committer,
780 )
781 .await
782 .expect("commit-tree");
783
784 assert_eq!(
785 w.git(&["rev-list", "--parents", "-n1", merge.as_str()]),
786 format!("{merge} {base} {head}")
787 );
788 assert_eq!(
789 w.git(&[
790 "log",
791 "-1",
792 "--format=%T|%an|%ae|%at|%cn|%ce|%ct|%s",
793 merge.as_str()
794 ]),
795 format!(
796 "{tree}|Tahinli Author|tahinli@example.com|1700000000|Carol Committer|carol@example.com|1700000100|Merge pull request #1 from owner/feature"
797 )
798 );
799 assert!(
800 is_ancestor(&env, &gd, &head, &merge)
801 .await
802 .expect("ancestor")
803 );
804 }
805
806 #[tokio::test]
807 async fn conflicting_merge_lists_the_file() {
808 let sb = Sandbox::new();
809 let env = sb.env();
810 let w = sb.repo("repo");
811 w.write("f.txt", "base\n");
812 w.commit("c0");
813 w.git(&["switch", "-q", "-c", "feature"]);
814 w.write("f.txt", "head\n");
815 let head = w.commit("feature edits f");
816 w.git(&["switch", "-q", "main"]);
817 w.write("f.txt", "other\n");
818 let base = w.commit("main edits f");
819
820 let check = check_merge(&env, &w.git_dir(), &base, &head)
821 .await
822 .expect("check");
823 assert_eq!(
824 check,
825 MergeCheck::Conflict {
826 files: vec!["f.txt".to_owned()]
827 }
828 );
829 }
830
831 #[tokio::test]
832 async fn head_contained_in_base_is_up_to_date() {
833 let sb = Sandbox::new();
834 let env = sb.env();
835 let w = sb.repo("repo");
836 w.write("a.txt", "1\n");
837 let c0 = w.commit("c0");
838 w.write("a.txt", "2\n");
839 let c1 = w.commit("c1");
840 let gd = w.git_dir();
841
842 assert_eq!(
843 check_merge(&env, &gd, &c1, &c0).await.expect("check"),
844 MergeCheck::UpToDate
845 );
846 assert!(is_ancestor(&env, &gd, &c0, &c1).await.expect("ancestor"));
847 assert!(!is_ancestor(&env, &gd, &c1, &c0).await.expect("ancestor"));
848 }
849
850 #[tokio::test]
851 async fn update_ref_cas_succeeds_then_refuses_stale_old() {
852 let sb = Sandbox::new();
853 let env = sb.env();
854 let w = sb.repo("repo");
855 w.write("a.txt", "1\n");
856 let c0 = w.commit("c0");
857 w.write("a.txt", "2\n");
858 let c1 = w.commit("c1");
859 w.write("a.txt", "3\n");
860 let c2 = w.commit("c2");
861 let gd = w.git_dir();
862
863 // The base is at c2, so a CAS expecting c0 must fail and leave the ref alone.
864 let stale = update_ref_cas(&env, &gd, "refs/heads/main", &c1, &c0).await;
865 assert!(matches!(stale, Err(Error::RefMoved(_))), "{stale:?}");
866 assert_eq!(w.git(&["rev-parse", "main"]), c2);
867
868 update_ref_cas(&env, &gd, "refs/heads/main", &c1, &c2)
869 .await
870 .expect("cas with current old");
871 assert_eq!(w.git(&["rev-parse", "main"]), c1);
872 }
873
874 #[tokio::test]
875 async fn delete_ref_cas_deletes_only_at_expected_value() {
876 let sb = Sandbox::new();
877 let env = sb.env();
878 let w = sb.repo("repo");
879 w.write("a.txt", "1\n");
880 let c0 = w.commit("c0");
881 w.git(&["branch", "topic"]);
882 w.write("a.txt", "2\n");
883 let c1 = w.commit("c1");
884 let gd = w.git_dir();
885
886 // topic is at c0, so a deletion expecting c1 must fail and leave the ref alone.
887 let stale = delete_ref_cas(&env, &gd, "refs/heads/topic", &c1).await;
888 assert!(matches!(stale, Err(Error::RefMoved(_))), "{stale:?}");
889 assert_eq!(w.git(&["rev-parse", "topic"]), c0);
890
891 delete_ref_cas(&env, &gd, "refs/heads/topic", &c0)
892 .await
893 .expect("delete at current value");
894 let gone = w.git(&["for-each-ref", "refs/heads/topic"]);
895 assert!(gone.is_empty(), "{gone:?}");
896
897 // Deleting a ref that is already gone is a refusal, not a silent success.
898 let missing = delete_ref_cas(&env, &gd, "refs/heads/topic", &c0).await;
899 assert!(matches!(missing, Err(Error::RefMoved(_))), "{missing:?}");
900 }
901
902 #[tokio::test]
903 async fn range_log_returns_head_side_commits_oldest_first() {
904 let sb = Sandbox::new();
905 let env = sb.env();
906 let w = sb.repo("repo");
907 w.write("a.txt", "1\n");
908 w.commit("c0");
909 w.git(&["switch", "-q", "-c", "feature"]);
910 w.write("f1.txt", "1\n");
911 w.commit("f1");
912 w.write("f2.txt", "1\n");
913 let head = w.commit("f2");
914 w.git(&["switch", "-q", "main"]);
915 w.write("m.txt", "1\n");
916 let base = w.commit("m1");
917
918 let log = range_log(&env, &w.git_dir(), &base, &head, 100)
919 .await
920 .expect("range log");
921 let summaries: Vec<&str> = log.iter().map(|c| c.summary.as_str()).collect();
922 assert_eq!(summaries, vec!["f1", "f2"]);
923 }
924
925 #[tokio::test]
926 async fn range_diff_shows_only_head_side_after_base_moved() {
927 let sb = Sandbox::new();
928 let env = sb.env();
929 let w = sb.repo("repo");
930 w.write("a.txt", "1\n");
931 w.commit("c0");
932 w.git(&["switch", "-q", "-c", "feature"]);
933 w.write("feat.txt", "feature\n");
934 let head = w.commit("feature");
935 w.git(&["switch", "-q", "main"]);
936 w.write("base.txt", "base\n");
937 let base = w.commit("base moves");
938
939 let diff = range_diff_files(&env, &w.git_dir(), &base, &head, LIMITS)
940 .await
941 .expect("range diff");
942 let paths: Vec<String> = diff
943 .files
944 .iter()
945 .map(|f| f.new_path.clone().unwrap_or_default())
946 .collect();
947 assert_eq!(paths, vec!["feat.txt".to_owned()]);
948 assert_eq!(diff.files[0].status, DiffStatus::Added);
949 }
950
951 /// True when the repo at `git_dir` has `oid` in its object store.
952 fn has_object(git_dir: &Path, oid: &str) -> bool {
953 Command::new("/usr/bin/git")
954 .arg("--git-dir")
955 .arg(git_dir)
956 .args(["cat-file", "-e", oid])
957 .env_clear()
958 .env("PATH", "/usr/bin:/bin")
959 .env("GIT_CONFIG_NOSYSTEM", "1")
960 .env("GIT_CONFIG_GLOBAL", "/dev/null")
961 .status()
962 .expect("git runs")
963 .success()
964 }
965
966 #[tokio::test]
967 async fn alternate_objects_read_fork_commit_without_copying_it() {
968 let sb = Sandbox::new();
969 let env = sb.env();
970 let base = sb.repo("base");
971 base.write("a.txt", "1\n");
972 let base_tip = base.commit("base");
973 // The fork is a clone, so both histories share `base_tip`.
974 let fork_dir = sb._dir.path().join("fork");
975 git_in(
976 sb._dir.path(),
977 &sb.home,
978 &["clone", "-q", base.work.to_str().expect("utf8"), "fork"],
979 );
980 let fork = Work {
981 work: fork_dir,
982 home: sb.home.clone(),
983 };
984 fork.write("b.txt", "fork\n");
985 let fork_head = fork.commit("fork work");
986 let base_git = base.git_dir();
987 let fork_objects = fork.git_dir().join("objects");
988 assert!(!has_object(&base_git, &fork_head));
989
990 // Without the alternate the base cannot see the fork's commit.
991 assert!(
992 range_log(&env, &base_git, &base_tip, &fork_head, 10)
993 .await
994 .is_err()
995 );
996
997 let src = ObjectSource {
998 extra: Some(fork_objects.as_path()),
999 };
1000 let log = range_log_with(&env, &base_git, src, &base_tip, &fork_head, 10)
1001 .await
1002 .expect("range log through alternate");
1003 let summaries: Vec<&str> = log.iter().map(|c| c.summary.as_str()).collect();
1004 assert_eq!(summaries, vec!["fork work"]);
1005
1006 let merge = merge_base_with(&env, &base_git, src, &base_tip, &fork_head)
1007 .await
1008 .expect("merge base through alternate");
1009 assert_eq!(merge.as_deref(), Some(base_tip.as_str()));
1010
1011 let diff = range_diff_files_with(&env, &base_git, src, &base_tip, &fork_head, LIMITS)
1012 .await
1013 .expect("range diff through alternate");
1014 let paths: Vec<String> = diff
1015 .files
1016 .iter()
1017 .map(|f| f.new_path.clone().unwrap_or_default())
1018 .collect();
1019 assert_eq!(paths, vec!["b.txt".to_owned()]);
1020
1021 // Reading through the alternate wrote nothing into the base repo.
1022 assert!(!has_object(&base_git, &fork_head));
1023 }
1024
1025 #[tokio::test]
1026 async fn fetch_into_pull_ref_from_fork_and_same_repo() {
1027 let sb = Sandbox::new();
1028 let env = sb.env();
1029 let base = sb.repo("base");
1030 base.write("a.txt", "1\n");
1031 let base_tip = base.commit("base");
1032 let fork = sb.repo("fork");
1033 fork.write("x.txt", "fork\n");
1034 let fork_tip = fork.commit("fork work");
1035
1036 fetch_into_pull_ref(&env, &base.git_dir(), &fork.git_dir(), &fork_tip, 1)
1037 .await
1038 .expect("fork fetch");
1039 assert_eq!(base.git(&["rev-parse", "refs/pull/1/head"]), fork_tip);
1040
1041 fetch_into_pull_ref(&env, &base.git_dir(), &base.git_dir(), &base_tip, 2)
1042 .await
1043 .expect("same-repo update");
1044 assert_eq!(base.git(&["rev-parse", "refs/pull/2/head"]), base_tip);
1045 }
1046
1047 #[tokio::test]
1048 async fn fetch_into_pull_ref_handles_unadvertised_fork_commit() {
1049 let sb = Sandbox::new();
1050 let env = sb.env();
1051 let base = sb.repo("base");
1052 base.write("a.txt", "1\n");
1053 base.commit("base");
1054 let fork = sb.repo("fork");
1055 fork.write("x.txt", "fork\n");
1056 fork.commit("main work");
1057 fork.git(&["switch", "-q", "-c", "topic"]);
1058 fork.write("y.txt", "topic\n");
1059 let topic_tip = fork.commit("topic work");
1060 fork.git(&["switch", "-q", "main"]);
1061 fork.git(&["branch", "-q", "-D", "topic"]);
1062
1063 fetch_into_pull_ref(&env, &base.git_dir(), &fork.git_dir(), &topic_tip, 3)
1064 .await
1065 .expect("unadvertised fetch");
1066 assert_eq!(base.git(&["rev-parse", "refs/pull/3/head"]), topic_tip);
1067 }
1068
1069 #[tokio::test]
1070 async fn blob_at_returns_blob_ids_for_files_only() {
1071 let sb = Sandbox::new();
1072 let env = sb.env();
1073 let w = sb.repo("repo");
1074 let gd = w.git_dir();
1075 w.write("a.txt", "1\n");
1076 std::fs::create_dir(w.work.join("dir")).expect("dir");
1077 w.write("dir/x.txt", "x\n");
1078 let c0 = w.commit("c0");
1079 let a0 = w.git(&["hash-object", "a.txt"]);
1080
1081 assert_eq!(
1082 blob_at(&env, &gd, &c0, "a.txt").await.expect("ok"),
1083 Some(a0.clone())
1084 );
1085 assert_eq!(
1086 blob_at(&env, &gd, &c0, "dir/x.txt").await.expect("ok"),
1087 Some(w.git(&["hash-object", "dir/x.txt"]))
1088 );
1089 assert_eq!(
1090 blob_at(&env, &gd, &c0, "missing.txt").await.expect("ok"),
1091 None
1092 );
1093 assert_eq!(blob_at(&env, &gd, &c0, "dir").await.expect("ok"), None);
1094
1095 w.write("a.txt", "2\n");
1096 let c1 = w.commit("c1");
1097 let a1 = blob_at(&env, &gd, &c1, "a.txt").await.expect("ok");
1098 assert_eq!(a1, Some(w.git(&["hash-object", "a.txt"])));
1099 assert_ne!(a1, Some(a0));
1100 // The older commit still maps to the older blob.
1101 let old_spec = format!("{c0}:a.txt");
1102 assert_eq!(
1103 blob_at(&env, &gd, &c0, "a.txt").await.expect("ok"),
1104 Some(w.git(&["rev-parse", old_spec.as_str()]))
1105 );
1106 }
1107
1108 #[tokio::test]
1109 async fn blob_at_handles_literal_special_and_unicode_names() {
1110 let sb = Sandbox::new();
1111 let env = sb.env();
1112 let w = sb.repo("repo");
1113 let gd = w.git_dir();
1114 std::fs::create_dir(w.work.join("dir with space")).expect("dir");
1115 w.write("dir with space/füß ü.txt", "u\n");
1116 w.write("star*", "s\n");
1117 w.write(":colon", "c\n");
1118 w.write("other", "o\n");
1119 let c0 = w.commit("c0");
1120
1121 assert_eq!(
1122 blob_at(&env, &gd, &c0, "dir with space/füß ü.txt")
1123 .await
1124 .expect("ok"),
1125 Some(w.git(&["hash-object", "dir with space/füß ü.txt"]))
1126 );
1127 assert_eq!(
1128 blob_at(&env, &gd, &c0, "star*").await.expect("ok"),
1129 Some(w.git(&["hash-object", "star*"]))
1130 );
1131 assert_eq!(
1132 blob_at(&env, &gd, &c0, ":colon").await.expect("ok"),
1133 Some(w.git(&["hash-object", ":colon"]))
1134 );
1135 // A glob must not match other entries.
1136 assert_eq!(blob_at(&env, &gd, &c0, "st*").await.expect("ok"), None);
1137 assert_eq!(blob_at(&env, &gd, &c0, "*").await.expect("ok"), None);
1138 }
1139
1140 #[tokio::test]
1141 async fn blob_at_rejects_invalid_paths_and_commits() {
1142 let sb = Sandbox::new();
1143 let env = sb.env();
1144 let w = sb.repo("repo");
1145 w.write("a.txt", "1\n");
1146 let c0 = w.commit("c0");
1147 let gd = w.git_dir();
1148
1149 for bad in [
1150 "", "../x", "a/../x", "/a", "a//b", "a/", "./a", "a/./b", "a\nb", "a\0b",
1151 ] {
1152 let r = blob_at(&env, &gd, &c0, bad).await;
1153 assert!(matches!(r, Err(Error::InvalidInput(_))), "{bad:?}: {r:?}");
1154 }
1155 let r = blob_at(&env, &gd, "not-hex", "a.txt").await;
1156 assert!(matches!(r, Err(Error::InvalidInput(_))), "{r:?}");
1157 }
1158
1159 #[tokio::test]
1160 async fn invalid_inputs_are_rejected_before_git() {
1161 let sb = Sandbox::new();
1162 let env = sb.env();
1163 let w = sb.repo("repo");
1164 w.write("a.txt", "1\n");
1165 let c0 = w.commit("c0");
1166 let gd = w.git_dir();
1167 let short = "a".repeat(39);
1168
1169 let bad_oid = |r: Result<()>| assert!(matches!(r, Err(Error::InvalidInput(_))), "{r:?}");
1170 bad_oid(check_merge(&env, &gd, "not-hex", &c0).await.map(|_| ()));
1171 bad_oid(merge_base(&env, &gd, &short, &c0).await.map(|_| ()));
1172 bad_oid(
1173 commit_tree(
1174 &env,
1175 &gd,
1176 "--output=/tmp/x",
1177 &[],
1178 "m",
1179 &Signature {
1180 name: "a".into(),
1181 email: "a@example.com".into(),
1182 time_unix: 0,
1183 },
1184 &Signature {
1185 name: "a".into(),
1186 email: "a@example.com".into(),
1187 time_unix: 0,
1188 },
1189 )
1190 .await
1191 .map(|_| ()),
1192 );
1193 bad_oid(update_ref_cas(&env, &gd, "refs/heads/main", "HEAD", &c0).await);
1194 bad_oid(update_ref_cas(&env, &gd, "refs/heads/../x", &c0, &c0).await);
1195 bad_oid(update_ref_cas(&env, &gd, "refs/heads/-x", &c0, &c0).await);
1196 bad_oid(fetch_into_pull_ref(&env, &gd, &gd, "--upload-pack=x", 1).await);
1197 bad_oid(fetch_into_pull_ref(&env, &gd, &gd, &c0, 0).await);
1198 bad_oid(range_log(&env, &gd, "main", &c0, 10).await.map(|_| ()));
1199 bad_oid(
1200 range_diff_files(&env, &gd, &c0, &short, LIMITS)
1201 .await
1202 .map(|_| ()),
1203 );
1204 let bad_name = Signature {
1205 name: "Eve <eve@example.com>".into(),
1206 email: "eve@example.com".into(),
1207 time_unix: 0,
1208 };
1209 bad_oid(
1210 commit_tree(&env, &gd, &c0, &[], "m", &bad_name, &bad_name)
1211 .await
1212 .map(|_| ()),
1213 );
1214 }
1215
1216 #[tokio::test]
1217 async fn rebase_replays_commits_keeping_authors() {
1218 let sb = Sandbox::new();
1219 let env = sb.env();
1220 let w = sb.repo("repo");
1221 w.write("a.txt", "1\n");
1222 w.commit("c0");
1223 w.git(&["switch", "-q", "-c", "feature"]);
1224 w.write("b.txt", "one\n");
1225 w.commit("first");
1226 w.write("b.txt", "two\n");
1227 let head = w.commit("second");
1228 w.git(&["switch", "-q", "main"]);
1229 w.write("c.txt", "main\n");
1230 let base = w.commit("main work");
1231 let gd = w.git_dir();
1232 let committer = Signature {
1233 name: "tahinli".into(),
1234 email: "tahinli@example.com".into(),
1235 time_unix: 1_700_000_000,
1236 };
1237 let (tip, count) = match rebase_commits(&env, &gd, &base, &head, &committer)
1238 .await
1239 .expect("rebase")
1240 {
1241 RebaseResult::Clean { tip, count } => (tip, count),
1242 other => panic!("expected clean, got {other:?}"),
1243 };
1244 assert_eq!(count, 2);
1245 assert_eq!(w.git(&["rev-parse", &format!("{tip}~2")]), base);
1246 assert_eq!(
1247 w.git(&["log", "-1", "--format=%an|%cn|%s", &tip]),
1248 "Tester|tahinli|second"
1249 );
1250 assert_eq!(w.git(&["show", &format!("{tip}:b.txt")]), "two");
1251 assert_eq!(w.git(&["show", &format!("{tip}:c.txt")]), "main");
1252 }
1253
1254 #[tokio::test]
1255 async fn rebase_reports_conflicts() {
1256 let sb = Sandbox::new();
1257 let env = sb.env();
1258 let w = sb.repo("repo");
1259 w.write("a.txt", "1\n");
1260 w.commit("c0");
1261 w.git(&["switch", "-q", "-c", "feature"]);
1262 w.write("a.txt", "feature\n");
1263 let head = w.commit("feature edit");
1264 w.git(&["switch", "-q", "main"]);
1265 w.write("a.txt", "main\n");
1266 let base = w.commit("main edit");
1267 let committer = Signature {
1268 name: "tahinli".into(),
1269 email: "tahinli@example.com".into(),
1270 time_unix: 1_700_000_000,
1271 };
1272 match rebase_commits(&env, &w.git_dir(), &base, &head, &committer)
1273 .await
1274 .expect("rebase")
1275 {
1276 RebaseResult::Conflict { commit, files } => {
1277 assert_eq!(commit, head);
1278 assert_eq!(files, vec!["a.txt".to_owned()]);
1279 }
1280 other => panic!("expected conflict, got {other:?}"),
1281 }
1282 }
1283}