1use std::path::{Path, PathBuf};
7use std::process::Stdio;
8
9use crate::proc::Quiet as _;
10use anyhow::{Context as _, Result, bail, ensure};
11use tokio::process::Command;
12
13#[derive(Debug)]
15pub struct GitOut {
16 pub code: Option<i32>,
18 pub stdout: String,
20 pub stderr: String,
22}
23
24impl GitOut {
25 pub fn ok(&self) -> bool {
27 self.code == Some(0)
28 }
29}
30
31pub async fn git_raw(cwd: &Path, args: &[&str]) -> Result<GitOut> {
34 git_raw_command(cwd, args, false).await
35}
36
37pub(crate) async fn git_raw_command(
38 cwd: &Path,
39 args: &[&str],
40 kill_on_drop: bool,
41) -> Result<GitOut> {
42 if args.starts_with(&["worktree", "add"]) {
43 return worktree_add_raw(cwd, args, kill_on_drop).await;
44 }
45 let _config_lock = if args == ["config", "extensions.worktreeConfig", "true"]
46 || args == ["config", "--unset", "extensions.worktreeConfig"]
47 {
48 Some(lock_worktree_config(cwd).await?)
49 } else {
50 None
51 };
52 git_raw_unlocked(cwd, args, kill_on_drop).await
53}
54
55async fn config_bool(repo: &Path, local: bool, key: &str) -> Result<bool> {
56 let scope = if local { "--local" } else { "--includes" };
57 let out = git_raw_unlocked(repo, &["config", scope, "--bool", "--get", key], false).await?;
58 match (out.code, out.stdout.as_str()) {
59 (Some(0), "true") => Ok(true),
60 (Some(0), "false") => Ok(false),
61 (Some(1), "") if out.stderr.is_empty() => Ok(false),
62 _ => bail!("read Git config {key}: {}", out.stderr),
63 }
64}
65
66async fn worktree_add_raw(cwd: &Path, args: &[&str], kill_on_drop: bool) -> Result<GitOut> {
67 let lock = lock_worktree_config(cwd).await?;
68 let relative = match args
69 .iter()
70 .rev()
71 .find(|arg| matches!(**arg, "--relative-paths" | "--no-relative-paths"))
72 {
73 Some(arg) => *arg == "--relative-paths",
74 None => config_bool(cwd, false, "worktree.useRelativePaths").await?,
75 };
76 if relative && !config_bool(cwd, true, "extensions.relativeWorktrees").await? {
77 let help = git_raw_unlocked(cwd, &["worktree", "add", "-h"], false).await?;
80 if help.stdout.contains("relative-paths") || help.stderr.contains("relative-paths") {
81 let add = git_raw_unlocked(cwd, args, kill_on_drop);
87 tokio::pin!(add);
88 loop {
89 tokio::select! {
90 result = &mut add => return result,
91 migrated = async {
92 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
93 config_bool(cwd, true, "extensions.relativeWorktrees").await
94 } => {
95 if matches!(migrated, Ok(true)) {
96 drop(lock);
97 return add.await;
98 }
99 }
100 }
101 }
102 }
103 }
104 drop(lock);
105 git_raw_unlocked(cwd, args, kill_on_drop).await
106}
107
108async fn lock_worktree_config(repo: &Path) -> Result<std::fs::File> {
109 let common = git_raw_unlocked(
110 repo,
111 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
112 false,
113 )
114 .await?;
115 ensure!(
116 common.ok(),
117 "resolve shared Git directory: {}",
118 common.stderr
119 );
120 let common = std::fs::canonicalize(&common.stdout)?;
121 let path = common.join("magi-worktree-config.lock");
122 let file = std::fs::OpenOptions::new()
123 .read(true)
124 .write(true)
125 .create(true)
126 .truncate(false)
127 .open(&path)?;
128 let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(30);
129 loop {
130 match crate::pr_head::try_lock_file(&file) {
131 Ok(()) => return Ok(file),
132 Err(e)
133 if e.kind() == std::io::ErrorKind::WouldBlock || e.raw_os_error() == Some(33) =>
134 {
135 ensure!(
136 tokio::time::Instant::now() < deadline,
137 "waiting for shared Git config lock: {}",
138 path.display()
139 );
140 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
141 }
142 Err(e) => return Err(e).context("acquire shared Git config lock"),
143 }
144 }
145}
146
147async fn git_raw_unlocked(cwd: &Path, args: &[&str], kill_on_drop: bool) -> Result<GitOut> {
148 #[cfg(test)]
149 crate::web::request_cost::git();
150 let out = Command::new("git")
151 .args(args)
152 .current_dir(cwd)
153 .quiet()
154 .env("GIT_TERMINAL_PROMPT", "0")
157 .env("GIT_EDITOR", "true")
158 .stdin(Stdio::null())
159 .kill_on_drop(kill_on_drop)
160 .output()
161 .await
162 .with_context(|| format!("spawn git {}", args.join(" ")))?;
163 Ok(GitOut {
164 code: out.status.code(),
165 stdout: String::from_utf8_lossy(&out.stdout).trim_end().to_owned(),
166 stderr: String::from_utf8_lossy(&out.stderr).trim_end().to_owned(),
167 })
168}
169
170pub(crate) fn path_arg(path: &Path) -> String {
173 #[cfg(windows)]
174 let unicode = path.to_str().is_some();
175 let path = path.to_string_lossy();
176 #[cfg(windows)]
177 {
178 if unicode {
179 windows_cli_path(&path)
180 } else {
181 path.into_owned()
182 }
183 }
184 #[cfg(not(windows))]
185 {
186 path.into_owned()
187 }
188}
189
190#[cfg(any(windows, test))]
191fn windows_cli_path(path: &str) -> String {
192 let path = path.replace('\\', "/");
193 if path.starts_with("//?/")
194 && path[4..].split('/').any(|part| {
195 let name = part.split('.').next().unwrap_or("").to_ascii_uppercase();
196 part.ends_with(['.', ' '])
197 || matches!(
198 name.as_str(),
199 "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
200 )
201 || (name.len() == 4
202 && (name.starts_with("COM") || name.starts_with("LPT"))
203 && matches!(name.as_bytes()[3], b'1'..=b'9'))
204 })
205 {
206 return path;
209 }
210 if let Some(unc) = path.strip_prefix("//?/UNC/") {
211 return format!("//{unc}");
212 }
213 if let Some(drive) = path.strip_prefix("//?/")
214 && drive.as_bytes().get(1) == Some(&b':')
215 && drive.as_bytes().get(2) == Some(&b'/')
216 && drive.as_bytes()[0].is_ascii_alphabetic()
217 {
218 return drive.to_owned();
219 }
220 path
221}
222
223pub(crate) fn canonical_output_path(value: &str) -> Result<PathBuf> {
226 let path = PathBuf::from(value);
227 let canonical = path.canonicalize()?;
228 #[cfg(windows)]
229 let same_path = windows_cli_path(path.to_str().context("non UTF-8 Git path")?)
230 == windows_cli_path(canonical.to_str().context("non UTF-8 canonical Git path")?);
231 #[cfg(not(windows))]
232 let same_path = path == canonical;
233 ensure!(same_path, "noncanonical Git path: {}", path.display());
234 Ok(canonical)
235}
236
237pub async fn fetch_origin(cwd: &Path, timeout: std::time::Duration) -> Result<()> {
249 let url = git(cwd, &["remote", "get-url", "origin"]).await?;
250 #[cfg(test)]
251 crate::web::request_cost::git();
252 let fut = Command::new("git")
253 .args([
254 "fetch",
255 "--quiet",
256 "--no-tags",
257 "--no-recurse-submodules",
258 "--no-write-fetch-head",
259 "--",
260 url.as_str(),
261 "+refs/heads/*:refs/remotes/origin/*",
262 ])
263 .current_dir(cwd)
264 .quiet()
265 .env("GIT_TERMINAL_PROMPT", "0")
266 .stdin(Stdio::null())
267 .kill_on_drop(true)
268 .output();
269 let out = tokio::time::timeout(timeout, fut)
270 .await
271 .map_err(|_| anyhow::anyhow!("git fetch timed out after {}s", timeout.as_secs()))?
272 .context("spawn git fetch")?;
273 if !out.status.success() {
274 bail!(
275 "git fetch failed ({}): {}",
276 crate::notices::exit_status(out.status.code()),
277 String::from_utf8_lossy(&out.stderr).trim_end()
278 );
279 }
280 Ok(())
281}
282
283pub async fn git(cwd: &Path, args: &[&str]) -> Result<String> {
285 let out = git_raw(cwd, args).await?;
286 if !out.ok() {
287 bail!(
288 "git {} failed in {} ({}): {}",
289 args.join(" "),
290 cwd.display(),
291 crate::notices::exit_status(out.code),
292 if out.stderr.is_empty() {
293 out.stdout.as_str()
294 } else {
295 out.stderr.as_str()
296 }
297 );
298 }
299 Ok(out.stdout)
300}
301
302pub async fn toplevel(path: &Path) -> Result<PathBuf> {
304 let out = Command::from(toplevel_command(path))
305 .kill_on_drop(true)
306 .output()
307 .await;
308 toplevel_output(path, out)
309}
310
311pub(crate) fn toplevel_blocking(path: &Path) -> Result<PathBuf> {
313 toplevel_output(path, toplevel_command(path).output())?
314 .canonicalize()
315 .with_context(|| format!("canonicalize Git checkout root of {}", path.display()))
316}
317
318fn toplevel_command(path: &Path) -> std::process::Command {
319 #[cfg(test)]
320 crate::web::request_cost::git();
321 let mut command = std::process::Command::new("git");
322 command
323 .args(["rev-parse", "--show-toplevel"])
324 .current_dir(path)
325 .quiet()
326 .stdin(Stdio::null());
327 for key in [
329 "GIT_DIR",
330 "GIT_WORK_TREE",
331 "GIT_IMPLICIT_WORK_TREE",
332 "GIT_COMMON_DIR",
333 "GIT_CONFIG",
334 "GIT_CONFIG_PARAMETERS",
335 "GIT_CONFIG_COUNT",
336 "GIT_CONFIG_GLOBAL",
337 "GIT_CONFIG_SYSTEM",
338 "GIT_PREFIX",
339 ] {
340 command.env_remove(key);
341 }
342 command
343}
344
345fn toplevel_output(path: &Path, out: std::io::Result<std::process::Output>) -> Result<PathBuf> {
346 let out = out.with_context(|| format!("read Git checkout root of {}", path.display()))?;
347 ensure!(
348 out.status.success(),
349 "cannot read Git checkout root of {}: {}",
350 path.display(),
351 String::from_utf8_lossy(&out.stderr).trim_end()
352 );
353 Ok(PathBuf::from(
354 std::str::from_utf8(&out.stdout)?.trim_end_matches(['\r', '\n']),
355 ))
356}
357
358pub(crate) fn same_checkout(left: &Path, right: &Path) -> Result<bool> {
361 if left == right {
362 return Ok(true);
363 }
364 let canonical = |path: &Path| {
365 path.canonicalize()
366 .with_context(|| format!("resolve repository {}", path.display()))
367 };
368 let left = canonical(left)?;
369 let right = canonical(right)?;
370 Ok(left == right || toplevel_blocking(&left)? == toplevel_blocking(&right)?)
371}
372
373pub async fn rev_parse(repo: &Path, rev: &str) -> Result<String> {
375 git(repo, &["rev-parse", rev]).await
376}
377
378pub async fn current_branch(repo: &Path) -> Result<Option<String>> {
380 let out = git_raw(repo, &["symbolic-ref", "--quiet", "--short", "HEAD"]).await?;
381 Ok(if out.ok() && !out.stdout.is_empty() {
382 Some(out.stdout)
383 } else {
384 None
385 })
386}
387
388pub fn remote_head_branch(remote: &str, symref: &str) -> Option<String> {
393 symref
394 .trim()
395 .strip_prefix(&format!("refs/remotes/{remote}/"))
396 .filter(|b| !b.is_empty() && *b != "HEAD")
397 .map(str::to_owned)
398}
399
400pub async fn ensure_remote_head(repo: &Path, remote: &str, base: &str) {
406 let head = format!("refs/remotes/{remote}/HEAD");
407 if git_raw(repo, &["symbolic-ref", "--quiet", &head])
408 .await
409 .is_ok_and(|o| o.ok())
410 {
411 return;
412 }
413 let target = format!("refs/remotes/{remote}/{base}");
414 let _ = git_raw(repo, &["symbolic-ref", &head, &target]).await;
415}
416
417fn symref_branch(out: &str) -> Option<String> {
420 out.lines()
421 .find_map(|l| l.strip_prefix("ref: refs/heads/"))
422 .and_then(|l| l.split_whitespace().next())
423 .map(str::to_owned)
424}
425
426pub async fn merge_base_branch(
433 repo: &Path,
434 remote: &str,
435 explicit: Option<&str>,
436) -> Result<String> {
437 if let Some(b) = explicit.map(str::trim).filter(|b| !b.is_empty()) {
438 return Ok(b.to_owned());
439 }
440 let head = format!("refs/remotes/{remote}/HEAD");
441 let read = || async {
442 let out = git_raw(repo, &["symbolic-ref", "--quiet", &head])
443 .await
444 .ok()?;
445 if out.ok() {
446 remote_head_branch(remote, &out.stdout)
447 } else {
448 None
449 }
450 };
451 if let Some(b) = read().await {
452 return Ok(b);
453 }
454 let set = git_raw(repo, &["remote", "set-head", remote, "-a"]).await;
455 if let Some(b) = read().await {
456 return Ok(b);
457 }
458 if let Ok(o) = git_raw(repo, &["ls-remote", "--symref", remote, "HEAD"]).await
463 && o.ok()
464 && let Some(b) = symref_branch(&o.stdout)
465 {
466 return Ok(b);
467 }
468 let why = match set {
469 Ok(o) if !o.ok() => o.stderr.lines().next().unwrap_or("").trim().to_owned(),
470 Ok(_) => "the remote reported no default branch".to_owned(),
471 Err(e) => e.to_string(),
472 };
473 bail!(
474 "cannot tell which branch of `{remote}` is the base ({why}): set [merge] base \
475 (and remote) in magi.toml, or run `git remote set-head {remote} -a`. magi does \
476 not fall back to the checked-out branch, which may be detached or stale"
477 )
478}
479
480pub async fn is_clean(repo: &Path) -> Result<bool> {
482 Ok(git(repo, &["status", "--porcelain"]).await?.is_empty())
483}
484
485pub async fn status_porcelain(repo: &Path) -> Result<String> {
487 git(repo, &["status", "--porcelain"]).await
488}
489
490pub async fn worktree_add_branch(repo: &Path, path: &Path, branch: &str, base: &str) -> Result<()> {
492 if let Some(parent) = path.parent() {
493 tokio::fs::create_dir_all(parent).await.ok();
494 }
495 let path_s = path_arg(path);
496 git(repo, &["worktree", "add", "-b", branch, &path_s, base])
497 .await
498 .map(|_| ())
499}
500
501pub(crate) async fn worktree_add_existing(
503 repo: &Path,
504 path: &Path,
505 branch: &str,
506 force: bool,
507) -> Result<()> {
508 if let Some(parent) = path.parent() {
509 tokio::fs::create_dir_all(parent).await.ok();
510 }
511 let path_s = path_arg(path);
512 if force {
513 git(repo, &["worktree", "add", "--force", &path_s, branch]).await
514 } else {
515 git(repo, &["worktree", "add", &path_s, branch]).await
516 }
517 .map(|_| ())
518}
519
520pub async fn worktree_add_detached(repo: &Path, path: &Path, rev: &str) -> Result<()> {
522 if let Some(parent) = path.parent() {
523 tokio::fs::create_dir_all(parent).await.ok();
524 }
525 let path_s = path_arg(path);
526 git(repo, &["worktree", "add", "--detach", &path_s, rev])
527 .await
528 .map(|_| ())
529}
530
531pub async fn reset_detached(worktree: &Path, rev: &str) -> Result<()> {
533 reset_detached_keep_ignored(worktree, rev).await?;
534 clean_all(worktree).await
535}
536
537pub async fn reset_detached_keep_ignored(worktree: &Path, rev: &str) -> Result<()> {
540 git(worktree, &["checkout", "--detach", rev]).await?;
541 git(worktree, &["reset", "--hard", rev]).await.map(|_| ())
542}
543
544pub async fn worktree_holding(repo: &Path, branch: &str) -> Result<Option<PathBuf>> {
549 let listing = git(repo, &["worktree", "list", "--porcelain"]).await?;
550 Ok(parse_worktree_holder(&listing, branch))
551}
552
553fn parse_worktree_holder(listing: &str, branch: &str) -> Option<PathBuf> {
554 let want = format!("refs/heads/{branch}");
555 let mut path: Option<PathBuf> = None;
556 for line in listing.lines() {
557 if let Some(p) = line.strip_prefix("worktree ") {
558 path = Some(PathBuf::from(p));
559 } else if line.strip_prefix("branch ") == Some(want.as_str()) {
560 return path;
561 }
562 }
563 None
564}
565
566pub async fn worktree_remove(repo: &Path, path: &Path) -> Result<bool> {
570 let path_s = path_arg(path);
571 let out = git_raw(repo, &["worktree", "remove", "--force", &path_s]).await?;
572 if out.ok() {
573 return Ok(true);
574 }
575 if !path.exists() {
577 git_raw(repo, &["worktree", "prune"]).await?;
578 }
579 Ok(false)
580}
581
582pub async fn worktree_remove_clean(repo: &Path, path: &Path) -> Result<bool> {
586 let path_s = path_arg(path);
587 Ok(git_raw(repo, &["worktree", "remove", &path_s]).await?.ok())
588}
589
590pub async fn remove_worktree_from_linked(dir: &Path) {
599 let Ok(link) = std::fs::read_to_string(dir.join(".git")) else {
600 return;
601 };
602 let Some(admin) = link.strip_prefix("gitdir:").map(str::trim) else {
603 return;
604 };
605 let admin = Path::new(admin);
608 let Some(common) = admin.parent().and_then(Path::parent) else {
609 return;
610 };
611 let common_s = common.to_string_lossy();
612 let _ = git_raw(dir, &["--git-dir", &common_s, "worktree", "prune"]).await;
613}
614
615pub async fn worktree_prune(repo: &Path) -> Result<()> {
624 git(repo, &["worktree", "prune"]).await.map(|_| ())
625}
626
627pub async fn branch_delete(repo: &Path, branch: &str) -> Result<bool> {
629 Ok(git_raw(repo, &["branch", "-D", branch]).await?.ok())
630}
631
632pub async fn branch_exists(repo: &Path, branch: &str) -> Result<bool> {
634 let refname = format!("refs/heads/{branch}");
635 Ok(
636 git_raw(repo, &["show-ref", "--verify", "--quiet", &refname])
637 .await?
638 .ok(),
639 )
640}
641
642pub async fn remote_has_branch(repo: &Path, remote: &str, branch: &str) -> Result<bool> {
645 let refname = format!("refs/heads/{branch}");
646 let out = git_raw(repo, &["ls-remote", "--exit-code", remote, &refname]).await?;
647 match out.code {
648 Some(0) => Ok(true),
649 Some(2) => Ok(false),
650 code => bail!(
651 "git ls-remote {remote} failed ({}): {}",
652 crate::notices::exit_status(code),
653 out.stderr
654 ),
655 }
656}
657
658pub async fn diff(worktree: &Path, base: &str, head: &str) -> Result<String> {
660 let range = format!("{base}...{head}");
661 git(
662 worktree,
663 &["diff", "--no-color", "--no-ext-diff", "-M", &range],
664 )
665 .await
666}
667
668pub async fn diff_stat(worktree: &Path, base: &str, head: &str) -> Result<String> {
670 let range = format!("{base}...{head}");
671 git(worktree, &["diff", "--no-color", "--stat", &range]).await
672}
673
674pub async fn changed_lines(worktree: &Path, base: &str, head: &str) -> Option<usize> {
678 let out = git_raw(worktree, &["diff", "--numstat", base, head])
679 .await
680 .ok()?;
681 if !out.ok() {
682 return None;
683 }
684 let mut total = 0usize;
685 for line in out.stdout.lines().filter(|l| !l.trim().is_empty()) {
686 let mut cols = line.split('\t');
687 let added: usize = cols.next()?.parse().ok()?;
688 let removed: usize = cols.next()?.parse().ok()?;
689 total = total.saturating_add(added).saturating_add(removed);
690 }
691 Some(total)
692}
693
694pub async fn restore_to(worktree: &Path, rev: &str) -> Result<()> {
698 git(worktree, &["reset", "--hard", "-q", rev]).await?;
699 git(worktree, &["clean", "-ffdq"]).await?;
702 git(
708 worktree,
709 &[
710 "submodule",
711 "--quiet",
712 "update",
713 "--recursive",
714 "--force",
715 "--checkout",
716 ],
717 )
718 .await?;
719 git(
720 worktree,
721 &[
722 "submodule",
723 "--quiet",
724 "foreach",
725 "--recursive",
726 "git clean -ffdq",
727 ],
728 )
729 .await?;
730 Ok(())
731}
732
733pub async fn changed_files(worktree: &Path, base: &str, head: &str) -> Result<Vec<String>> {
735 let range = format!("{base}...{head}");
736 let out = git(worktree, &["diff", "--name-only", &range]).await?;
737 Ok(out.lines().map(str::to_owned).collect())
738}
739
740pub async fn commit_log(worktree: &Path, base: &str, head: &str) -> Result<Vec<(String, String)>> {
744 let range = format!("{base}..{head}");
745 let out = git(
746 worktree,
747 &[
748 "log",
749 "--reverse",
750 "--no-color",
751 "--format=%s%x1f%b%x00",
752 &range,
753 ],
754 )
755 .await?;
756 Ok(out
757 .split('\0')
758 .filter_map(|rec| {
759 let rec = rec.trim_start_matches('\n');
760 if rec.trim().is_empty() {
761 return None;
762 }
763 let (subject, body) = rec.split_once('\x1f').unwrap_or((rec, ""));
764 Some((subject.trim().to_owned(), body.trim().to_owned()))
765 })
766 .collect())
767}
768
769pub async fn log_oneline(worktree: &Path, base: &str, head: &str) -> Result<String> {
771 let range = format!("{base}..{head}");
772 git(
773 worktree,
774 &["log", "--reverse", "--format=%s%n%b%n--", &range],
775 )
776 .await
777}
778
779pub async fn subjects(worktree: &Path, base: &str, head: &str) -> Result<Vec<String>> {
782 let range = format!("{base}..{head}");
783 let out = git(worktree, &["log", "--reverse", "--format=%s%x00", &range]).await?;
784 let mut parts: Vec<String> = out.split('\0').map(|s| s.trim().to_owned()).collect();
785 parts.pop();
787 Ok(parts)
788}
789
790pub async fn commits_ahead(worktree: &Path, base: &str, head: &str) -> Result<usize> {
792 let range = format!("{base}..{head}");
793 let out = git(worktree, &["rev-list", "--count", &range]).await?;
794 Ok(out.trim().parse().unwrap_or(0))
795}
796
797pub const NEUTRAL_IDENTITY_NAME: &str = "magi candidate";
799
800pub const NEUTRAL_IDENTITY_EMAIL: &str = "magi@localhost";
802
803#[derive(Debug, Clone, PartialEq, Eq)]
805pub struct CommitProvenance {
806 pub commit: String,
808 pub parents: Vec<String>,
810 pub author_name: String,
812 pub author_email: String,
814 pub committer_name: String,
816 pub committer_email: String,
818 pub message: String,
820}
821
822pub async fn commit_provenance(repo: &Path, rev: &str) -> Result<CommitProvenance> {
824 let spec = format!("{rev}^{{commit}}");
825 let out = git_raw(
826 repo,
827 &[
828 "-c",
829 "log.showSignature=false",
830 "show",
831 "-s",
832 "--format=%H%x00%P%x00%an%x00%ae%x00%cn%x00%ce%x00%B%x00end",
833 &spec,
834 "--",
835 ],
836 )
837 .await?;
838 ensure!(
839 out.ok(),
840 "git show commit provenance for {rev} failed: {}",
841 out.stderr
842 );
843 let parts: Vec<&str> = out.stdout.split('\0').collect();
844 ensure!(
845 parts.len() == 8 && parts[7] == "end",
846 "unexpected git commit provenance output for {rev}"
847 );
848 let parents = parts[1].split_whitespace().map(str::to_owned).collect();
849 let message = parts[6]
850 .strip_suffix("\r\n")
851 .or_else(|| parts[6].strip_suffix('\n'))
852 .unwrap_or(parts[6])
853 .to_owned();
854 Ok(CommitProvenance {
855 commit: parts[0].to_owned(),
856 parents,
857 author_name: parts[2].to_owned(),
858 author_email: parts[3].to_owned(),
859 committer_name: parts[4].to_owned(),
860 committer_email: parts[5].to_owned(),
861 message,
862 })
863}
864
865pub async fn commit_all(worktree: &Path, message: &str) -> Result<bool> {
872 if git(worktree, &["status", "--porcelain"]).await?.is_empty() {
873 return Ok(false);
874 }
875 git(worktree, &["add", "-A"]).await?;
876 if !crate::worktree_setup::withheld_paths(worktree)
878 .await
879 .is_empty()
880 {
881 crate::worktree_setup::unstage_products(worktree).await?;
882 if git_raw(worktree, &["diff", "--cached", "--quiet"])
883 .await?
884 .ok()
885 {
886 return Ok(false);
887 }
888 }
889 let user_name = format!("user.name={NEUTRAL_IDENTITY_NAME}");
890 let user_email = format!("user.email={NEUTRAL_IDENTITY_EMAIL}");
891 let out = git_raw(
892 worktree,
893 &[
894 "-c",
895 &user_name,
896 "-c",
897 &user_email,
898 "commit",
899 "--no-verify",
900 "-m",
901 message,
902 ],
903 )
904 .await?;
905 if !out.ok() {
906 bail!("rescue commit failed: {}", out.stderr);
907 }
908 Ok(true)
909}
910
911#[derive(Debug, Clone, PartialEq, Eq)]
914pub struct Stray {
915 pub path: String,
917 pub manager: String,
919 pub kept_by: String,
922}
923
924#[derive(Debug, Default)]
926pub struct Rescue {
927 pub committed: bool,
929 pub withheld: Vec<Stray>,
931}
932
933fn lock_kind(name: &str) -> Option<(&'static str, &'static str)> {
935 Some(match name {
936 "package-lock.json" | "npm-shrinkwrap.json" => ("node", "npm"),
937 "yarn.lock" => ("node", "yarn"),
938 "pnpm-lock.yaml" => ("node", "pnpm"),
939 "bun.lock" | "bun.lockb" => ("node", "bun"),
940 "poetry.lock" => ("python", "poetry"),
941 "uv.lock" => ("python", "uv"),
942 "Pipfile.lock" => ("python", "pipenv"),
943 "pdm.lock" => ("python", "pdm"),
944 "Cargo.lock" => ("rust", "cargo"),
945 _ => return None,
946 })
947}
948
949fn split_dir(path: &str) -> (&str, &str) {
950 path.rsplit_once('/').unwrap_or(("", path))
951}
952
953pub fn stray_lockfiles(untracked: &[String], tracked: &[String]) -> Vec<Stray> {
961 let mut out = Vec::new();
962 for path in untracked {
963 let (dir, name) = split_dir(path);
964 let Some((eco, manager)) = lock_kind(name) else {
965 continue;
966 };
967 let beside = |other: &String| split_dir(other).0 == dir;
968 let kept_by = if manager == "cargo" {
969 let has_manifest = tracked
970 .iter()
971 .chain(untracked)
972 .any(|p| beside(p) && split_dir(p).1 == "Cargo.toml");
973 if has_manifest {
974 continue;
975 }
976 "no Cargo.toml in the directory".to_owned()
977 } else {
978 let Some(other) = tracked.iter().find(|p| {
979 beside(p)
980 && lock_kind(split_dir(p).1).is_some_and(|(e, m)| e == eco && m != manager)
981 }) else {
982 continue;
983 };
984 other.clone()
985 };
986 out.push(Stray {
987 path: path.clone(),
988 manager: manager.to_owned(),
989 kept_by,
990 });
991 }
992 out
993}
994
995async fn nul_list(worktree: &Path, args: &[&str]) -> Result<Vec<String>> {
996 let out = git(worktree, args).await?;
997 Ok(out
998 .split('\0')
999 .filter(|s| !s.is_empty())
1000 .map(str::to_owned)
1001 .collect())
1002}
1003
1004pub async fn snapshot_uncommitted(worktree: &Path, destination: &Path) -> Result<()> {
1008 if destination.exists() {
1009 if destination.join("complete").exists() {
1010 return Ok(());
1011 }
1012 bail!("earlier recovery snapshot is incomplete; retain original worktree");
1013 }
1014 std::fs::create_dir_all(destination)?;
1015 for (name, args) in [
1016 ("status.txt", vec!["status", "--porcelain=v1"]),
1017 ("staged.patch", vec!["diff", "--binary", "--cached"]),
1018 ("unstaged.patch", vec!["diff", "--binary"]),
1019 ] {
1020 let out = Command::new("git")
1023 .args(&args)
1024 .current_dir(worktree)
1025 .quiet()
1026 .stdin(Stdio::null())
1027 .output()
1028 .await?;
1029 if !out.status.success() {
1030 bail!(
1031 "recovery snapshot failed: {}",
1032 String::from_utf8_lossy(&out.stderr)
1033 );
1034 }
1035 std::fs::write(destination.join(name), out.stdout)?;
1036 }
1037 let paths = nul_list(
1038 worktree,
1039 &["ls-files", "-z", "--others", "--exclude-standard"],
1040 )
1041 .await?;
1042 for name in paths {
1043 let relative = Path::new(&name);
1044 if relative
1045 .components()
1046 .any(|c| !matches!(c, std::path::Component::Normal(_)))
1047 {
1048 bail!("unsafe recovery path");
1049 }
1050 let source = worktree.join(relative);
1051 let target = destination.join("untracked").join(relative);
1052 std::fs::create_dir_all(target.parent().context("untracked recovery parent")?)?;
1053 if std::fs::symlink_metadata(&source)?.file_type().is_symlink() {
1054 bail!("untracked symlink requires manual recovery: {name}");
1056 }
1057 std::fs::copy(source, target)?;
1058 }
1059 std::fs::write(destination.join("complete"), "snapshot captured\n")?;
1060 Ok(())
1061}
1062
1063pub async fn rescue_commit(worktree: &Path, message: &str) -> Result<Rescue> {
1069 if git(worktree, &["status", "--porcelain"]).await?.is_empty() {
1070 return Ok(Rescue::default());
1071 }
1072 let untracked = nul_list(
1073 worktree,
1074 &["ls-files", "-z", "--others", "--exclude-standard"],
1075 )
1076 .await?;
1077 let tracked = nul_list(worktree, &["ls-files", "-z"]).await?;
1078 let withheld = stray_lockfiles(&untracked, &tracked);
1079
1080 git(worktree, &["add", "-A"]).await?;
1081 if !withheld.is_empty() {
1082 let mut args = vec!["reset", "-q", "--"];
1083 args.extend(withheld.iter().map(|s| s.path.as_str()));
1084 git(worktree, &args).await?;
1085 }
1086 crate::worktree_setup::unstage_products(worktree).await?;
1087 if git_raw(worktree, &["diff", "--cached", "--quiet"])
1088 .await?
1089 .ok()
1090 {
1091 return Ok(Rescue {
1092 committed: false,
1093 withheld,
1094 });
1095 }
1096 let out = git_raw(
1097 worktree,
1098 &[
1099 "-c",
1100 "user.name=magi candidate",
1101 "-c",
1102 "user.email=magi@localhost",
1103 "commit",
1104 "--no-verify",
1105 "-m",
1106 message,
1107 ],
1108 )
1109 .await?;
1110 if !out.ok() {
1111 bail!("rescue commit failed: {}", out.stderr);
1112 }
1113 Ok(Rescue {
1114 committed: true,
1115 withheld,
1116 })
1117}
1118
1119pub async fn enable_worktree_config(repo: &Path) -> Result<bool> {
1124 let out = git_raw(repo, &["config", "--get", "extensions.worktreeConfig"]).await?;
1125 if out.ok() && out.stdout.trim() == "true" {
1126 return Ok(false);
1127 }
1128 git(repo, &["config", "extensions.worktreeConfig", "true"]).await?;
1129 Ok(true)
1130}
1131
1132pub async fn disable_worktree_config(repo: &Path) -> Result<()> {
1134 git_raw(repo, &["config", "--unset", "extensions.worktreeConfig"]).await?;
1135 Ok(())
1136}
1137
1138struct WorktreeConfigRef {
1141 count: usize,
1143 we_enabled: bool,
1149}
1150
1151static WORKTREE_CONFIG: std::sync::LazyLock<
1158 std::sync::Mutex<
1159 std::collections::HashMap<PathBuf, std::sync::Arc<tokio::sync::Mutex<WorktreeConfigRef>>>,
1160 >,
1161> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
1162
1163fn worktree_config_slot(repo: &Path) -> std::sync::Arc<tokio::sync::Mutex<WorktreeConfigRef>> {
1165 let mut map = WORKTREE_CONFIG
1166 .lock()
1167 .unwrap_or_else(std::sync::PoisonError::into_inner);
1168 map.entry(repo.to_path_buf())
1169 .or_insert_with(|| {
1170 std::sync::Arc::new(tokio::sync::Mutex::new(WorktreeConfigRef {
1171 count: 0,
1172 we_enabled: false,
1173 }))
1174 })
1175 .clone()
1176}
1177
1178pub async fn acquire_worktree_config(repo: &Path) -> Result<()> {
1195 let slot = worktree_config_slot(repo);
1196 let mut entry = slot.lock().await;
1197 entry.count += 1;
1198 if entry.count == 1 {
1199 entry.we_enabled = enable_worktree_config(repo).await?;
1200 }
1201 Ok(())
1202}
1203
1204pub async fn release_worktree_config(repo: &Path) -> Result<()> {
1210 let slot = worktree_config_slot(repo);
1211 let mut entry = slot.lock().await;
1212 entry.count = entry.count.saturating_sub(1);
1213 if entry.count == 0 && entry.we_enabled {
1214 disable_worktree_config(repo).await?;
1215 entry.we_enabled = false;
1216 }
1217 Ok(())
1218}
1219
1220pub async fn set_worktree_hooks_path(worktree: &Path, hooks_dir: &Path) -> Result<()> {
1226 let dir = path_arg(hooks_dir);
1227 git(worktree, &["config", "--worktree", "core.hooksPath", &dir])
1228 .await
1229 .map(|_| ())
1230}
1231
1232pub async fn local_exclude(worktree: &Path, pattern: &str) -> Result<()> {
1234 let git_dir = git(worktree, &["rev-parse", "--git-path", "info/exclude"]).await?;
1235 let path = worktree.join(git_dir);
1236 if let Some(parent) = path.parent() {
1237 tokio::fs::create_dir_all(parent).await.ok();
1238 }
1239 let mut body = tokio::fs::read_to_string(&path).await.unwrap_or_default();
1240 if body.lines().any(|l| l.trim() == pattern) {
1241 return Ok(());
1242 }
1243 if !body.is_empty() && !body.ends_with('\n') {
1244 body.push('\n');
1245 }
1246 body.push_str(pattern);
1247 body.push('\n');
1248 tokio::fs::write(&path, body)
1249 .await
1250 .with_context(|| format!("write {}", path.display()))?;
1251 Ok(())
1252}
1253
1254pub async fn merge_no_ff(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
1260 git_raw(
1261 repo,
1262 &["merge", "--no-ff", "--no-edit", "-m", message, branch],
1263 )
1264 .await
1265}
1266
1267pub async fn merge_squash(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
1278 let staged = git_raw(repo, &["merge", "--squash", branch]).await?;
1279 if !staged.ok() {
1280 return Ok(staged);
1281 }
1282 git_raw(repo, &["commit", "-m", message]).await
1283}
1284
1285pub async fn merge_ff_only(repo: &Path, branch: &str) -> Result<GitOut> {
1295 git_raw(repo, &["merge", "--ff-only", branch]).await
1296}
1297
1298pub async fn push(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
1300 git_raw(repo, &["push", "-u", remote, branch]).await
1301}
1302
1303pub async fn push_as(
1306 repo: &Path,
1307 remote: &str,
1308 local: &str,
1309 head: &str,
1310 expected: &str,
1311) -> Result<GitOut> {
1312 let lease = format!("--force-with-lease=refs/heads/{head}:{expected}");
1313 let refspec = format!("refs/heads/{local}:refs/heads/{head}");
1314 git_raw(repo, &["push", &lease, remote, &refspec]).await
1315}
1316
1317pub async fn remote_head(repo: &Path, remote: &str, branch: &str) -> Result<Option<String>> {
1319 let reference = format!("refs/heads/{branch}");
1320 let out = git(repo, &["ls-remote", "--refs", remote, &reference]).await?;
1321 Ok(out.split_whitespace().next().map(str::to_owned))
1322}
1323
1324pub async fn push_rewritten(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
1332 git_raw(repo, &["push", "--force-with-lease", remote, branch]).await
1333}
1334
1335pub async fn push_pinned(
1344 repo: &Path,
1345 remote: &str,
1346 branch: &str,
1347 expected: &str,
1348) -> Result<GitOut> {
1349 let lease = format!("--force-with-lease=refs/heads/{branch}:{expected}");
1350 let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1351 git_raw(repo, &["push", &lease, remote, &refspec]).await
1352}
1353
1354pub async fn cherry(repo: &Path, upstream: &str, head: &str) -> Result<(Vec<String>, Vec<String>)> {
1357 let out = git(repo, &["cherry", upstream, head]).await?;
1358 let (mut unmatched, mut matched) = (Vec::new(), Vec::new());
1359 for line in out.lines() {
1360 if let Some(sha) = line.strip_prefix("+ ") {
1361 unmatched.push(sha.trim().to_owned());
1362 } else if let Some(sha) = line.strip_prefix("- ") {
1363 matched.push(sha.trim().to_owned());
1364 }
1365 }
1366 Ok((unmatched, matched))
1367}
1368
1369#[derive(Debug)]
1371pub struct RebaseRecord {
1372 pub picks: Vec<String>,
1374 pub heads: Vec<String>,
1376}
1377
1378pub(crate) const REBASE_EXEC: &str =
1379 "git rev-parse HEAD >> \"$(git rev-parse --git-path magi-rebase-heads)\"";
1380
1381const REBASE_PICKS_PENDING: &str = "magi-rebase-picks-pending";
1382
1383async fn rebase_file(scratch: &Path, name: &str) -> Result<PathBuf> {
1384 let path = git(scratch, &["rev-parse", "--git-path", name]).await?;
1385 let path = Path::new(path.trim());
1386 Ok(if path.is_absolute() {
1387 path.to_path_buf()
1388 } else {
1389 scratch.join(path)
1390 })
1391}
1392
1393pub(crate) async fn check_rebase_preparation(
1395 state: &crate::run::RunState,
1396 head: &str,
1397 dir: &Path,
1398) -> Result<()> {
1399 let winner = state.winner().context("missing retained winner")?;
1400 let common = crate::repo_lock::common_dir(&state.repo).await?;
1401 ensure!(
1402 common.is_some() && common == crate::repo_lock::common_dir(&winner.worktree).await?,
1403 "retained worktree repository changed"
1404 );
1405 ensure!(
1406 !dir.join("base-sync").try_exists()?,
1407 "retained scratch exists; inspect it before recovery"
1408 );
1409 let scratch = path_arg(&dir.join("base-sync"));
1410 let listing = git(&state.repo, &["worktree", "list", "--porcelain", "-z"]).await?;
1411 ensure!(
1412 !listing
1413 .split('\0')
1414 .filter_map(|line| line.strip_prefix("worktree "))
1415 .any(|path| {
1416 if cfg!(windows) {
1417 path.eq_ignore_ascii_case(&scratch)
1418 } else {
1419 path == scratch
1420 }
1421 }),
1422 "retained scratch Git registration exists; inspect it before recovery"
1423 );
1424 for name in [
1425 "rebase-merge",
1426 "rebase-apply",
1427 "MERGE_HEAD",
1428 "CHERRY_PICK_HEAD",
1429 "REVERT_HEAD",
1430 "sequencer",
1431 "index.lock",
1432 ] {
1433 ensure!(
1434 !rebase_file(&winner.worktree, name).await?.try_exists()?,
1435 "retained Git operation: {name}"
1436 );
1437 }
1438 ensure!(
1439 is_clean(&winner.worktree).await?,
1440 "retained worktree changed"
1441 );
1442 ensure!(
1443 current_branch(&winner.worktree).await?.as_deref() == Some(winner.branch.as_str()),
1444 "retained worktree branch changed"
1445 );
1446 ensure!(
1447 rev_parse(&winner.worktree, "HEAD").await? == head
1448 && rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch)).await? == head,
1449 "retained HEAD changed"
1450 );
1451 Ok(())
1452}
1453
1454pub(crate) async fn probe_rebase_preparation(
1457 state: &crate::run::RunState,
1458 head: &str,
1459 dir: &Path,
1460 wait: &crate::repo_lock::WaitPolicy,
1461) -> Result<()> {
1462 let _lease = crate::repo_lock::SeatLease::operation_with(
1463 &state.repo,
1464 state.config.coordination.as_ref(),
1465 wait,
1466 )
1467 .await?;
1468 check_rebase_preparation(state, head, dir).await?;
1469 let scratch = dir.join(format!(
1470 "base-sync-probe-{}-{:016x}",
1471 std::process::id(),
1472 crate::rng::entropy()
1473 ));
1474 ensure!(
1475 !scratch.try_exists()?,
1476 "previous preparation probe requires inspection"
1477 );
1478 worktree_add_detached(&state.repo, &scratch, head).await?;
1479 let result = initialize_rebase_record(&scratch).await;
1480 let removed = worktree_remove_clean(&state.repo, &scratch).await?;
1481 result?;
1482 ensure!(
1483 removed && !scratch.try_exists()?,
1484 "preparation probe cleanup failed"
1485 );
1486 Ok(())
1487}
1488
1489async fn full_commit(scratch: &Path, sha: &str) -> Result<String> {
1490 anyhow::ensure!(
1491 !sha.is_empty() && sha.bytes().all(|b| b.is_ascii_hexdigit()),
1492 "invalid rebase commit id: {sha}"
1493 );
1494 rev_parse(scratch, &format!("{sha}^{{commit}}")).await
1495}
1496
1497enum Instruction<'a> {
1498 Pick(&'a str),
1499 Record,
1500}
1501
1502fn instructions<'a>(
1503 text: &'a str,
1504 exec: &'a str,
1505) -> impl DoubleEndedIterator<Item = Result<Instruction<'a>>> {
1506 text.lines()
1507 .map(str::trim)
1508 .filter(|line| !line.is_empty() && !line.starts_with('#'))
1509 .map(move |line| match line.split_once(' ') {
1510 Some(("pick" | "p", args)) => Ok(Instruction::Pick(
1511 args.split_whitespace()
1512 .next()
1513 .context("pick without commit")?,
1514 )),
1515 Some(("exec" | "x", command)) if command == exec => Ok(Instruction::Record),
1516 _ => bail!("unexpected rebase instruction: {line}"),
1517 })
1518}
1519
1520pub(crate) async fn stopped_pick(scratch: &Path) -> Result<Option<String>> {
1523 stopped_pick_with_exec(scratch, REBASE_EXEC).await
1524}
1525
1526async fn stopped_pick_with_exec(scratch: &Path, exec: &str) -> Result<Option<String>> {
1527 let done = std::fs::read_to_string(rebase_file(scratch, "rebase-merge/done").await?)?;
1528 let mut steps = instructions(&done, exec);
1529 let Some(Instruction::Pick(id)) = steps.next_back().transpose()? else {
1530 return Ok(None);
1531 };
1532 let pick = full_commit(scratch, id).await?;
1533 ensure!(
1534 rev_parse(scratch, "REBASE_HEAD^{commit}").await? == pick,
1535 "REBASE_HEAD does not match the stopped pick"
1536 );
1537 let saved = std::fs::read_to_string(rebase_file(scratch, "magi-rebase-picks").await?)?;
1538 let mut picks = saved.lines();
1539 for step in steps {
1540 if let Instruction::Pick(id) = step? {
1541 ensure!(
1542 picks.next().is_some_and(|sha| sha.starts_with(id)),
1543 "completed picks do not match the saved replay"
1544 );
1545 }
1546 }
1547 ensure!(
1548 picks.next() == Some(pick.as_str()),
1549 "stopped pick does not match its position in the saved replay"
1550 );
1551 Ok(Some(pick))
1552}
1553
1554async fn save_rebase_picks(scratch: &Path, exec: &str) -> Result<()> {
1557 let mut picks = Vec::new();
1558 for name in ["rebase-merge/done", "rebase-merge/git-rebase-todo"] {
1559 let text = std::fs::read_to_string(rebase_file(scratch, name).await?)?;
1560 for step in instructions(&text, exec) {
1561 if let Instruction::Pick(id) = step? {
1562 picks.push(full_commit(scratch, id).await?);
1563 }
1564 }
1565 }
1566 let path = rebase_file(scratch, "magi-rebase-picks").await?;
1567 let tmp = path.with_extension("tmp");
1568 std::fs::write(&tmp, picks.join("\n") + "\n")?;
1569 std::fs::rename(tmp, path)?;
1570 Ok(())
1571}
1572
1573pub(crate) async fn finish_rebase_pick_capture(scratch: &Path, exec: &str) -> Result<()> {
1576 let pending = rebase_file(scratch, REBASE_PICKS_PENDING).await?;
1577 match pending.symlink_metadata() {
1578 Ok(meta) => ensure!(meta.is_file(), "invalid pick capture marker"),
1579 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
1580 Err(e) => return Err(e).context("inspect pick capture marker"),
1581 }
1582 let ledger = pending.with_file_name("magi-rebase-picks");
1583 match ledger.symlink_metadata() {
1584 Ok(meta) => ensure!(meta.is_file(), "invalid pick ledger"),
1585 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1586 save_rebase_picks(scratch, exec).await?;
1587 }
1588 Err(e) => return Err(e).context("inspect pick ledger"),
1589 }
1590 std::fs::remove_file(pending).context("finish pick capture")
1591}
1592
1593pub(crate) async fn claim_recording_retry(
1597 repo: &Path,
1598 scratch: &Path,
1599 branch: &str,
1600 original: &str,
1601 onto_sha: &str,
1602 owner_retry: Option<u64>,
1603 exec: &str,
1604) -> Result<()> {
1605 let admin = rebase_scratch_admin(repo, scratch).await?;
1606 let seq = admin.join("rebase-merge");
1607 let read = |path: PathBuf| -> Result<String> {
1608 ensure!(
1609 path.symlink_metadata()?.is_file(),
1610 "not a regular file: {}",
1611 path.display()
1612 );
1613 std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))
1614 };
1615 let branch_ref = format!("refs/heads/{branch}");
1616 ensure!(
1617 seq.symlink_metadata()?.is_dir()
1618 && seq
1619 .join("reschedule-failed-exec")
1620 .symlink_metadata()?
1621 .is_file()
1622 && read(seq.join("head-name"))?.trim_end() == branch_ref
1623 && read(seq.join("orig-head"))?.trim_end() == original
1624 && read(seq.join("onto"))?.trim_end() == onto_sha
1625 && rev_parse(repo, &branch_ref).await? == original
1626 && git_raw(scratch, &["symbolic-ref", "-q", "HEAD"])
1627 .await?
1628 .code
1629 == Some(1),
1630 "scratch rebase does not match the reserved operation"
1631 );
1632 let automatic = admin.join("magi-rebase-recording-retry");
1633 let (marker, previously_retried) = match owner_retry {
1634 Some(generation) => match automatic.symlink_metadata() {
1635 Ok(meta) => {
1636 ensure!(meta.is_file(), "invalid automatic retry marker");
1637 (
1638 admin.join(format!("magi-rebase-recording-retry-{generation}")),
1639 true,
1640 )
1641 }
1642 Err(e) if e.kind() == std::io::ErrorKind::NotFound => (automatic, false),
1644 Err(e) => return Err(e).context("inspect automatic retry marker"),
1645 },
1646 None => (automatic, false),
1647 };
1648 ensure!(!marker.try_exists()?, "recording retry already spent");
1649 ensure!(
1650 git(scratch, &["status", "--porcelain", "--untracked-files=all"])
1651 .await?
1652 .is_empty(),
1653 "scratch has uncommitted changes"
1654 );
1655
1656 let saved = read(admin.join("magi-rebase-picks"))?;
1657 ensure!(saved.ends_with('\n'), "incomplete saved pick ledger");
1658 let mut picks = saved.lines();
1659 let mut done_picks = 0;
1660 for (file, done) in [("done", true), ("git-rebase-todo", false)] {
1661 let text = read(seq.join(file))?;
1662 let mut steps = instructions(&text, exec).peekable();
1663 if !done {
1666 ensure!(
1667 matches!(steps.next().transpose()?, Some(Instruction::Record)),
1668 "the recording exec was not rescheduled"
1669 );
1670 }
1671 while let Some(step) = steps.next() {
1672 let Instruction::Pick(sha) = step? else {
1673 bail!("expected a pick in {file}");
1674 };
1675 let pick = full_commit(scratch, sha).await?;
1676 ensure!(
1677 picks.next() == Some(pick.as_str())
1678 && is_ancestor(repo, &pick, original).await
1679 && matches!(steps.next().transpose()?, Some(Instruction::Record)),
1680 "{file} does not match the saved pick/exec sequence"
1681 );
1682 done_picks += usize::from(done);
1683 if done && previously_retried {
1684 while steps
1685 .next_if(|step| matches!(step, Ok(Instruction::Record)))
1686 .is_some()
1687 {}
1688 }
1689 }
1690 }
1691 ensure!(
1692 picks.next().is_none() && done_picks > 0,
1693 "incomplete pick sequence"
1694 );
1695
1696 let heads = read(admin.join("magi-rebase-heads"))?;
1697 ensure!(
1698 (heads.is_empty() || heads.ends_with('\n')) && heads.lines().count() == done_picks - 1,
1699 "cannot prove the failed exec has not already recorded a HEAD"
1700 );
1701 let head = rev_parse(scratch, "HEAD^{commit}").await?;
1702 let mut previous = onto_sha;
1703 for sha in heads.lines().chain(std::iter::once(head.as_str())) {
1704 ensure!(
1705 sha.len() == head.len() && sha.bytes().all(|b| b.is_ascii_hexdigit()),
1706 "partial or invalid recorded HEAD"
1707 );
1708 if sha != previous {
1709 ensure!(
1710 git(scratch, &["rev-list", "--parents", "-1", sha]).await?
1711 == format!("{sha} {previous}"),
1712 "recorded HEADs and scratch HEAD are not a replay onto the reserved target"
1713 );
1714 }
1715 previous = sha;
1716 }
1717 std::fs::File::create_new(marker)
1718 .context("cannot claim recording retry (already spent or scratch unwritable)")?
1719 .sync_all()?;
1720 Ok(())
1721}
1722
1723pub(crate) async fn rebase_scratch_admin(repo: &Path, scratch: &Path) -> Result<PathBuf> {
1725 let common = crate::repo_lock::common_dir(repo)
1726 .await?
1727 .context("not a repository")?;
1728 let admin = std::fs::canonicalize(git(scratch, &["rev-parse", "--absolute-git-dir"]).await?)?;
1729 let backlink = std::fs::read_to_string(admin.join("gitdir"))?;
1730 ensure!(
1731 admin.parent() == Some(common.join("worktrees").as_path())
1732 && admin.join(backlink.trim_end()).canonicalize()?
1733 == scratch.join(".git").canonicalize()?,
1734 "not a scratch worktree of the reserved repository"
1735 );
1736 Ok(admin)
1737}
1738
1739pub async fn rebase_record(scratch: &Path) -> Result<RebaseRecord> {
1741 let mut lists = Vec::new();
1742 for name in ["magi-rebase-picks", "magi-rebase-heads"] {
1743 let text = std::fs::read_to_string(rebase_file(scratch, name).await?)
1744 .with_context(|| format!("read {name}"))?;
1745 let mut commits = Vec::new();
1746 for sha in text.lines() {
1747 let full = full_commit(scratch, sha).await?;
1748 anyhow::ensure!(full == sha, "non-full commit id in {name}");
1749 commits.push(full);
1750 }
1751 lists.push(commits);
1752 }
1753 let heads = lists.pop().unwrap();
1754 let picks = lists.pop().unwrap();
1755 anyhow::ensure!(
1756 !picks.is_empty() && picks.len() == heads.len(),
1757 "rebase pick/HEAD count mismatch"
1758 );
1759 Ok(RebaseRecord { picks, heads })
1760}
1761
1762pub fn rebase_said(text: &str) -> String {
1764 text.trim()
1765 .split(['\r', '\n'])
1766 .filter(|line| !line.trim_start().starts_with("Executing:"))
1767 .collect::<Vec<_>>()
1768 .join("\n")
1769}
1770
1771#[derive(Debug, Clone, PartialEq, Eq)]
1773pub enum RebaseStart {
1774 Applied,
1777 Conflicted(String),
1780 Sequencer(String),
1783 Failed(String),
1786}
1787
1788pub async fn rebase_start(
1803 repo: &Path,
1804 scratch: &Path,
1805 branch: &str,
1806 onto: &str,
1807) -> Result<RebaseStart> {
1808 rebase_prepare(repo, scratch, branch).await?;
1809 rebase_execute(repo, scratch, onto, REBASE_EXEC).await
1810}
1811
1812#[derive(Debug)]
1814pub struct RebasePreparationError(pub String);
1815
1816impl std::fmt::Display for RebasePreparationError {
1817 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1818 f.write_str(&self.0)
1819 }
1820}
1821
1822impl std::error::Error for RebasePreparationError {}
1823
1824async fn initialize_rebase_record(scratch: &Path) -> Result<()> {
1825 std::fs::write(rebase_file(scratch, "magi-rebase-heads").await?, "")?;
1826 Ok(())
1827}
1828
1829pub(crate) async fn rebase_prepare(repo: &Path, scratch: &Path, branch: &str) -> Result<()> {
1832 if checked_rebase_in_progress(scratch).await? {
1833 return Ok(());
1834 }
1835 let result = async {
1836 worktree_remove(repo, scratch).await.ok();
1837 let path = path_arg(scratch);
1838 let args = ["worktree", "add", "--force", &path, branch];
1839 let out = git_raw(repo, &args).await?;
1840 ensure!(
1841 out.ok(),
1842 "git {} (exit {:?}): {}",
1843 args.join(" "),
1844 out.code,
1845 if out.stderr.trim().is_empty() {
1846 &out.stdout
1847 } else {
1848 &out.stderr
1849 }
1850 );
1851 initialize_rebase_record(scratch).await
1852 }
1853 .await;
1854 result.map_err(|e| {
1855 RebasePreparationError(format!(
1856 "prepare rebase scratch {}: {e:#}",
1857 scratch.display()
1858 ))
1859 .into()
1860 })
1861}
1862
1863pub(crate) async fn rebase_execute(
1865 repo: &Path,
1866 scratch: &Path,
1867 onto: &str,
1868 exec: &str,
1869) -> Result<RebaseStart> {
1870 std::fs::File::create_new(rebase_file(scratch, REBASE_PICKS_PENDING).await?)?.sync_all()?;
1871 let out = git_raw(
1872 scratch,
1873 &[
1874 "rebase",
1875 "--empty=drop",
1876 "--reschedule-failed-exec",
1877 "--exec",
1878 exec,
1879 onto,
1880 ],
1881 )
1882 .await?;
1883 if out.ok() {
1884 worktree_remove(repo, scratch).await.ok();
1885 return Ok(RebaseStart::Applied);
1886 }
1887 let why = rebase_said(&format!("{}\n{}", out.stderr, out.stdout));
1888 if checked_rebase_in_progress(scratch)
1889 .await
1890 .with_context(|| format!("{why}\ncannot read scratch rebase state"))?
1891 {
1892 finish_rebase_pick_capture(scratch, exec)
1893 .await
1894 .with_context(|| format!("{why}\ncannot record rebase picks"))?;
1895 return Ok(match unmerged_paths(scratch).await {
1896 Ok(paths) if paths.is_empty() => RebaseStart::Sequencer(why),
1897 Err(e) => RebaseStart::Sequencer(format!("{why}\ncannot read unmerged paths: {e:#}")),
1898 Ok(_) => match stopped_pick_with_exec(scratch, exec).await {
1899 Ok(Some(_)) => RebaseStart::Conflicted(why),
1900 Ok(None) => RebaseStart::Sequencer(why),
1901 Err(e) => {
1902 RebaseStart::Sequencer(format!("{why}\ncannot identify stopped pick: {e:#}"))
1903 }
1904 },
1905 });
1906 }
1907 worktree_remove(repo, scratch).await.ok();
1908 Ok(RebaseStart::Failed(why))
1909}
1910
1911pub async fn rebase_in_progress(worktree: &Path) -> bool {
1913 checked_rebase_in_progress(worktree).await.unwrap_or(false)
1914}
1915
1916pub(crate) async fn checked_rebase_in_progress(worktree: &Path) -> Result<bool> {
1918 match worktree.symlink_metadata() {
1919 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
1920 result => ensure!(
1921 result?.is_dir(),
1922 "not a worktree directory: {}",
1923 worktree.display()
1924 ),
1925 }
1926 let backlink = worktree.join(".git");
1928 backlink
1929 .symlink_metadata()
1930 .with_context(|| format!("inspect scratch Git backlink {}", backlink.display()))?;
1931 for name in ["rebase-merge", "rebase-apply"] {
1932 let path = rebase_file(worktree, name).await?;
1933 match path.symlink_metadata() {
1934 Ok(meta) if meta.is_dir() => return Ok(true),
1935 Ok(_) => bail!("not a sequencer directory: {}", path.display()),
1936 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1937 Err(e) => return Err(e).with_context(|| format!("inspect {}", path.display())),
1938 }
1939 }
1940 Ok(false)
1941}
1942
1943pub async fn unmerged_paths(worktree: &Path) -> Result<Vec<String>> {
1945 let out = git(worktree, &["diff", "--name-only", "--diff-filter=U", "-z"]).await?;
1946 Ok(out
1947 .split('\0')
1948 .filter(|l| !l.is_empty())
1949 .map(str::to_owned)
1950 .collect())
1951}
1952
1953pub async fn rebase_abort(repo: &Path, scratch: &Path) {
1956 git_raw(scratch, &["rebase", "--abort"]).await.ok();
1957 worktree_remove(repo, scratch).await.ok();
1958}
1959
1960pub async fn rebase_branch_in_temp(
1968 repo: &Path,
1969 scratch: &Path,
1970 branch: &str,
1971 onto: &str,
1972) -> Result<Option<String>> {
1973 match rebase_start(repo, scratch, branch, onto).await? {
1974 RebaseStart::Applied => Ok(None),
1975 RebaseStart::Failed(why) => Ok(Some(why)),
1976 RebaseStart::Conflicted(why) | RebaseStart::Sequencer(why) => {
1977 rebase_abort(repo, scratch).await;
1978 Ok(Some(why))
1979 }
1980 }
1981}
1982
1983pub async fn sync_to_head(worktree: &Path) -> Result<()> {
1996 reset_hard_head(worktree).await?;
1997 clean_all(worktree).await
1998}
1999
2000pub async fn reset_hard_head(worktree: &Path) -> Result<()> {
2002 git(worktree, &["reset", "--hard", "HEAD"])
2003 .await
2004 .map(|_| ())
2005}
2006
2007pub async fn clean_all(worktree: &Path) -> Result<()> {
2009 git(worktree, &["clean", "-fdx"]).await.map(|_| ())
2010}
2011
2012pub async fn fetch(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
2031 let refspec = format!("+refs/heads/{branch}:refs/remotes/{remote}/{branch}");
2032 git_raw(repo, &["fetch", "--quiet", remote, &refspec]).await
2033}
2034
2035pub async fn merge_base(repo: &Path, a: &str, b: &str) -> Result<String> {
2037 Ok(git(repo, &["merge-base", a, b]).await?.trim().to_owned())
2038}
2039
2040pub async fn is_ancestor(repo: &Path, ancestor: &str, of: &str) -> bool {
2042 git_raw(repo, &["merge-base", "--is-ancestor", ancestor, of])
2043 .await
2044 .is_ok_and(|o| o.ok())
2045}
2046
2047pub async fn ancestry(repo: &Path, ancestor: &str, of: &str) -> Result<bool> {
2052 let out = git_raw(repo, &["merge-base", "--is-ancestor", ancestor, of]).await?;
2053 match out.code {
2054 Some(0) => Ok(true),
2055 Some(1) => Ok(false),
2056 _ => bail!(
2057 "git merge-base --is-ancestor {ancestor} {of} failed ({}): {}",
2058 crate::notices::exit_status(out.code),
2059 out.stderr
2060 ),
2061 }
2062}
2063
2064pub async fn commit_of(repo: &Path, rev: &str) -> Option<String> {
2066 let spec = format!("{rev}^{{commit}}");
2067 let out = git_raw(repo, &["rev-parse", "--verify", "--quiet", &spec])
2068 .await
2069 .ok()?;
2070 (out.ok() && !out.stdout.is_empty()).then_some(out.stdout)
2071}
2072
2073pub async fn branches_containing(repo: &Path, commit: &str) -> Result<Vec<String>> {
2075 let out = git(
2076 repo,
2077 &[
2078 "branch",
2079 "-a",
2080 "--contains",
2081 commit,
2082 "--format=%(refname:short)",
2083 ],
2084 )
2085 .await?;
2086 Ok(out
2087 .lines()
2088 .map(str::trim)
2089 .filter(|l| !l.is_empty() && !l.ends_with("/HEAD") && !l.contains("HEAD detached"))
2090 .map(str::to_owned)
2091 .collect())
2092}
2093
2094pub async fn cherry_pick(worktree: &Path, commit: &str) -> Result<()> {
2098 let out = git_raw(
2099 worktree,
2100 &[
2101 "-c",
2102 "user.name=magi candidate",
2103 "-c",
2104 "user.email=magi@localhost",
2105 "cherry-pick",
2106 "-x",
2107 commit,
2108 ],
2109 )
2110 .await?;
2111 if out.ok() {
2112 return Ok(());
2113 }
2114 let _ = git_raw(worktree, &["cherry-pick", "--abort"]).await;
2115 bail!(
2116 "cherry-pick of {commit} failed: {}",
2117 if out.stderr.is_empty() {
2118 out.stdout
2119 } else {
2120 out.stderr
2121 }
2122 )
2123}
2124
2125pub async fn tree_of(repo: &Path, rev: &str) -> Result<String> {
2127 git(repo, &["rev-parse", &format!("{rev}^{{tree}}")]).await
2128}
2129
2130pub async fn rev_exists(repo: &Path, rev: &str) -> bool {
2132 git_raw(repo, &["rev-parse", "--verify", "--quiet", rev])
2133 .await
2134 .is_ok_and(|o| o.ok())
2135}
2136
2137#[cfg(test)]
2138mod tests {
2139 #[tokio::test]
2140 async fn checkout_discovery_ignores_inherited_git_target() {
2141 const FIXTURE: &str = "MAGI_TEST_CHECKOUT_DISCOVERY_ROOT";
2142 if let Some(root) = std::env::var_os(FIXTURE) {
2143 let root = std::path::PathBuf::from(root);
2144 let first = root.join("first");
2145 let second = root.join("second");
2146 let plain = root.join("plain");
2147 assert_eq!(
2148 super::toplevel(&second)
2149 .await
2150 .unwrap()
2151 .canonicalize()
2152 .unwrap(),
2153 second.canonicalize().unwrap()
2154 );
2155 assert!(super::toplevel(&plain).await.is_err());
2156 assert!(!super::same_checkout(&first, &second).unwrap());
2157 assert!(super::same_checkout(&first, &plain).is_err());
2158 assert!(super::same_checkout(&first, &first.join("src")).unwrap());
2159 assert!(
2160 super::toplevel(&root.join("bounded/src/nested"))
2161 .await
2162 .is_err()
2163 );
2164 return;
2165 }
2166 let fixture = tempfile::tempdir().unwrap();
2167 let root = fixture.path();
2168 for name in ["first", "second"] {
2169 let checkout = root.join(name);
2170 std::fs::create_dir_all(checkout.join("src")).unwrap();
2171 super::git(&checkout, &["init", "-q"]).await.unwrap();
2172 }
2173 let bounded = root.join("bounded");
2174 std::fs::create_dir_all(bounded.join("src/nested")).unwrap();
2175 super::git(&bounded, &["init", "-q"]).await.unwrap();
2176 std::fs::create_dir(root.join("plain")).unwrap();
2177 let output = std::process::Command::new(std::env::current_exe().unwrap())
2178 .args([
2179 "--exact",
2180 "git::tests::checkout_discovery_ignores_inherited_git_target",
2181 ])
2182 .env(FIXTURE, root)
2183 .env("GIT_DIR", root.join("first/.git"))
2184 .env("GIT_WORK_TREE", root.join("first"))
2185 .env("GIT_CONFIG_COUNT", "1")
2186 .env("GIT_CONFIG_KEY_0", "core.worktree")
2187 .env("GIT_CONFIG_VALUE_0", root.join("first"))
2188 .env(
2189 "GIT_CEILING_DIRECTORIES",
2190 super::path_arg(&bounded.join("src").canonicalize().unwrap()),
2191 )
2192 .output()
2193 .unwrap();
2194 let stdout = String::from_utf8_lossy(&output.stdout);
2195 assert!(
2196 output.status.success() && stdout.contains("1 passed"),
2197 "{stdout}"
2198 );
2199 }
2200
2201 #[test]
2202 fn git_cli_path_spelling_handles_windows_canonical_prefixes() {
2203 for (native, expected) in [
2204 (r"\\?\C:\temp\work tree", "C:/temp/work tree"),
2205 (
2206 r"\\?\UNC\server\share\work tree",
2207 "//server/share/work tree",
2208 ),
2209 (r"C:\temp\work tree", "C:/temp/work tree"),
2210 ("C:/temp/work tree", "C:/temp/work tree"),
2211 ] {
2212 assert_eq!(super::windows_cli_path(native), expected);
2213 }
2214 }
2215
2216 #[test]
2217 fn git_cli_path_spelling_does_not_alias_extended_only_names() {
2218 for path in [
2219 r"\\?\C:\temp.\copy",
2220 r"\\?\C:\temp \copy",
2221 r"\\?\C:\NUL.txt\copy",
2222 r"\\?\C:\COM1\copy",
2223 ] {
2224 assert!(super::windows_cli_path(path).starts_with("//?/"));
2225 }
2226 }
2227
2228 #[cfg(unix)]
2229 #[test]
2230 fn git_cli_path_spelling_preserves_native_paths_on_unix() {
2231 assert_eq!(
2232 super::path_arg(std::path::Path::new(r"/tmp/back\slash")),
2233 r"/tmp/back\slash"
2234 );
2235 }
2236
2237 #[test]
2238 fn git_cli_canonical_output_accepts_platform_spelling_and_rejects_aliases() {
2239 let temp = tempfile::tempdir().unwrap();
2240 let canonical = temp.path().canonicalize().unwrap();
2241 let printed = super::path_arg(&canonical);
2242 assert_eq!(super::canonical_output_path(&printed).unwrap(), canonical);
2243 let noncanonical = format!("{printed}/child/..");
2246 std::fs::create_dir(canonical.join("child")).unwrap();
2247 assert!(super::canonical_output_path(&noncanonical).is_err());
2248 #[cfg(unix)]
2249 {
2250 let alias = canonical.join("alias");
2251 std::os::unix::fs::symlink(canonical.join("child"), &alias).unwrap();
2252 assert!(super::canonical_output_path(alias.to_str().unwrap()).is_err());
2253 }
2254 }
2255
2256 use super::*;
2257
2258 #[tokio::test]
2259 async fn recording_exec_transient_failure() {
2260 recording_exec_fixture(false).await;
2261 }
2262
2263 #[tokio::test]
2264 async fn recording_exec_persistent_failure() {
2265 recording_exec_fixture(true).await;
2266 }
2267
2268 fn shell_script(path: &Path, body: &str) {
2269 std::fs::write(path, body).unwrap();
2270 #[cfg(unix)]
2271 {
2272 use std::os::unix::fs::PermissionsExt as _;
2273 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
2274 }
2275 }
2276
2277 #[tokio::test]
2278 async fn rebase_pick_ledger_publish_failure_can_resume() {
2279 use crate::rebase::{Rebased, SEQUENCER_INFRASTRUCTURE, rebase_prepared_with_exec};
2280 use crate::run::RunState;
2281
2282 crate::run::pin_test_home();
2283 let (_temp, repo) = scratch().await;
2284 let base = rev_parse(&repo, "main").await.unwrap();
2285 sh(&repo, &["checkout", "-qb", "topic"]);
2286 track(&repo, "topic", "topic").await;
2287 let original = rev_parse(&repo, "topic").await.unwrap();
2288 sh(&repo, &["checkout", "-q", "main"]);
2289 track(&repo, "upstream", "upstream").await;
2290 let mut state = RunState::new(
2291 repo.clone(),
2292 "main".into(),
2293 base,
2294 "sync".into(),
2295 crate::config::Config::default(),
2296 );
2297 let work = repo.parent().unwrap().join("scratch");
2298 rebase_prepare(&repo, &work, "topic").await.unwrap();
2299 let obstacle = rebase_file(&work, "magi-rebase-picks.tmp").await.unwrap();
2300 std::fs::create_dir(&obstacle).unwrap();
2301 let exec = format!(
2302 r#"if test -d "$(git rev-parse --git-path magi-rebase-picks.tmp)"; then echo 'fixture ledger failure' >&2; exit 1; fi; {REBASE_EXEC}"#
2303 );
2304 let error = rebase_prepared_with_exec(&mut state, &work, "topic", "main", &exec)
2305 .await
2306 .unwrap_err();
2307 assert!(error.is::<crate::repo_lock::ResourceBlocked>());
2308 let mut state = RunState::load(&state.id).unwrap();
2309 let block = state.resource_block.as_ref().unwrap();
2310 assert_eq!(block.kind, SEQUENCER_INFRASTRUCTURE);
2311 assert!(block.detail.contains("fixture ledger failure"), "{block:?}");
2312 assert!(
2313 block.detail.contains("cannot record rebase picks"),
2314 "{block:?}"
2315 );
2316 assert!(rebase_in_progress(&work).await);
2317 assert_eq!(rev_parse(&repo, "topic").await.unwrap(), original);
2318 std::fs::remove_dir(obstacle).unwrap();
2319
2320 assert_eq!(
2321 rebase_prepared_with_exec(&mut state, &work, "topic", "main", &exec)
2322 .await
2323 .unwrap(),
2324 Rebased::Applied
2325 );
2326 assert!(state.rebase_fixes.is_empty());
2327 assert!(is_ancestor(&repo, "main", "topic").await);
2328 }
2329
2330 async fn recording_exec_fixture(persistent: bool) {
2331 use crate::queue::{Queue, Source, Task};
2332 use crate::rebase::{Rebased, SEQUENCER_INFRASTRUCTURE, rebase_prepared_with_exec};
2333 use crate::run::{Origin, RunState};
2334
2335 crate::run::pin_test_home();
2336 let temp = tempfile::tempdir().unwrap();
2337 let root = temp.path();
2338 let exec = format!(
2339 r#"root=$(git config --local magi.test-root) && if test ! -f "$root/attempts" || test -f "$root/fault"; then echo failed >> "$root/attempts"; echo 'fixture recording exec failed' >&2; exit 1; fi; echo recorded >> "$root/attempts" && {REBASE_EXEC}"#
2340 );
2341 let (_temp, repo) = scratch().await;
2342 sh(&repo, &["config", "magi.test-root", &path_arg(root)]);
2343 let base = rev_parse(&repo, "main").await.unwrap();
2344 sh(&repo, &["checkout", "-qb", "topic"]);
2345 track(&repo, "one", "one").await;
2346 track(&repo, "two", "two").await;
2347 let picks = git(&repo, &["rev-list", "--reverse", "main..topic"])
2348 .await
2349 .unwrap();
2350 sh(&repo, &["checkout", "-q", "main"]);
2351 track(&repo, "upstream", "upstream").await;
2352 let hooks = root.join("hooks");
2353 std::fs::create_dir(&hooks).unwrap();
2354 shell_script(
2355 &hooks.join("post-rewrite"),
2356 r#"#!/bin/sh
2357test "$1" = rebase || exit 0
2358root=$(git config --local magi.test-root) || exit 1
2359for name in picks heads; do
2360 cp "$(git rev-parse --git-path magi-rebase-$name)" "$root/$name" || exit 1
2361done
2362"#,
2363 );
2364 sh(&repo, &["config", "core.hooksPath", &path_arg(&hooks)]);
2365 let mut state = RunState::new(
2366 repo.clone(),
2367 "main".into(),
2368 base,
2369 "sync".into(),
2370 crate::config::Config::default(),
2371 );
2372 let queue = Queue::open();
2373 let mut task = Task::new("sync".into(), "sync".into(), repo.clone(), Source::Human);
2374 state.origin = Some(Origin::queue(&task.id));
2375 state.task_instruction = Some(task.instruction.clone());
2376 task.start(state.id.clone());
2377 queue.put(&mut task).unwrap();
2378 let work = root.join("scratch");
2379 rebase_prepare(&repo, &work, "topic").await.unwrap();
2380 let attempts = || std::fs::read_to_string(root.join("attempts")).unwrap();
2381 if persistent {
2382 std::fs::write(root.join("fault"), "").unwrap();
2383 for _ in 0..2 {
2385 let error = rebase_prepared_with_exec(&mut state, &work, "topic", "main", &exec)
2386 .await
2387 .unwrap_err();
2388 assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
2389 state = RunState::load(&state.id).unwrap();
2390 let block = state.resource_block.as_ref().unwrap();
2391 assert_eq!(block.kind, SEQUENCER_INFRASTRUCTURE);
2392 assert!(
2393 block.detail.contains("fixture recording exec failed"),
2394 "{block:?}"
2395 );
2396 assert!(state.rebase_fixes.is_empty());
2397 assert_eq!(attempts().lines().collect::<Vec<_>>(), ["failed", "failed"]);
2398 assert!(rebase_in_progress(&work).await);
2399 }
2400 let heads_file = rebase_file(&work, "magi-rebase-heads").await.unwrap();
2403 let todo_file = rebase_file(&work, "rebase-merge/git-rebase-todo")
2404 .await
2405 .unwrap();
2406 let original = rev_parse(&repo, "topic").await.unwrap();
2407 let target = rev_parse(&repo, "main").await.unwrap();
2408 let claim =
2409 || claim_recording_retry(&repo, &work, "topic", &original, &target, Some(1), &exec);
2410 let head = rev_parse(&work, "HEAD").await.unwrap();
2411 for invalid in [format!("{head}\n"), head[..12].to_string()] {
2412 std::fs::write(&heads_file, invalid).unwrap();
2413 assert!(claim().await.is_err());
2414 }
2415 std::fs::write(&heads_file, "").unwrap();
2416 let todo = std::fs::read_to_string(&todo_file).unwrap();
2417 std::fs::write(&todo_file, format!("exec true\n{todo}")).unwrap();
2418 assert!(claim().await.is_err());
2419 std::fs::write(todo_file, todo).unwrap();
2420 std::fs::remove_file(root.join("fault")).unwrap();
2421 task.release_operator("resume", None);
2422 queue.put(&mut task).unwrap();
2423 }
2424 let result = rebase_prepared_with_exec(&mut state, &work, "topic", "main", &exec)
2425 .await
2426 .unwrap();
2427 assert_eq!(result, Rebased::Applied);
2428 assert!(state.rebase_fixes.is_empty());
2429 assert_eq!(attempts().lines().count(), if persistent { 4 } else { 3 });
2430 let heads = git(&repo, &["rev-list", "--reverse", "main..topic"])
2431 .await
2432 .unwrap();
2433 assert_eq!(heads.lines().count(), 2);
2434 assert_eq!(
2435 std::fs::read_to_string(root.join("picks")).unwrap().trim(),
2436 picks
2437 );
2438 assert_eq!(
2439 std::fs::read_to_string(root.join("heads")).unwrap().trim(),
2440 heads
2441 );
2442 }
2443
2444 #[test]
2445 fn worktree_holder_is_read_from_the_porcelain_listing() {
2446 let listing = "worktree /repo\nHEAD aaa\nbranch refs/heads/main\n\n\
2447 worktree /wt/cand-A\nHEAD bbb\nbranch refs/heads/magi/f82f/A\n\n\
2448 worktree /wt/detached\nHEAD ccc\ndetached\n";
2449 assert_eq!(
2450 parse_worktree_holder(listing, "magi/f82f/A"),
2451 Some(PathBuf::from("/wt/cand-A"))
2452 );
2453 assert_eq!(parse_worktree_holder(listing, "magi/f82f"), None);
2454 assert_eq!(parse_worktree_holder(listing, "other"), None);
2455 }
2456
2457 async fn scratch() -> (tempfile::TempDir, PathBuf) {
2458 let dir = tempfile::tempdir().unwrap();
2459 let repo = dir.path().join("repo");
2460 tokio::fs::create_dir_all(&repo).await.unwrap();
2461 git(&repo, &["init", "-b", "main"]).await.unwrap();
2462 git(&repo, &["config", "user.name", "test"]).await.unwrap();
2463 git(&repo, &["config", "user.email", "test@example.com"])
2464 .await
2465 .unwrap();
2466 tokio::fs::write(repo.join("a.txt"), "one\n").await.unwrap();
2467 git(&repo, &["add", "-A"]).await.unwrap();
2468 git(&repo, &["commit", "-m", "init"]).await.unwrap();
2469 (dir, repo)
2470 }
2471
2472 #[tokio::test]
2473 async fn restore_to_removes_nested_repositories_inside_submodules() {
2474 let (_parent_dir, repo) = scratch().await;
2475 let (_source_dir, source) = scratch().await;
2476 sh(
2477 &repo,
2478 &[
2479 "-c",
2480 "protocol.file.allow=always",
2481 "submodule",
2482 "add",
2483 &source.to_string_lossy(),
2484 "sub",
2485 ],
2486 );
2487 sh(&repo, &["commit", "-am", "add submodule"]);
2488 let pre = rev_parse(&repo, "HEAD").await.unwrap();
2489 let sub = repo.join("sub");
2490 sh(&sub, &["init", "nested"]);
2491 tokio::fs::write(sub.join("nested/rejected.txt"), "rejected\n")
2492 .await
2493 .unwrap();
2494
2495 restore_to(&repo, &pre).await.unwrap();
2496
2497 assert!(!sub.join("nested").exists());
2498 assert_eq!(rev_parse(&repo, "HEAD").await.unwrap(), pre);
2499 assert_eq!(
2500 rev_parse(&sub, "HEAD").await.unwrap(),
2501 rev_parse(&source, "HEAD").await.unwrap()
2502 );
2503 assert!(
2504 git(&repo, &["status", "--porcelain"])
2505 .await
2506 .unwrap()
2507 .is_empty()
2508 );
2509 }
2510
2511 #[tokio::test]
2512 async fn a_branch_rebases_onto_a_moved_base_and_says_when_it_cannot() {
2513 let (_g, repo) = scratch().await;
2514
2515 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
2517 tokio::fs::write(repo.join("b.txt"), "side\n")
2518 .await
2519 .unwrap();
2520 git(&repo, &["add", "-A"]).await.unwrap();
2521 git(&repo, &["commit", "-m", "side work"]).await.unwrap();
2522
2523 git(&repo, &["checkout", "main"]).await.unwrap();
2526 tokio::fs::write(repo.join("c.txt"), "main\n")
2527 .await
2528 .unwrap();
2529 git(&repo, &["add", "-A"]).await.unwrap();
2530 git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
2531
2532 let scratch_tree = repo.parent().unwrap().join("rebase-scratch");
2533 let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
2534 .await
2535 .unwrap();
2536 assert!(clean.is_none(), "a disjoint change rebases: {clean:?}");
2537 assert_eq!(
2538 commits_ahead(&repo, "main", "side").await.unwrap(),
2539 1,
2540 "one commit, replayed onto the new base"
2541 );
2542 assert!(
2543 !scratch_tree.exists(),
2544 "the throwaway worktree is not left behind"
2545 );
2546
2547 git(&repo, &["checkout", "-b", "clash"]).await.unwrap();
2549 tokio::fs::write(repo.join("a.txt"), "clash\n")
2550 .await
2551 .unwrap();
2552 git(&repo, &["add", "-A"]).await.unwrap();
2553 git(&repo, &["commit", "-m", "clash"]).await.unwrap();
2554 git(&repo, &["checkout", "main"]).await.unwrap();
2555 tokio::fs::write(repo.join("a.txt"), "main edit\n")
2556 .await
2557 .unwrap();
2558 git(&repo, &["add", "-A"]).await.unwrap();
2559 git(&repo, &["commit", "-m", "main edit"]).await.unwrap();
2560
2561 let before = rev_parse(&repo, "clash").await.unwrap();
2562 let why = rebase_branch_in_temp(&repo, &scratch_tree, "clash", "main")
2563 .await
2564 .unwrap()
2565 .expect("a same-line clash cannot be rebased silently");
2566 assert!(
2567 why.to_lowercase().contains("conflict"),
2568 "the reason is what git said, which is what a person needs: {why}"
2569 );
2570 assert_eq!(
2571 rev_parse(&repo, "clash").await.unwrap(),
2572 before,
2573 "a failed rebase leaves the branch exactly where it was"
2574 );
2575 assert!(!scratch_tree.exists(), "and cleans up after itself");
2576 }
2577
2578 #[tokio::test]
2579 async fn merge_squash_folds_the_branch_into_one_commit_under_the_given_message() {
2580 let (_g, repo) = scratch().await;
2581 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
2582 for name in ["b.txt", "c.txt"] {
2583 tokio::fs::write(repo.join(name), "side\n").await.unwrap();
2584 git(&repo, &["add", "-A"]).await.unwrap();
2585 git(
2586 &repo,
2587 &["commit", "-m", "magi: candidate A (uncommitted work)"],
2588 )
2589 .await
2590 .unwrap();
2591 }
2592 git(&repo, &["checkout", "main"]).await.unwrap();
2593 let before = rev_parse(&repo, "main").await.unwrap();
2594
2595 let out = merge_squash(&repo, "side", "an explicit subject")
2596 .await
2597 .unwrap();
2598 assert!(out.ok(), "{}", out.stderr);
2599 assert_eq!(
2600 commits_ahead(&repo, &before, "main").await.unwrap(),
2601 1,
2602 "squash adds exactly one commit onto the tip, not one per candidate commit"
2603 );
2604 let subject = git(&repo, &["log", "-1", "--format=%s"]).await.unwrap();
2605 assert_eq!(
2606 subject, "an explicit subject",
2607 "the candidate's own placeholder subject must not survive: {subject}"
2608 );
2609 }
2610
2611 #[tokio::test]
2612 async fn merge_ff_only_fast_forwards_a_branch_already_rebased_onto_the_tip() {
2613 let (_g, repo) = scratch().await;
2614 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
2615 tokio::fs::write(repo.join("b.txt"), "side\n")
2616 .await
2617 .unwrap();
2618 git(&repo, &["add", "-A"]).await.unwrap();
2619 git(&repo, &["commit", "-m", "side work"]).await.unwrap();
2620 git(&repo, &["checkout", "main"]).await.unwrap();
2621
2622 let before = rev_parse(&repo, "side").await.unwrap();
2623 let out = merge_ff_only(&repo, "side").await.unwrap();
2624 assert!(out.ok(), "{}", out.stderr);
2625 assert_eq!(
2626 rev_parse(&repo, "main").await.unwrap(),
2627 before,
2628 "a fast-forward moves the base tip to the branch, no merge commit"
2629 );
2630 }
2631
2632 #[tokio::test]
2633 async fn merge_ff_only_refuses_to_write_a_merge_commit() {
2634 let (_g, repo) = scratch().await;
2635 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
2636 tokio::fs::write(repo.join("b.txt"), "side\n")
2637 .await
2638 .unwrap();
2639 git(&repo, &["add", "-A"]).await.unwrap();
2640 git(&repo, &["commit", "-m", "side work"]).await.unwrap();
2641
2642 git(&repo, &["checkout", "main"]).await.unwrap();
2644 tokio::fs::write(repo.join("c.txt"), "main\n")
2645 .await
2646 .unwrap();
2647 git(&repo, &["add", "-A"]).await.unwrap();
2648 git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
2649
2650 let before = rev_parse(&repo, "main").await.unwrap();
2651 let out = merge_ff_only(&repo, "side").await.unwrap();
2652 assert!(!out.ok(), "a divergent branch cannot fast-forward");
2653 assert_eq!(
2654 rev_parse(&repo, "main").await.unwrap(),
2655 before,
2656 "a refused fast-forward must not touch main"
2657 );
2658 }
2659
2660 #[tokio::test]
2661 async fn a_sibling_worktree_stays_stale_after_a_rebase_until_synced() {
2662 let (guard, repo) = scratch().await;
2663
2664 git(&repo, &["branch", "side"]).await.unwrap();
2668 let side_wt = guard.path().join("side-wt");
2669 git(
2670 &repo,
2671 &["worktree", "add", &side_wt.to_string_lossy(), "side"],
2672 )
2673 .await
2674 .unwrap();
2675 tokio::fs::write(side_wt.join("b.txt"), "candidate\n")
2676 .await
2677 .unwrap();
2678 git(&side_wt, &["add", "-A"]).await.unwrap();
2679 git(&side_wt, &["commit", "-m", "side work"]).await.unwrap();
2680
2681 git(&repo, &["checkout", "main"]).await.unwrap();
2683 tokio::fs::write(repo.join("c.txt"), "main\n")
2684 .await
2685 .unwrap();
2686 git(&repo, &["add", "-A"]).await.unwrap();
2687 git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
2688
2689 let scratch_tree = guard.path().join("rebase-scratch");
2691 let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
2692 .await
2693 .unwrap();
2694 assert!(clean.is_none());
2695
2696 assert_eq!(
2700 rev_parse(&side_wt, "HEAD").await.unwrap(),
2701 rev_parse(&repo, "side").await.unwrap(),
2702 "HEAD follows the moved ref"
2703 );
2704 assert!(
2705 !side_wt.join("c.txt").exists(),
2706 "stale until synced: main's new file has not reached this worktree's disk"
2707 );
2708
2709 sync_to_head(&side_wt).await.unwrap();
2710 assert!(side_wt.join("c.txt").is_file(), "synced now");
2711 assert!(
2712 side_wt.join("b.txt").is_file(),
2713 "the worktree's own committed work survives the sync"
2714 );
2715 assert!(is_clean(&side_wt).await.unwrap());
2716 }
2717
2718 #[tokio::test]
2719 async fn clean_repo_reports_clean_then_dirty() {
2720 let (_g, repo) = scratch().await;
2721 assert!(is_clean(&repo).await.unwrap());
2722 tokio::fs::write(repo.join("a.txt"), "two\n").await.unwrap();
2723 assert!(!is_clean(&repo).await.unwrap());
2724 }
2725
2726 async fn track(repo: &Path, name: &str, body: &str) {
2727 let p = repo.join(name);
2728 if let Some(d) = p.parent() {
2729 tokio::fs::create_dir_all(d).await.unwrap();
2730 }
2731 tokio::fs::write(&p, body).await.unwrap();
2732 git(repo, &["add", name]).await.unwrap();
2733 git(
2734 repo,
2735 &[
2736 "-c",
2737 "user.name=t",
2738 "-c",
2739 "user.email=t@localhost",
2740 "commit",
2741 "-q",
2742 "-m",
2743 "seed",
2744 ],
2745 )
2746 .await
2747 .unwrap();
2748 }
2749
2750 #[tokio::test]
2751 async fn rescue_withholds_a_foreign_lockfile() {
2752 let (_g, repo) = scratch().await;
2753 track(&repo, "web/bun.lock", "a\n").await;
2754 tokio::fs::write(repo.join("web/pnpm-lock.yaml"), "x\n")
2755 .await
2756 .unwrap();
2757 tokio::fs::write(repo.join("web/app.ts"), "real\n")
2758 .await
2759 .unwrap();
2760
2761 let r = rescue_commit(&repo, "rescue").await.unwrap();
2762 assert!(r.committed);
2763 assert_eq!(
2764 r.withheld,
2765 [Stray {
2766 path: "web/pnpm-lock.yaml".to_owned(),
2767 manager: "pnpm".to_owned(),
2768 kept_by: "web/bun.lock".to_owned(),
2769 }]
2770 );
2771 let files = git(&repo, &["show", "--name-only", "--format=", "HEAD"])
2772 .await
2773 .unwrap();
2774 assert!(files.contains("web/app.ts"), "{files}");
2775 assert!(!files.contains("pnpm-lock"), "{files}");
2776 assert!(repo.join("web/pnpm-lock.yaml").is_file(), "not deleted");
2777 }
2778
2779 #[tokio::test]
2780 async fn rescue_with_only_a_stray_commits_nothing() {
2781 let (_g, repo) = scratch().await;
2782 track(&repo, "bun.lock", "a\n").await;
2783 tokio::fs::write(repo.join("yarn.lock"), "x\n")
2784 .await
2785 .unwrap();
2786 let r = rescue_commit(&repo, "rescue").await.unwrap();
2787 assert!(!r.committed);
2788 assert_eq!(r.withheld.len(), 1);
2789 }
2790
2791 #[tokio::test]
2792 async fn rescue_keeps_a_same_manager_lockfile_update() {
2793 let (_g, repo) = scratch().await;
2794 track(&repo, "bun.lock", "a\n").await;
2795 tokio::fs::write(repo.join("bun.lock"), "b\n")
2796 .await
2797 .unwrap();
2798 let r = rescue_commit(&repo, "rescue").await.unwrap();
2799 assert!(r.committed);
2800 assert!(r.withheld.is_empty());
2801 let files = git(&repo, &["show", "--name-only", "--format=", "HEAD"])
2802 .await
2803 .unwrap();
2804 assert_eq!(files, "bun.lock");
2805 }
2806
2807 #[tokio::test]
2808 async fn rescue_keeps_the_first_lockfile_in_a_bare_directory() {
2809 let (_g, repo) = scratch().await;
2810 track(&repo, "other/bun.lock", "a\n").await;
2811 tokio::fs::create_dir_all(repo.join("web")).await.unwrap();
2812 tokio::fs::write(repo.join("web/package-lock.json"), "{}\n")
2813 .await
2814 .unwrap();
2815 let r = rescue_commit(&repo, "rescue").await.unwrap();
2816 assert!(r.committed);
2817 assert!(r.withheld.is_empty());
2818 }
2819
2820 #[test]
2821 fn a_cargo_lock_is_foreign_only_without_a_cargo_toml() {
2822 let s = |v: &[&str]| v.iter().map(|x| (*x).to_owned()).collect::<Vec<_>>();
2823 assert_eq!(stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&[])).len(), 1);
2824 assert!(stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&["a/Cargo.toml"])).is_empty());
2825 assert!(stray_lockfiles(&s(&["a/Cargo.lock", "a/Cargo.toml"]), &s(&[])).is_empty());
2826 assert_eq!(
2828 stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&["Cargo.toml"])).len(),
2829 1
2830 );
2831 }
2832
2833 #[tokio::test]
2834 async fn clean_removal_preserves_edits_while_scratch_removal_discards_them() {
2835 let (guard, repo) = scratch().await;
2836 let wt = guard.path().join("scratch-wt");
2837 worktree_add_detached(&repo, &wt, "HEAD").await.unwrap();
2838 tokio::fs::write(wt.join("built.txt"), "build output")
2839 .await
2840 .unwrap();
2841 assert!(!worktree_remove_clean(&repo, &wt).await.unwrap());
2842 assert!(wt.join("built.txt").exists());
2843 let listing = git(&repo, &["worktree", "list", "--porcelain"])
2844 .await
2845 .unwrap();
2846 let registered = listing
2847 .lines()
2848 .filter_map(|line| line.strip_prefix("worktree "))
2849 .map(PathBuf::from)
2850 .find(|path| path.canonicalize().unwrap() == wt.canonicalize().unwrap())
2851 .expect("the refused removal must retain the worktree registration");
2852 assert!(worktree_remove(&repo, &wt).await.unwrap());
2853 assert!(!wt.exists());
2854 let listing = git(&repo, &["worktree", "list", "--porcelain"])
2855 .await
2856 .unwrap();
2857 assert!(!listing.lines().any(|line| {
2858 line.strip_prefix("worktree ")
2859 .is_some_and(|path| Path::new(path) == registered)
2860 }));
2861 }
2862
2863 #[tokio::test]
2864 async fn worktree_lifecycle_and_diff() {
2865 let (guard, repo) = scratch().await;
2866 let base = rev_parse(&repo, "HEAD").await.unwrap();
2867 let wt = guard.path().join("wt-a");
2868 worktree_add_branch(&repo, &wt, "magi/test/a", &base)
2869 .await
2870 .unwrap();
2871 tokio::fs::write(wt.join("b.txt"), "candidate\n")
2872 .await
2873 .unwrap();
2874
2875 assert!(commit_all(&wt, "candidate work").await.unwrap());
2876 assert!(!commit_all(&wt, "nothing left").await.unwrap());
2877
2878 assert_eq!(commits_ahead(&wt, &base, "HEAD").await.unwrap(), 1);
2879 let patch = diff(&wt, &base, "HEAD").await.unwrap();
2880 assert!(patch.contains("b.txt"), "patch was: {patch}");
2881 assert_eq!(
2882 changed_files(&wt, &base, "HEAD").await.unwrap(),
2883 ["b.txt".to_owned()]
2884 );
2885
2886 let author = git(&wt, &["log", "-1", "--format=%an <%ae>"])
2888 .await
2889 .unwrap();
2890 assert_eq!(author, "magi candidate <magi@localhost>");
2891
2892 let head = rev_parse(&wt, "HEAD").await.unwrap();
2893 let prov = commit_provenance(&wt, &head).await.unwrap();
2894 assert_eq!(prov.commit, head);
2895 assert_eq!(prov.parents, vec![base.clone()]);
2896 assert_eq!(prov.author_name, NEUTRAL_IDENTITY_NAME);
2897 assert_eq!(prov.author_email, NEUTRAL_IDENTITY_EMAIL);
2898 assert_eq!(prov.committer_name, NEUTRAL_IDENTITY_NAME);
2899 assert_eq!(prov.committer_email, NEUTRAL_IDENTITY_EMAIL);
2900 assert_eq!(prov.message, "candidate work");
2901
2902 assert!(worktree_remove(&repo, &wt).await.unwrap());
2903 assert!(branch_exists(&repo, "magi/test/a").await.unwrap());
2904 assert!(branch_delete(&repo, "magi/test/a").await.unwrap());
2905 assert!(!branch_exists(&repo, "magi/test/a").await.unwrap());
2906 }
2907
2908 #[tokio::test]
2909 async fn commit_provenance_distinguishes_merge_commits_body_and_identities() {
2910 let (_guard, repo) = scratch().await;
2911 let base = rev_parse(&repo, "HEAD").await.unwrap();
2912
2913 tokio::fs::write(repo.join("body.txt"), "one\n")
2915 .await
2916 .unwrap();
2917 git(&repo, &["add", "body.txt"]).await.unwrap();
2918 let out = tokio::process::Command::new("git")
2919 .current_dir(&repo)
2920 .env("GIT_AUTHOR_NAME", "Alice")
2921 .env("GIT_AUTHOR_EMAIL", "alice@example.com")
2922 .env("GIT_COMMITTER_NAME", NEUTRAL_IDENTITY_NAME)
2923 .env("GIT_COMMITTER_EMAIL", NEUTRAL_IDENTITY_EMAIL)
2924 .args(["commit", "--no-verify", "-m", "subject\n\nextra body"])
2925 .output()
2926 .await
2927 .unwrap();
2928 assert!(out.status.success());
2929 let extra = rev_parse(&repo, "HEAD").await.unwrap();
2930 let prov = commit_provenance(&repo, &extra).await.unwrap();
2931 assert_eq!(prov.parents, vec![base.clone()]);
2932 assert_eq!(prov.author_name, "Alice");
2933 assert_eq!(prov.author_email, "alice@example.com");
2934 assert_eq!(prov.committer_name, NEUTRAL_IDENTITY_NAME);
2935 assert_eq!(prov.committer_email, NEUTRAL_IDENTITY_EMAIL);
2936 assert_eq!(prov.message, "subject\n\nextra body");
2937
2938 git(&repo, &["checkout", "-b", "side", &base])
2940 .await
2941 .unwrap();
2942 tokio::fs::write(repo.join("side.txt"), "two\n")
2943 .await
2944 .unwrap();
2945 assert!(commit_all(&repo, "side change").await.unwrap());
2946 let side = rev_parse(&repo, "HEAD").await.unwrap();
2947 git(&repo, &["checkout", "-"]).await.unwrap();
2948 let merge_out = git_raw(
2949 &repo,
2950 &[
2951 "-c",
2952 &format!("user.name={NEUTRAL_IDENTITY_NAME}"),
2953 "-c",
2954 &format!("user.email={NEUTRAL_IDENTITY_EMAIL}"),
2955 "merge",
2956 "--no-ff",
2957 "-m",
2958 "merge side",
2959 &side,
2960 ],
2961 )
2962 .await
2963 .unwrap();
2964 assert!(merge_out.ok(), "{}", merge_out.stderr);
2965 let merged = rev_parse(&repo, "HEAD").await.unwrap();
2966 let merged_prov = commit_provenance(&repo, &merged).await.unwrap();
2967 assert_eq!(merged_prov.parents, vec![extra, side]);
2968 assert_eq!(merged_prov.message, "merge side");
2969 }
2970
2971 #[tokio::test]
2972 async fn worktree_scoped_hooks_path_does_not_leak_to_primary() {
2973 let (guard, repo) = scratch().await;
2974 let base = rev_parse(&repo, "HEAD").await.unwrap();
2975 let wt = guard.path().join("wt-h");
2976 worktree_add_branch(&repo, &wt, "magi/test/h", &base)
2977 .await
2978 .unwrap();
2979 let hooks = guard.path().join("hooks");
2980 tokio::fs::create_dir_all(&hooks).await.unwrap();
2981
2982 assert!(enable_worktree_config(&repo).await.unwrap());
2983 set_worktree_hooks_path(&wt, &hooks).await.unwrap();
2984
2985 let in_wt = git(&wt, &["config", "--get", "core.hooksPath"])
2986 .await
2987 .unwrap();
2988 assert!(!in_wt.is_empty());
2989 let in_primary = git_raw(&repo, &["config", "--get", "core.hooksPath"])
2990 .await
2991 .unwrap();
2992 assert!(
2993 !in_primary.ok(),
2994 "primary worktree must keep its own hooks: {in_primary:?}"
2995 );
2996
2997 disable_worktree_config(&repo).await.unwrap();
2998 }
2999
3000 #[tokio::test]
3001 async fn worktree_hooks_run_when_the_hooks_dir_is_canonical() {
3002 let (guard, repo) = scratch().await;
3003 let base = rev_parse(&repo, "HEAD").await.unwrap();
3004 let wt = guard.path().join("wt-canon");
3005 worktree_add_branch(&repo, &wt, "magi/test/canon", &base)
3006 .await
3007 .unwrap();
3008 let hooks = guard.path().join("hooks-canon");
3009 tokio::fs::create_dir_all(&hooks).await.unwrap();
3010 tokio::fs::write(
3011 hooks.join("commit-msg"),
3012 "#!/bin/sh\nprintf 'hooked\\n' > \"$1\"\n",
3013 )
3014 .await
3015 .unwrap();
3016 #[cfg(unix)]
3017 {
3018 use std::os::unix::fs::PermissionsExt as _;
3019 std::fs::set_permissions(
3020 hooks.join("commit-msg"),
3021 std::fs::Permissions::from_mode(0o755),
3022 )
3023 .unwrap();
3024 }
3025
3026 assert!(enable_worktree_config(&repo).await.unwrap());
3027 set_worktree_hooks_path(&wt, &hooks.canonicalize().unwrap())
3028 .await
3029 .unwrap();
3030 tokio::fs::write(wt.join("hooked.txt"), "x").await.unwrap();
3031 git(&wt, &["add", "-A"]).await.unwrap();
3032 git(&wt, &["commit", "-q", "-m", "original"]).await.unwrap();
3033 assert_eq!(
3034 git(&wt, &["log", "-1", "--format=%s"]).await.unwrap(),
3035 "hooked"
3036 );
3037
3038 disable_worktree_config(&repo).await.unwrap();
3039 }
3040
3041 #[tokio::test]
3042 async fn worktree_config_stays_on_while_a_sibling_run_still_holds_it() {
3043 let (_g, repo) = scratch().await;
3044
3045 acquire_worktree_config(&repo).await.unwrap();
3048 acquire_worktree_config(&repo).await.unwrap();
3049
3050 let on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
3051 .await
3052 .unwrap();
3053 assert_eq!(on, "true");
3054
3055 release_worktree_config(&repo).await.unwrap();
3059 let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
3060 .await
3061 .unwrap();
3062 assert_eq!(
3063 still_on, "true",
3064 "a sibling run's release must not disable the setting for the one still working"
3065 );
3066
3067 release_worktree_config(&repo).await.unwrap();
3069 let after = git_raw(&repo, &["config", "--get", "extensions.worktreeConfig"])
3070 .await
3071 .unwrap();
3072 assert!(
3073 !after.ok(),
3074 "the last release must turn the setting back off: {after:?}"
3075 );
3076 }
3077
3078 #[tokio::test]
3079 async fn worktree_config_already_on_before_magi_touched_it_is_left_alone() {
3080 let (_g, repo) = scratch().await;
3081 git(&repo, &["config", "extensions.worktreeConfig", "true"])
3082 .await
3083 .unwrap();
3084
3085 acquire_worktree_config(&repo).await.unwrap();
3090 release_worktree_config(&repo).await.unwrap();
3091
3092 let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
3093 .await
3094 .unwrap();
3095 assert_eq!(still_on, "true");
3096 }
3097
3098 #[tokio::test]
3099 async fn local_exclude_is_idempotent() {
3100 let (_g, repo) = scratch().await;
3101 local_exclude(&repo, "/.magi/").await.unwrap();
3102 local_exclude(&repo, "/.magi/").await.unwrap();
3103 let path = repo.join(".git/info/exclude");
3104 let body = tokio::fs::read_to_string(&path).await.unwrap();
3105 assert_eq!(body.matches("/.magi/").count(), 1);
3106 }
3107
3108 fn sh(cwd: &Path, args: &[&str]) {
3109 let out = std::process::Command::new("git")
3110 .quiet()
3111 .args(args)
3112 .current_dir(cwd)
3113 .output()
3114 .unwrap();
3115 assert!(
3116 out.status.success(),
3117 "git {args:?}: {}",
3118 String::from_utf8_lossy(&out.stderr)
3119 );
3120 }
3121
3122 async fn with_remote() -> (tempfile::TempDir, PathBuf) {
3125 let (g, repo) = scratch().await;
3126 let bare = g.path().join("bare.git");
3127 sh(g.path(), &["init", "--bare", "-b", "trunk", "bare.git"]);
3128 sh(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
3129 sh(&repo, &["push", "origin", "HEAD:refs/heads/trunk"]);
3130 sh(&repo, &["fetch", "origin"]);
3131 (g, repo)
3132 }
3133
3134 #[test]
3135 fn remote_head_branch_strips_only_the_matching_remote() {
3136 assert_eq!(
3137 remote_head_branch("origin", "refs/remotes/origin/main\n").as_deref(),
3138 Some("main")
3139 );
3140 assert_eq!(remote_head_branch("up", "refs/remotes/origin/main"), None);
3141 assert_eq!(remote_head_branch("origin", "refs/remotes/origin/"), None);
3142 }
3143
3144 #[tokio::test]
3145 async fn merge_base_branch_reads_origin_head_when_present() {
3146 let (_g, repo) = with_remote().await;
3147 sh(&repo, &["remote", "set-head", "origin", "trunk"]);
3148 assert_eq!(
3149 merge_base_branch(&repo, "origin", None).await.unwrap(),
3150 "trunk"
3151 );
3152 }
3153
3154 #[tokio::test]
3155 async fn merge_base_branch_recovers_a_missing_origin_head() {
3156 let (_g, repo) = with_remote().await;
3157 sh(&repo, &["remote", "set-head", "origin", "-d"]);
3159 let head = git_raw(
3160 &repo,
3161 &["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"],
3162 )
3163 .await
3164 .unwrap();
3165 assert!(!head.ok(), "precondition: no origin/HEAD");
3166 assert_eq!(
3167 merge_base_branch(&repo, "origin", None).await.unwrap(),
3168 "trunk"
3169 );
3170 }
3171
3172 #[tokio::test]
3173 async fn merge_base_branch_errors_without_a_remote_and_never_uses_head() {
3174 let (_g, repo) = scratch().await;
3175 let err = merge_base_branch(&repo, "origin", None).await.unwrap_err();
3176 assert!(format!("{err:#}").contains("[merge] base"), "{err:#}");
3177 }
3178
3179 #[tokio::test]
3180 async fn merge_base_branch_prefers_the_explicit_base() {
3181 let (_g, repo) = with_remote().await;
3182 assert_eq!(
3183 merge_base_branch(&repo, "origin", Some("release"))
3184 .await
3185 .unwrap(),
3186 "release"
3187 );
3188 }
3189
3190 #[tokio::test]
3191 async fn merge_base_branch_names_an_unfetched_default_branch() {
3192 let (g, repo) = scratch().await;
3195 let bare = g.path().join("bare.git");
3196 sh(g.path(), &["init", "--bare", "-b", "trunk", "bare.git"]);
3197 sh(
3198 &repo,
3199 &["push", &bare.to_string_lossy(), "HEAD:refs/heads/trunk"],
3200 );
3201 sh(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
3202 assert!(!rev_exists(&repo, "refs/remotes/origin/trunk").await);
3203 assert_eq!(
3204 merge_base_branch(&repo, "origin", None).await.unwrap(),
3205 "trunk"
3206 );
3207 }
3208
3209 #[test]
3210 fn symref_branch_reads_ls_remote_output() {
3211 assert_eq!(
3212 symref_branch("ref: refs/heads/main\tHEAD\nabc\tHEAD\n").as_deref(),
3213 Some("main")
3214 );
3215 assert_eq!(symref_branch("abc\tHEAD\n"), None);
3216 }
3217}