forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.08.8 MiBb00f3f4Tahinli1 month ago147 commits

pulls.rs1413 lines, 47.5 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/// Points `refname` at `new`, whatever it pointed at before. Used for the temporary refs that name
409/// a merge queue candidate; a rebuild replaces them.
410pub async fn set_ref(env: &GitEnv, repo: &Path, refname: &str, new: &str) -> Result<()> {
411 // Only the merge queue's temporary namespace is writable here, besides the usual checks.
412 let queue_ok = refname
413 .strip_prefix("refs/forge/merge-queue/")
414 .is_some_and(valid_branch_rest);
415 if !queue_ok {
416 return Err(Error::InvalidInput(format!(
417 "invalid ref name: {refname:?}"
418 )));
419 }
420 validate_oid(new)?;
421 let cmd = git(env, "update-ref")
422 .git_dir(repo)
423 .user_arg(refname)?
424 .user_arg(new)?;
425 let out = run_raw(cmd, None).await?;
426 if out.status.success() {
427 return Ok(());
428 }
429 Err(failed("update-ref", &out))
430}
431
432/// Deletes `refname` only if it still points at `old`. `git update-ref -d <ref> <old>` checks the
433/// old value itself, so a ref that moved, or one that is already gone, gives `Error::RefMoved`
434/// and is left alone. The zero id is not accepted as `old`: a deletion needs a real value to
435/// compare against.
436pub async fn delete_ref_cas(env: &GitEnv, repo: &Path, refname: &str, old: &str) -> Result<()> {
437 validate_ref(refname)?;
438 validate_oid(old)?;
439 let cmd = git(env, "update-ref")
440 .git_dir(repo)
441 .arg("-d")
442 .user_arg(refname)?
443 .user_arg(old)?;
444 let out = run_raw(cmd, None).await?;
445 if out.status.success() {
446 return Ok(());
447 }
448 let stderr = String::from_utf8_lossy(&out.stderr);
449 if stderr.contains("but expected") || stderr.contains("unable to resolve reference") {
450 return Err(Error::RefMoved(refname.to_owned()));
451 }
452 Err(failed("update-ref", &out))
453}
454
455/// The diff of the head side of a three-dot range: `merge-base(base, head)..head`. Parsed the same
456/// way as [`crate::history::commit_diff`]. With no common ancestor it is the diff from the empty tree.
457pub async fn range_diff_files(
458 env: &GitEnv,
459 repo: &Path,
460 base_oid: &str,
461 head_oid: &str,
462 limits: DiffLimits,
463) -> Result<CommitDiff> {
464 range_diff_files_with(
465 env,
466 repo,
467 ObjectSource::default(),
468 base_oid,
469 head_oid,
470 limits,
471 )
472 .await
473}
474
475/// [`range_diff_files`], reading objects missing from `repo` from `src`. Nothing is written.
476pub async fn range_diff_files_with(
477 env: &GitEnv,
478 repo: &Path,
479 src: ObjectSource<'_>,
480 base_oid: &str,
481 head_oid: &str,
482 limits: DiffLimits,
483) -> Result<CommitDiff> {
484 range_diff_files_ws(env, repo, src, base_oid, head_oid, limits, false).await
485}
486
487/// [`range_diff_files_with`], optionally ignoring whitespace changes.
488pub async fn range_diff_files_ws(
489 env: &GitEnv,
490 repo: &Path,
491 src: ObjectSource<'_>,
492 base_oid: &str,
493 head_oid: &str,
494 limits: DiffLimits,
495 ignore_ws: bool,
496) -> Result<CommitDiff> {
497 validate_oid(base_oid)?;
498 validate_oid(head_oid)?;
499 let from = match merge_base_with(env, repo, src, base_oid, head_oid).await? {
500 Some(b) => b,
501 None => empty_tree_for(head_oid).to_owned(),
502 };
503 diff_between(env, repo, src, &from, head_oid, limits, ignore_ws).await
504}
505
506/// Commits reachable from `head` but not from `base` (`log <head> ^<base>`), oldest first.
507/// At most `max` of the newest such commits are returned.
508pub async fn range_log(
509 env: &GitEnv,
510 repo: &Path,
511 base_oid: &str,
512 head_oid: &str,
513 max: usize,
514) -> Result<Vec<CommitInfo>> {
515 range_log_with(env, repo, ObjectSource::default(), base_oid, head_oid, max).await
516}
517
518/// [`range_log`], reading objects missing from `repo` from `src`. Nothing is written.
519pub async fn range_log_with(
520 env: &GitEnv,
521 repo: &Path,
522 src: ObjectSource<'_>,
523 base_oid: &str,
524 head_oid: &str,
525 max: usize,
526) -> Result<Vec<CommitInfo>> {
527 validate_oid(base_oid)?;
528 validate_oid(head_oid)?;
529 new_commits_with(env, repo, src, Some(base_oid), head_oid, max).await
530}
531
532/// Outcome of replaying head commits onto a base tip.
533#[derive(Debug, Clone, PartialEq, Eq)]
534pub enum RebaseResult {
535 /// The commits replay cleanly; `tip` is the new head (the base tip when every commit was
536 /// already applied) and `count` the number of commits created.
537 Clean { tip: String, count: usize },
538 /// A commit does not apply; `commit` is its id and `files` the conflicted paths.
539 Conflict { commit: String, files: Vec<String> },
540}
541
542/// Replays the commits reachable from `head_oid` but not from `base_oid` onto `base_oid`, oldest
543/// first, keeping each author and message. The committer is `committer`. Merge commits in the
544/// range are skipped and a commit whose changes the base already has is dropped. Nothing is
545/// written but objects: no ref moves.
546pub async fn rebase_commits(
547 env: &GitEnv,
548 repo: &Path,
549 base_oid: &str,
550 head_oid: &str,
551 committer: &Signature,
552) -> Result<RebaseResult> {
553 validate_oid(base_oid)?;
554 validate_oid(head_oid)?;
555 let negated = format!("^{base_oid}");
556 let cmd = git(env, "rev-list")
557 .git_dir(repo)
558 .arg("--reverse")
559 .arg("--topo-order")
560 .arg("--no-merges")
561 .user_revs(&[head_oid, negated.as_str()])?;
562 let out = run_raw(cmd, None).await?;
563 if !out.status.success() {
564 return Err(failed("rev-list", &out));
565 }
566 let commits: Vec<String> = String::from_utf8_lossy(&out.stdout)
567 .lines()
568 .map(str::to_owned)
569 .collect();
570 let mut tip = base_oid.to_owned();
571 let mut count = 0usize;
572 for commit in commits {
573 validate_oid(&commit)?;
574 let cmd = git(env, "log")
575 .git_dir(repo)
576 .arg("-1")
577 .arg("--format=%P%x00%an%x00%ae%x00%at%x00%B")
578 .user_revs(&[commit.as_str()])?;
579 let out = run_raw(cmd, None).await?;
580 if !out.status.success() {
581 return Err(failed("log", &out));
582 }
583 let text = String::from_utf8_lossy(&out.stdout).into_owned();
584 let mut parts = text.splitn(5, '\0');
585 let parents = parts.next().unwrap_or_default();
586 let name = parts.next().unwrap_or_default().to_owned();
587 let email = parts.next().unwrap_or_default().to_owned();
588 let time_unix = parts
589 .next()
590 .and_then(|t| t.trim().parse::<i64>().ok())
591 .unwrap_or(committer.time_unix);
592 let message = parts.next().unwrap_or_default().to_owned();
593 let Some(parent) = parents.split_whitespace().next() else {
594 return Err(Error::InvalidInput(
595 "cannot rebase a root commit onto the base".into(),
596 ));
597 };
598 validate_oid(parent)?;
599 let cmd = git(env, "merge-tree")
600 .git_dir(repo)
601 .arg("--write-tree")
602 .arg("--name-only")
603 .arg("--no-messages")
604 .user_opt("--merge-base", parent)?
605 .user_revs(&[tip.as_str(), commit.as_str()])?;
606 let out = run_raw(cmd, None).await?;
607 let text = String::from_utf8_lossy(&out.stdout).into_owned();
608 let tree = match out.status.code() {
609 Some(0) => text.lines().next().unwrap_or_default().trim().to_owned(),
610 Some(1) => {
611 let mut files: Vec<String> = Vec::new();
612 for line in text
613 .lines()
614 .skip(1)
615 .map(str::trim)
616 .filter(|l| !l.is_empty())
617 {
618 if !files.iter().any(|f| f == line) {
619 files.push(line.to_owned());
620 }
621 }
622 return Ok(RebaseResult::Conflict { commit, files });
623 }
624 _ => return Err(failed("merge-tree", &out)),
625 };
626 validate_oid(&tree)?;
627 let tip_tree = format!("{tip}^{{tree}}");
628 let cmd = git(env, "rev-parse")
629 .git_dir(repo)
630 .arg("--verify")
631 .user_revs(&[tip_tree.as_str()])?;
632 let out = run_raw(cmd, None).await?;
633 if !out.status.success() {
634 return Err(failed("rev-parse", &out));
635 }
636 if stdout_trimmed(&out) == tree {
637 continue;
638 }
639 let author = Signature {
640 name,
641 email,
642 time_unix,
643 };
644 tip = commit_tree(
645 env,
646 repo,
647 &tree,
648 &[tip.as_str()],
649 message.trim_end_matches('\n'),
650 &author,
651 committer,
652 )
653 .await?;
654 count += 1;
655 }
656 Ok(RebaseResult::Clean { tip, count })
657}
658
659/// One file of a commit made by [`commit_file_edit`].
660#[derive(Debug, Clone, Copy)]
661pub struct FileEdit<'a> {
662 /// Repo path of the file. It must be a regular file in the base commit.
663 pub path: &'a str,
664 /// The new content of the file.
665 pub content: &'a [u8],
666}
667
668static EDIT_INDEX_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
669
670/// Commits `edit` on top of `base` and moves `refname` from `base` to the new commit, only if the
671/// ref still holds `base`. A moved ref gives `Error::RefMoved` and nothing changes. The new tree is
672/// `base`'s tree with the one file replaced and its mode kept. It is built in a temporary index in
673/// the repo, so no working tree is needed. The commit's only parent is `base`. Returns its id.
674#[allow(clippy::too_many_arguments)]
675pub async fn commit_file_edit(
676 env: &GitEnv,
677 repo: &Path,
678 refname: &str,
679 base: &str,
680 edit: &FileEdit<'_>,
681 message: &str,
682 author: &Signature,
683 committer: &Signature,
684) -> Result<String> {
685 validate_ref(refname)?;
686 validate_oid(base)?;
687 validate_blob_path(edit.path)?;
688 let seq = EDIT_INDEX_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
689 let index = repo.join(format!("forge-edit-index-{}-{seq}", std::process::id()));
690 let result = edit_and_commit(
691 env, repo, &index, refname, base, edit, message, author, committer,
692 )
693 .await;
694 // The index is scratch space. A leftover file is harmless, but do not keep it.
695 let _ = tokio::fs::remove_file(&index).await;
696 result
697}
698
699#[allow(clippy::too_many_arguments)]
700async fn edit_and_commit(
701 env: &GitEnv,
702 repo: &Path,
703 index: &Path,
704 refname: &str,
705 base: &str,
706 edit: &FileEdit<'_>,
707 message: &str,
708 author: &Signature,
709 committer: &Signature,
710) -> Result<String> {
711 let blob = GitCommand::new(env, "hash-object")
712 .git_dir(repo)
713 .arg("-w")
714 .arg("--stdin")
715 .output_stdin(edit.content)
716 .await?;
717 let blob = String::from_utf8_lossy(&blob).trim().to_owned();
718 validate_oid(&blob)?;
719
720 GitCommand::new(env, "read-tree")
721 .git_dir(repo)
722 .env("GIT_INDEX_FILE", index)
723 .user_arg(base)?
724 .status()
725 .await?;
726
727 // `ls-files -s` gives `<mode> <oid> <stage>\t<path>`. The path must be the file itself, and a
728 // regular file: a symlink or a submodule is not something a suggestion can rewrite.
729 let listing = GitCommand::new(env, "ls-files")
730 .git_dir(repo)
731 .env("GIT_INDEX_FILE", index)
732 .arg("-s")
733 .arg("-z")
734 .arg("--")
735 .user_arg(edit.path)?
736 .output()
737 .await?;
738 let entry =
739 String::from_utf8_lossy(listing.split(|b| *b == 0).next().unwrap_or_default()).into_owned();
740 let mode = match entry.split_once('\t') {
741 Some((meta, path)) if path == edit.path => meta.split_whitespace().next().unwrap_or(""),
742 _ => "",
743 };
744 if mode != "100644" && mode != "100755" {
745 return Err(Error::InvalidInput(format!(
746 "{} is not a regular file at this commit",
747 edit.path
748 )));
749 }
750 let mode = mode.to_owned();
751
752 GitCommand::new(env, "update-index")
753 .git_dir(repo)
754 .env("GIT_INDEX_FILE", index)
755 .arg("--add")
756 .arg("--cacheinfo")
757 .user_arg(&mode)?
758 .user_arg(&blob)?
759 .user_arg(edit.path)?
760 .status()
761 .await?;
762
763 let tree = GitCommand::new(env, "write-tree")
764 .git_dir(repo)
765 .env("GIT_INDEX_FILE", index)
766 .output()
767 .await?;
768 let tree = String::from_utf8_lossy(&tree).trim().to_owned();
769
770 let commit = commit_tree(env, repo, &tree, &[base], message, author, committer).await?;
771 update_ref_cas(env, repo, refname, &commit, base).await?;
772 Ok(commit)
773}
774
775#[cfg(test)]
776mod tests {
777 use super::*;
778 use crate::history::DiffStatus;
779 use std::path::PathBuf;
780 use std::process::Command;
781
782 const LIMITS: DiffLimits = DiffLimits {
783 max_files: 100,
784 max_lines_per_file: 1000,
785 max_total_lines: 10_000,
786 };
787
788 /// Runs git in `dir` with a cleared environment and fixed identities.
789 fn git_in(dir: &Path, home: &Path, args: &[&str]) -> String {
790 let out = Command::new("/usr/bin/git")
791 .arg("-C")
792 .arg(dir)
793 .args(["-c", "commit.gpgsign=false"])
794 .args(args)
795 .env_clear()
796 .env("PATH", "/usr/bin:/bin")
797 .env("HOME", home)
798 .env("GIT_CONFIG_NOSYSTEM", "1")
799 .env("GIT_CONFIG_GLOBAL", "/dev/null")
800 .env("GIT_AUTHOR_NAME", "Tester")
801 .env("GIT_AUTHOR_EMAIL", "tester@example.com")
802 .env("GIT_COMMITTER_NAME", "Tester")
803 .env("GIT_COMMITTER_EMAIL", "tester@example.com")
804 .output()
805 .expect("git runs");
806 assert!(
807 out.status.success(),
808 "git {args:?} failed: {}",
809 String::from_utf8_lossy(&out.stderr)
810 );
811 String::from_utf8_lossy(&out.stdout).trim().to_owned()
812 }
813
814 struct Sandbox {
815 _dir: tempfile::TempDir,
816 home: PathBuf,
817 }
818
819 impl Sandbox {
820 /// The data dir holds the real managed gitconfig, as written at boot, so these tests see
821 /// the same `protocol.file.allow = never` setting that the server runs with.
822 fn new() -> Self {
823 let dir = tempfile::tempdir().expect("tempdir");
824 let home = dir.path().join("home");
825 std::fs::create_dir(&home).expect("home dir");
826 crate::setup::write_managed_gitconfig(&home).expect("managed gitconfig");
827 Self { _dir: dir, home }
828 }
829
830 fn env(&self) -> GitEnv {
831 GitEnv {
832 git_bin: PathBuf::from("/usr/bin/git"),
833 data_dir: self.home.clone(),
834 }
835 }
836
837 /// A non-bare repo named `name` with `main` checked out.
838 fn repo(&self, name: &str) -> Work {
839 let work = self._dir.path().join(name);
840 std::fs::create_dir(&work).expect("work dir");
841 git_in(&work, &self.home, &["init", "-q", "-b", "main"]);
842 Work {
843 work,
844 home: self.home.clone(),
845 }
846 }
847 }
848
849 struct Work {
850 work: PathBuf,
851 home: PathBuf,
852 }
853
854 impl Work {
855 fn git_dir(&self) -> PathBuf {
856 self.work.join(".git")
857 }
858
859 fn git(&self, args: &[&str]) -> String {
860 git_in(&self.work, &self.home, args)
861 }
862
863 fn write(&self, name: &str, content: &str) {
864 std::fs::write(self.work.join(name), content).expect("write file");
865 }
866
867 /// Stages everything, commits, and returns the new full id.
868 fn commit(&self, msg: &str) -> String {
869 self.git(&["add", "-A"]);
870 self.git(&["commit", "-q", "--allow-empty", "-m", msg]);
871 self.git(&["rev-parse", "HEAD"])
872 }
873 }
874
875 #[tokio::test]
876 async fn clean_merge_builds_merge_commit_with_author() {
877 let sb = Sandbox::new();
878 let env = sb.env();
879 let w = sb.repo("repo");
880 w.write("a.txt", "1\n");
881 let c0 = w.commit("c0");
882 w.git(&["switch", "-q", "-c", "feature"]);
883 w.write("b.txt", "feature\n");
884 let head = w.commit("feature work");
885 w.git(&["switch", "-q", "main"]);
886 w.write("c.txt", "main\n");
887 let base = w.commit("main work");
888 let gd = w.git_dir();
889
890 assert_eq!(
891 merge_base(&env, &gd, &base, &head)
892 .await
893 .expect("merge-base"),
894 Some(c0)
895 );
896 let tree = match check_merge(&env, &gd, &base, &head).await.expect("check") {
897 MergeCheck::Clean { tree } => tree,
898 other => panic!("expected clean merge, got {other:?}"),
899 };
900 assert_eq!(tree.len(), 40);
901
902 let author = Signature {
903 name: "Tahinli Author".into(),
904 email: "tahinli@example.com".into(),
905 time_unix: 1_700_000_000,
906 };
907 let committer = Signature {
908 name: "Carol Committer".into(),
909 email: "carol@example.com".into(),
910 time_unix: 1_700_000_100,
911 };
912 let merge = commit_tree(
913 &env,
914 &gd,
915 &tree,
916 &[base.as_str(), head.as_str()],
917 "Merge pull request #1 from owner/feature\n\nFeature",
918 &author,
919 &committer,
920 )
921 .await
922 .expect("commit-tree");
923
924 assert_eq!(
925 w.git(&["rev-list", "--parents", "-n1", merge.as_str()]),
926 format!("{merge} {base} {head}")
927 );
928 assert_eq!(
929 w.git(&[
930 "log",
931 "-1",
932 "--format=%T|%an|%ae|%at|%cn|%ce|%ct|%s",
933 merge.as_str()
934 ]),
935 format!(
936 "{tree}|Tahinli Author|tahinli@example.com|1700000000|Carol Committer|carol@example.com|1700000100|Merge pull request #1 from owner/feature"
937 )
938 );
939 assert!(
940 is_ancestor(&env, &gd, &head, &merge)
941 .await
942 .expect("ancestor")
943 );
944 }
945
946 #[tokio::test]
947 async fn conflicting_merge_lists_the_file() {
948 let sb = Sandbox::new();
949 let env = sb.env();
950 let w = sb.repo("repo");
951 w.write("f.txt", "base\n");
952 w.commit("c0");
953 w.git(&["switch", "-q", "-c", "feature"]);
954 w.write("f.txt", "head\n");
955 let head = w.commit("feature edits f");
956 w.git(&["switch", "-q", "main"]);
957 w.write("f.txt", "other\n");
958 let base = w.commit("main edits f");
959
960 let check = check_merge(&env, &w.git_dir(), &base, &head)
961 .await
962 .expect("check");
963 assert_eq!(
964 check,
965 MergeCheck::Conflict {
966 files: vec!["f.txt".to_owned()]
967 }
968 );
969 }
970
971 #[tokio::test]
972 async fn head_contained_in_base_is_up_to_date() {
973 let sb = Sandbox::new();
974 let env = sb.env();
975 let w = sb.repo("repo");
976 w.write("a.txt", "1\n");
977 let c0 = w.commit("c0");
978 w.write("a.txt", "2\n");
979 let c1 = w.commit("c1");
980 let gd = w.git_dir();
981
982 assert_eq!(
983 check_merge(&env, &gd, &c1, &c0).await.expect("check"),
984 MergeCheck::UpToDate
985 );
986 assert!(is_ancestor(&env, &gd, &c0, &c1).await.expect("ancestor"));
987 assert!(!is_ancestor(&env, &gd, &c1, &c0).await.expect("ancestor"));
988 }
989
990 #[tokio::test]
991 async fn update_ref_cas_succeeds_then_refuses_stale_old() {
992 let sb = Sandbox::new();
993 let env = sb.env();
994 let w = sb.repo("repo");
995 w.write("a.txt", "1\n");
996 let c0 = w.commit("c0");
997 w.write("a.txt", "2\n");
998 let c1 = w.commit("c1");
999 w.write("a.txt", "3\n");
1000 let c2 = w.commit("c2");
1001 let gd = w.git_dir();
1002
1003 // The base is at c2, so a CAS expecting c0 must fail and leave the ref alone.
1004 let stale = update_ref_cas(&env, &gd, "refs/heads/main", &c1, &c0).await;
1005 assert!(matches!(stale, Err(Error::RefMoved(_))), "{stale:?}");
1006 assert_eq!(w.git(&["rev-parse", "main"]), c2);
1007
1008 update_ref_cas(&env, &gd, "refs/heads/main", &c1, &c2)
1009 .await
1010 .expect("cas with current old");
1011 assert_eq!(w.git(&["rev-parse", "main"]), c1);
1012 }
1013
1014 #[tokio::test]
1015 async fn delete_ref_cas_deletes_only_at_expected_value() {
1016 let sb = Sandbox::new();
1017 let env = sb.env();
1018 let w = sb.repo("repo");
1019 w.write("a.txt", "1\n");
1020 let c0 = w.commit("c0");
1021 w.git(&["branch", "topic"]);
1022 w.write("a.txt", "2\n");
1023 let c1 = w.commit("c1");
1024 let gd = w.git_dir();
1025
1026 // topic is at c0, so a deletion expecting c1 must fail and leave the ref alone.
1027 let stale = delete_ref_cas(&env, &gd, "refs/heads/topic", &c1).await;
1028 assert!(matches!(stale, Err(Error::RefMoved(_))), "{stale:?}");
1029 assert_eq!(w.git(&["rev-parse", "topic"]), c0);
1030
1031 delete_ref_cas(&env, &gd, "refs/heads/topic", &c0)
1032 .await
1033 .expect("delete at current value");
1034 let gone = w.git(&["for-each-ref", "refs/heads/topic"]);
1035 assert!(gone.is_empty(), "{gone:?}");
1036
1037 // Deleting a ref that is already gone is a refusal, not a silent success.
1038 let missing = delete_ref_cas(&env, &gd, "refs/heads/topic", &c0).await;
1039 assert!(matches!(missing, Err(Error::RefMoved(_))), "{missing:?}");
1040 }
1041
1042 #[tokio::test]
1043 async fn range_log_returns_head_side_commits_oldest_first() {
1044 let sb = Sandbox::new();
1045 let env = sb.env();
1046 let w = sb.repo("repo");
1047 w.write("a.txt", "1\n");
1048 w.commit("c0");
1049 w.git(&["switch", "-q", "-c", "feature"]);
1050 w.write("f1.txt", "1\n");
1051 w.commit("f1");
1052 w.write("f2.txt", "1\n");
1053 let head = w.commit("f2");
1054 w.git(&["switch", "-q", "main"]);
1055 w.write("m.txt", "1\n");
1056 let base = w.commit("m1");
1057
1058 let log = range_log(&env, &w.git_dir(), &base, &head, 100)
1059 .await
1060 .expect("range log");
1061 let summaries: Vec<&str> = log.iter().map(|c| c.summary.as_str()).collect();
1062 assert_eq!(summaries, vec!["f1", "f2"]);
1063 }
1064
1065 #[tokio::test]
1066 async fn range_diff_shows_only_head_side_after_base_moved() {
1067 let sb = Sandbox::new();
1068 let env = sb.env();
1069 let w = sb.repo("repo");
1070 w.write("a.txt", "1\n");
1071 w.commit("c0");
1072 w.git(&["switch", "-q", "-c", "feature"]);
1073 w.write("feat.txt", "feature\n");
1074 let head = w.commit("feature");
1075 w.git(&["switch", "-q", "main"]);
1076 w.write("base.txt", "base\n");
1077 let base = w.commit("base moves");
1078
1079 let diff = range_diff_files(&env, &w.git_dir(), &base, &head, LIMITS)
1080 .await
1081 .expect("range diff");
1082 let paths: Vec<String> = diff
1083 .files
1084 .iter()
1085 .map(|f| f.new_path.clone().unwrap_or_default())
1086 .collect();
1087 assert_eq!(paths, vec!["feat.txt".to_owned()]);
1088 assert_eq!(diff.files[0].status, DiffStatus::Added);
1089 }
1090
1091 /// True when the repo at `git_dir` has `oid` in its object store.
1092 fn has_object(git_dir: &Path, oid: &str) -> bool {
1093 Command::new("/usr/bin/git")
1094 .arg("--git-dir")
1095 .arg(git_dir)
1096 .args(["cat-file", "-e", oid])
1097 .env_clear()
1098 .env("PATH", "/usr/bin:/bin")
1099 .env("GIT_CONFIG_NOSYSTEM", "1")
1100 .env("GIT_CONFIG_GLOBAL", "/dev/null")
1101 .status()
1102 .expect("git runs")
1103 .success()
1104 }
1105
1106 #[tokio::test]
1107 async fn alternate_objects_read_fork_commit_without_copying_it() {
1108 let sb = Sandbox::new();
1109 let env = sb.env();
1110 let base = sb.repo("base");
1111 base.write("a.txt", "1\n");
1112 let base_tip = base.commit("base");
1113 // The fork is a clone, so both histories share `base_tip`.
1114 let fork_dir = sb._dir.path().join("fork");
1115 git_in(
1116 sb._dir.path(),
1117 &sb.home,
1118 &["clone", "-q", base.work.to_str().expect("utf8"), "fork"],
1119 );
1120 let fork = Work {
1121 work: fork_dir,
1122 home: sb.home.clone(),
1123 };
1124 fork.write("b.txt", "fork\n");
1125 let fork_head = fork.commit("fork work");
1126 let base_git = base.git_dir();
1127 let fork_objects = fork.git_dir().join("objects");
1128 assert!(!has_object(&base_git, &fork_head));
1129
1130 // Without the alternate the base cannot see the fork's commit.
1131 assert!(
1132 range_log(&env, &base_git, &base_tip, &fork_head, 10)
1133 .await
1134 .is_err()
1135 );
1136
1137 let src = ObjectSource {
1138 extra: Some(fork_objects.as_path()),
1139 };
1140 let log = range_log_with(&env, &base_git, src, &base_tip, &fork_head, 10)
1141 .await
1142 .expect("range log through alternate");
1143 let summaries: Vec<&str> = log.iter().map(|c| c.summary.as_str()).collect();
1144 assert_eq!(summaries, vec!["fork work"]);
1145
1146 let merge = merge_base_with(&env, &base_git, src, &base_tip, &fork_head)
1147 .await
1148 .expect("merge base through alternate");
1149 assert_eq!(merge.as_deref(), Some(base_tip.as_str()));
1150
1151 let diff = range_diff_files_with(&env, &base_git, src, &base_tip, &fork_head, LIMITS)
1152 .await
1153 .expect("range diff through alternate");
1154 let paths: Vec<String> = diff
1155 .files
1156 .iter()
1157 .map(|f| f.new_path.clone().unwrap_or_default())
1158 .collect();
1159 assert_eq!(paths, vec!["b.txt".to_owned()]);
1160
1161 // Reading through the alternate wrote nothing into the base repo.
1162 assert!(!has_object(&base_git, &fork_head));
1163 }
1164
1165 #[tokio::test]
1166 async fn fetch_into_pull_ref_from_fork_and_same_repo() {
1167 let sb = Sandbox::new();
1168 let env = sb.env();
1169 let base = sb.repo("base");
1170 base.write("a.txt", "1\n");
1171 let base_tip = base.commit("base");
1172 let fork = sb.repo("fork");
1173 fork.write("x.txt", "fork\n");
1174 let fork_tip = fork.commit("fork work");
1175
1176 fetch_into_pull_ref(&env, &base.git_dir(), &fork.git_dir(), &fork_tip, 1)
1177 .await
1178 .expect("fork fetch");
1179 assert_eq!(base.git(&["rev-parse", "refs/pull/1/head"]), fork_tip);
1180
1181 fetch_into_pull_ref(&env, &base.git_dir(), &base.git_dir(), &base_tip, 2)
1182 .await
1183 .expect("same-repo update");
1184 assert_eq!(base.git(&["rev-parse", "refs/pull/2/head"]), base_tip);
1185 }
1186
1187 #[tokio::test]
1188 async fn fetch_into_pull_ref_handles_unadvertised_fork_commit() {
1189 let sb = Sandbox::new();
1190 let env = sb.env();
1191 let base = sb.repo("base");
1192 base.write("a.txt", "1\n");
1193 base.commit("base");
1194 let fork = sb.repo("fork");
1195 fork.write("x.txt", "fork\n");
1196 fork.commit("main work");
1197 fork.git(&["switch", "-q", "-c", "topic"]);
1198 fork.write("y.txt", "topic\n");
1199 let topic_tip = fork.commit("topic work");
1200 fork.git(&["switch", "-q", "main"]);
1201 fork.git(&["branch", "-q", "-D", "topic"]);
1202
1203 fetch_into_pull_ref(&env, &base.git_dir(), &fork.git_dir(), &topic_tip, 3)
1204 .await
1205 .expect("unadvertised fetch");
1206 assert_eq!(base.git(&["rev-parse", "refs/pull/3/head"]), topic_tip);
1207 }
1208
1209 #[tokio::test]
1210 async fn blob_at_returns_blob_ids_for_files_only() {
1211 let sb = Sandbox::new();
1212 let env = sb.env();
1213 let w = sb.repo("repo");
1214 let gd = w.git_dir();
1215 w.write("a.txt", "1\n");
1216 std::fs::create_dir(w.work.join("dir")).expect("dir");
1217 w.write("dir/x.txt", "x\n");
1218 let c0 = w.commit("c0");
1219 let a0 = w.git(&["hash-object", "a.txt"]);
1220
1221 assert_eq!(
1222 blob_at(&env, &gd, &c0, "a.txt").await.expect("ok"),
1223 Some(a0.clone())
1224 );
1225 assert_eq!(
1226 blob_at(&env, &gd, &c0, "dir/x.txt").await.expect("ok"),
1227 Some(w.git(&["hash-object", "dir/x.txt"]))
1228 );
1229 assert_eq!(
1230 blob_at(&env, &gd, &c0, "missing.txt").await.expect("ok"),
1231 None
1232 );
1233 assert_eq!(blob_at(&env, &gd, &c0, "dir").await.expect("ok"), None);
1234
1235 w.write("a.txt", "2\n");
1236 let c1 = w.commit("c1");
1237 let a1 = blob_at(&env, &gd, &c1, "a.txt").await.expect("ok");
1238 assert_eq!(a1, Some(w.git(&["hash-object", "a.txt"])));
1239 assert_ne!(a1, Some(a0));
1240 // The older commit still maps to the older blob.
1241 let old_spec = format!("{c0}:a.txt");
1242 assert_eq!(
1243 blob_at(&env, &gd, &c0, "a.txt").await.expect("ok"),
1244 Some(w.git(&["rev-parse", old_spec.as_str()]))
1245 );
1246 }
1247
1248 #[tokio::test]
1249 async fn blob_at_handles_literal_special_and_unicode_names() {
1250 let sb = Sandbox::new();
1251 let env = sb.env();
1252 let w = sb.repo("repo");
1253 let gd = w.git_dir();
1254 std::fs::create_dir(w.work.join("dir with space")).expect("dir");
1255 w.write("dir with space/füß ü.txt", "u\n");
1256 w.write("star*", "s\n");
1257 w.write(":colon", "c\n");
1258 w.write("other", "o\n");
1259 let c0 = w.commit("c0");
1260
1261 assert_eq!(
1262 blob_at(&env, &gd, &c0, "dir with space/füß ü.txt")
1263 .await
1264 .expect("ok"),
1265 Some(w.git(&["hash-object", "dir with space/füß ü.txt"]))
1266 );
1267 assert_eq!(
1268 blob_at(&env, &gd, &c0, "star*").await.expect("ok"),
1269 Some(w.git(&["hash-object", "star*"]))
1270 );
1271 assert_eq!(
1272 blob_at(&env, &gd, &c0, ":colon").await.expect("ok"),
1273 Some(w.git(&["hash-object", ":colon"]))
1274 );
1275 // A glob must not match other entries.
1276 assert_eq!(blob_at(&env, &gd, &c0, "st*").await.expect("ok"), None);
1277 assert_eq!(blob_at(&env, &gd, &c0, "*").await.expect("ok"), None);
1278 }
1279
1280 #[tokio::test]
1281 async fn invalid_inputs_are_rejected_before_git() {
1282 let sb = Sandbox::new();
1283 let env = sb.env();
1284 let w = sb.repo("repo");
1285 w.write("a.txt", "1\n");
1286 let c0 = w.commit("c0");
1287 let gd = w.git_dir();
1288 let short = "a".repeat(39);
1289
1290 for bad in [
1291 "", "../x", "a/../x", "/a", "a//b", "a/", "./a", "a/./b", "a\nb", "a\0b",
1292 ] {
1293 let r = blob_at(&env, &gd, &c0, bad).await;
1294 assert!(matches!(r, Err(Error::InvalidInput(_))), "{bad:?}: {r:?}");
1295 }
1296 let r = blob_at(&env, &gd, "not-hex", "a.txt").await;
1297 assert!(matches!(r, Err(Error::InvalidInput(_))), "{r:?}");
1298
1299 let bad_oid = |r: Result<()>| assert!(matches!(r, Err(Error::InvalidInput(_))), "{r:?}");
1300 bad_oid(check_merge(&env, &gd, "not-hex", &c0).await.map(|_| ()));
1301 bad_oid(merge_base(&env, &gd, &short, &c0).await.map(|_| ()));
1302 bad_oid(
1303 commit_tree(
1304 &env,
1305 &gd,
1306 "--output=/tmp/x",
1307 &[],
1308 "m",
1309 &Signature {
1310 name: "a".into(),
1311 email: "a@example.com".into(),
1312 time_unix: 0,
1313 },
1314 &Signature {
1315 name: "a".into(),
1316 email: "a@example.com".into(),
1317 time_unix: 0,
1318 },
1319 )
1320 .await
1321 .map(|_| ()),
1322 );
1323 bad_oid(update_ref_cas(&env, &gd, "refs/heads/main", "HEAD", &c0).await);
1324 bad_oid(update_ref_cas(&env, &gd, "refs/heads/../x", &c0, &c0).await);
1325 bad_oid(update_ref_cas(&env, &gd, "refs/heads/-x", &c0, &c0).await);
1326 bad_oid(fetch_into_pull_ref(&env, &gd, &gd, "--upload-pack=x", 1).await);
1327 bad_oid(fetch_into_pull_ref(&env, &gd, &gd, &c0, 0).await);
1328 bad_oid(range_log(&env, &gd, "main", &c0, 10).await.map(|_| ()));
1329 bad_oid(
1330 range_diff_files(&env, &gd, &c0, &short, LIMITS)
1331 .await
1332 .map(|_| ()),
1333 );
1334 let bad_name = Signature {
1335 name: "Eve <eve@example.com>".into(),
1336 email: "eve@example.com".into(),
1337 time_unix: 0,
1338 };
1339 bad_oid(
1340 commit_tree(&env, &gd, &c0, &[], "m", &bad_name, &bad_name)
1341 .await
1342 .map(|_| ()),
1343 );
1344 }
1345
1346 #[tokio::test]
1347 async fn rebase_replays_commits_keeping_authors() {
1348 let sb = Sandbox::new();
1349 let env = sb.env();
1350 let w = sb.repo("repo");
1351 w.write("a.txt", "1\n");
1352 w.commit("c0");
1353 w.git(&["switch", "-q", "-c", "feature"]);
1354 w.write("b.txt", "one\n");
1355 w.commit("first");
1356 w.write("b.txt", "two\n");
1357 let head = w.commit("second");
1358 w.git(&["switch", "-q", "main"]);
1359 w.write("c.txt", "main\n");
1360 let base = w.commit("main work");
1361 let gd = w.git_dir();
1362 let committer = Signature {
1363 name: "tahinli".into(),
1364 email: "tahinli@example.com".into(),
1365 time_unix: 1_700_000_000,
1366 };
1367 let (tip, count) = match rebase_commits(&env, &gd, &base, &head, &committer)
1368 .await
1369 .expect("rebase")
1370 {
1371 RebaseResult::Clean { tip, count } => (tip, count),
1372 other => panic!("expected clean, got {other:?}"),
1373 };
1374 assert_eq!(count, 2);
1375 assert_eq!(w.git(&["rev-parse", &format!("{tip}~2")]), base);
1376 assert_eq!(
1377 w.git(&["log", "-1", "--format=%an|%cn|%s", &tip]),
1378 "Tester|tahinli|second"
1379 );
1380 assert_eq!(w.git(&["show", &format!("{tip}:b.txt")]), "two");
1381 assert_eq!(w.git(&["show", &format!("{tip}:c.txt")]), "main");
1382 }
1383
1384 #[tokio::test]
1385 async fn rebase_reports_conflicts() {
1386 let sb = Sandbox::new();
1387 let env = sb.env();
1388 let w = sb.repo("repo");
1389 w.write("a.txt", "1\n");
1390 w.commit("c0");
1391 w.git(&["switch", "-q", "-c", "feature"]);
1392 w.write("a.txt", "feature\n");
1393 let head = w.commit("feature edit");
1394 w.git(&["switch", "-q", "main"]);
1395 w.write("a.txt", "main\n");
1396 let base = w.commit("main edit");
1397 let committer = Signature {
1398 name: "tahinli".into(),
1399 email: "tahinli@example.com".into(),
1400 time_unix: 1_700_000_000,
1401 };
1402 match rebase_commits(&env, &w.git_dir(), &base, &head, &committer)
1403 .await
1404 .expect("rebase")
1405 {
1406 RebaseResult::Conflict { commit, files } => {
1407 assert_eq!(commit, head);
1408 assert_eq!(files, vec!["a.txt".to_owned()]);
1409 }
1410 other => panic!("expected conflict, got {other:?}"),
1411 }
1412 }
1413}