1use std::path::{Path, PathBuf};
7use std::process::Stdio;
8
9use crate::proc::Quiet as _;
10use anyhow::{Context as _, Result, bail};
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 let out = Command::new("git")
35 .args(args)
36 .current_dir(cwd)
37 .quiet()
38 .env("GIT_TERMINAL_PROMPT", "0")
41 .env("GIT_EDITOR", "true")
42 .stdin(Stdio::null())
43 .output()
44 .await
45 .with_context(|| format!("spawn git {}", args.join(" ")))?;
46 Ok(GitOut {
47 code: out.status.code(),
48 stdout: String::from_utf8_lossy(&out.stdout).trim_end().to_owned(),
49 stderr: String::from_utf8_lossy(&out.stderr).trim_end().to_owned(),
50 })
51}
52
53pub async fn git(cwd: &Path, args: &[&str]) -> Result<String> {
55 let out = git_raw(cwd, args).await?;
56 if !out.ok() {
57 bail!(
58 "git {} failed in {} (exit {:?}): {}",
59 args.join(" "),
60 cwd.display(),
61 out.code,
62 if out.stderr.is_empty() {
63 out.stdout.as_str()
64 } else {
65 out.stderr.as_str()
66 }
67 );
68 }
69 Ok(out.stdout)
70}
71
72pub async fn toplevel(path: &Path) -> Result<PathBuf> {
74 let out = git(path, &["rev-parse", "--show-toplevel"]).await?;
75 Ok(PathBuf::from(out))
76}
77
78pub async fn rev_parse(repo: &Path, rev: &str) -> Result<String> {
80 git(repo, &["rev-parse", rev]).await
81}
82
83pub async fn current_branch(repo: &Path) -> Result<Option<String>> {
85 let out = git_raw(repo, &["symbolic-ref", "--quiet", "--short", "HEAD"]).await?;
86 Ok(if out.ok() && !out.stdout.is_empty() {
87 Some(out.stdout)
88 } else {
89 None
90 })
91}
92
93pub async fn is_clean(repo: &Path) -> Result<bool> {
95 Ok(git(repo, &["status", "--porcelain"]).await?.is_empty())
96}
97
98pub async fn status_porcelain(repo: &Path) -> Result<String> {
100 git(repo, &["status", "--porcelain"]).await
101}
102
103pub async fn worktree_add_branch(repo: &Path, path: &Path, branch: &str, base: &str) -> Result<()> {
105 if let Some(parent) = path.parent() {
106 tokio::fs::create_dir_all(parent).await.ok();
107 }
108 let path_s = path.to_string_lossy().to_string();
109 git(repo, &["worktree", "add", "-b", branch, &path_s, base])
110 .await
111 .map(|_| ())
112}
113
114pub async fn worktree_add_detached(repo: &Path, path: &Path, rev: &str) -> Result<()> {
116 if let Some(parent) = path.parent() {
117 tokio::fs::create_dir_all(parent).await.ok();
118 }
119 let path_s = path.to_string_lossy().to_string();
120 git(repo, &["worktree", "add", "--detach", &path_s, rev])
121 .await
122 .map(|_| ())
123}
124
125pub async fn reset_detached(worktree: &Path, rev: &str) -> Result<()> {
127 git(worktree, &["checkout", "--detach", rev]).await?;
128 git(worktree, &["reset", "--hard", rev]).await?;
129 git(worktree, &["clean", "-fdx"]).await?;
130 Ok(())
131}
132
133pub async fn worktree_holding(repo: &Path, branch: &str) -> Result<Option<PathBuf>> {
138 let listing = git(repo, &["worktree", "list", "--porcelain"]).await?;
139 Ok(parse_worktree_holder(&listing, branch))
140}
141
142fn parse_worktree_holder(listing: &str, branch: &str) -> Option<PathBuf> {
143 let want = format!("refs/heads/{branch}");
144 let mut path: Option<PathBuf> = None;
145 for line in listing.lines() {
146 if let Some(p) = line.strip_prefix("worktree ") {
147 path = Some(PathBuf::from(p));
148 } else if line.strip_prefix("branch ") == Some(want.as_str()) {
149 return path;
150 }
151 }
152 None
153}
154
155pub async fn worktree_remove(repo: &Path, path: &Path) -> Result<bool> {
158 let path_s = path.to_string_lossy().to_string();
159 let out = git_raw(repo, &["worktree", "remove", "--force", &path_s]).await?;
160 if out.ok() {
161 return Ok(true);
162 }
163 git_raw(repo, &["worktree", "prune"]).await?;
165 Ok(false)
166}
167
168pub async fn worktree_remove_clean(repo: &Path, path: &Path) -> Result<bool> {
172 let path_s = path.to_string_lossy().to_string();
173 Ok(git_raw(repo, &["worktree", "remove", &path_s]).await?.ok())
174}
175
176pub async fn remove_worktree_from_linked(dir: &Path) {
185 let Ok(link) = std::fs::read_to_string(dir.join(".git")) else {
186 return;
187 };
188 let Some(admin) = link.strip_prefix("gitdir:").map(str::trim) else {
189 return;
190 };
191 let admin = Path::new(admin);
194 let Some(common) = admin.parent().and_then(Path::parent) else {
195 return;
196 };
197 let common_s = common.to_string_lossy();
198 let _ = git_raw(dir, &["--git-dir", &common_s, "worktree", "prune"]).await;
199}
200
201pub async fn worktree_prune(repo: &Path) -> Result<()> {
210 git(repo, &["worktree", "prune"]).await.map(|_| ())
211}
212
213pub async fn branch_delete(repo: &Path, branch: &str) -> Result<bool> {
215 Ok(git_raw(repo, &["branch", "-D", branch]).await?.ok())
216}
217
218pub async fn branch_exists(repo: &Path, branch: &str) -> Result<bool> {
220 let refname = format!("refs/heads/{branch}");
221 Ok(
222 git_raw(repo, &["show-ref", "--verify", "--quiet", &refname])
223 .await?
224 .ok(),
225 )
226}
227
228pub async fn remote_has_branch(repo: &Path, remote: &str, branch: &str) -> Result<bool> {
231 let refname = format!("refs/heads/{branch}");
232 let out = git_raw(repo, &["ls-remote", "--exit-code", remote, &refname]).await?;
233 match out.code {
234 Some(0) => Ok(true),
235 Some(2) => Ok(false),
236 code => bail!(
237 "git ls-remote {remote} failed (exit {code:?}): {}",
238 out.stderr
239 ),
240 }
241}
242
243pub async fn diff(worktree: &Path, base: &str, head: &str) -> Result<String> {
245 let range = format!("{base}...{head}");
246 git(
247 worktree,
248 &["diff", "--no-color", "--no-ext-diff", "-M", &range],
249 )
250 .await
251}
252
253pub async fn diff_stat(worktree: &Path, base: &str, head: &str) -> Result<String> {
255 let range = format!("{base}...{head}");
256 git(worktree, &["diff", "--no-color", "--stat", &range]).await
257}
258
259pub async fn changed_files(worktree: &Path, base: &str, head: &str) -> Result<Vec<String>> {
261 let range = format!("{base}...{head}");
262 let out = git(worktree, &["diff", "--name-only", &range]).await?;
263 Ok(out.lines().map(str::to_owned).collect())
264}
265
266pub async fn log_oneline(worktree: &Path, base: &str, head: &str) -> Result<String> {
268 let range = format!("{base}..{head}");
269 git(
270 worktree,
271 &["log", "--reverse", "--format=%s%n%b%n--", &range],
272 )
273 .await
274}
275
276pub async fn subjects(worktree: &Path, base: &str, head: &str) -> Result<Vec<String>> {
279 let range = format!("{base}..{head}");
280 let out = git(worktree, &["log", "--reverse", "--format=%s%x00", &range]).await?;
281 let mut parts: Vec<String> = out.split('\0').map(|s| s.trim().to_owned()).collect();
282 parts.pop();
284 Ok(parts)
285}
286
287pub async fn commits_ahead(worktree: &Path, base: &str, head: &str) -> Result<usize> {
289 let range = format!("{base}..{head}");
290 let out = git(worktree, &["rev-list", "--count", &range]).await?;
291 Ok(out.trim().parse().unwrap_or(0))
292}
293
294pub async fn commit_all(worktree: &Path, message: &str) -> Result<bool> {
301 if git(worktree, &["status", "--porcelain"]).await?.is_empty() {
302 return Ok(false);
303 }
304 git(worktree, &["add", "-A"]).await?;
305 let out = git_raw(
306 worktree,
307 &[
308 "-c",
309 "user.name=magi candidate",
310 "-c",
311 "user.email=magi@localhost",
312 "commit",
313 "--no-verify",
314 "-m",
315 message,
316 ],
317 )
318 .await?;
319 if !out.ok() {
320 bail!("rescue commit failed: {}", out.stderr);
321 }
322 Ok(true)
323}
324
325#[derive(Debug, Clone, PartialEq, Eq)]
328pub struct Stray {
329 pub path: String,
331 pub manager: String,
333 pub kept_by: String,
336}
337
338#[derive(Debug, Default)]
340pub struct Rescue {
341 pub committed: bool,
343 pub withheld: Vec<Stray>,
345}
346
347fn lock_kind(name: &str) -> Option<(&'static str, &'static str)> {
349 Some(match name {
350 "package-lock.json" | "npm-shrinkwrap.json" => ("node", "npm"),
351 "yarn.lock" => ("node", "yarn"),
352 "pnpm-lock.yaml" => ("node", "pnpm"),
353 "bun.lock" | "bun.lockb" => ("node", "bun"),
354 "poetry.lock" => ("python", "poetry"),
355 "uv.lock" => ("python", "uv"),
356 "Pipfile.lock" => ("python", "pipenv"),
357 "pdm.lock" => ("python", "pdm"),
358 "Cargo.lock" => ("rust", "cargo"),
359 _ => return None,
360 })
361}
362
363fn split_dir(path: &str) -> (&str, &str) {
364 path.rsplit_once('/').unwrap_or(("", path))
365}
366
367pub fn stray_lockfiles(untracked: &[String], tracked: &[String]) -> Vec<Stray> {
375 let mut out = Vec::new();
376 for path in untracked {
377 let (dir, name) = split_dir(path);
378 let Some((eco, manager)) = lock_kind(name) else {
379 continue;
380 };
381 let beside = |other: &String| split_dir(other).0 == dir;
382 let kept_by = if manager == "cargo" {
383 let has_manifest = tracked
384 .iter()
385 .chain(untracked)
386 .any(|p| beside(p) && split_dir(p).1 == "Cargo.toml");
387 if has_manifest {
388 continue;
389 }
390 "no Cargo.toml in the directory".to_owned()
391 } else {
392 let Some(other) = tracked.iter().find(|p| {
393 beside(p)
394 && lock_kind(split_dir(p).1).is_some_and(|(e, m)| e == eco && m != manager)
395 }) else {
396 continue;
397 };
398 other.clone()
399 };
400 out.push(Stray {
401 path: path.clone(),
402 manager: manager.to_owned(),
403 kept_by,
404 });
405 }
406 out
407}
408
409async fn nul_list(worktree: &Path, args: &[&str]) -> Result<Vec<String>> {
410 let out = git(worktree, args).await?;
411 Ok(out
412 .split('\0')
413 .filter(|s| !s.is_empty())
414 .map(str::to_owned)
415 .collect())
416}
417
418pub async fn rescue_commit(worktree: &Path, message: &str) -> Result<Rescue> {
424 if git(worktree, &["status", "--porcelain"]).await?.is_empty() {
425 return Ok(Rescue::default());
426 }
427 let untracked = nul_list(
428 worktree,
429 &["ls-files", "-z", "--others", "--exclude-standard"],
430 )
431 .await?;
432 let tracked = nul_list(worktree, &["ls-files", "-z"]).await?;
433 let withheld = stray_lockfiles(&untracked, &tracked);
434
435 git(worktree, &["add", "-A"]).await?;
436 if !withheld.is_empty() {
437 let mut args = vec!["reset", "-q", "--"];
438 args.extend(withheld.iter().map(|s| s.path.as_str()));
439 git(worktree, &args).await?;
440 }
441 if git_raw(worktree, &["diff", "--cached", "--quiet"])
442 .await?
443 .ok()
444 {
445 return Ok(Rescue {
446 committed: false,
447 withheld,
448 });
449 }
450 let out = git_raw(
451 worktree,
452 &[
453 "-c",
454 "user.name=magi candidate",
455 "-c",
456 "user.email=magi@localhost",
457 "commit",
458 "--no-verify",
459 "-m",
460 message,
461 ],
462 )
463 .await?;
464 if !out.ok() {
465 bail!("rescue commit failed: {}", out.stderr);
466 }
467 Ok(Rescue {
468 committed: true,
469 withheld,
470 })
471}
472
473pub async fn enable_worktree_config(repo: &Path) -> Result<bool> {
478 let out = git_raw(repo, &["config", "--get", "extensions.worktreeConfig"]).await?;
479 if out.ok() && out.stdout.trim() == "true" {
480 return Ok(false);
481 }
482 git(repo, &["config", "extensions.worktreeConfig", "true"]).await?;
483 Ok(true)
484}
485
486pub async fn disable_worktree_config(repo: &Path) -> Result<()> {
488 git_raw(repo, &["config", "--unset", "extensions.worktreeConfig"]).await?;
489 Ok(())
490}
491
492struct WorktreeConfigRef {
495 count: usize,
497 we_enabled: bool,
503}
504
505static WORKTREE_CONFIG: std::sync::LazyLock<
512 std::sync::Mutex<
513 std::collections::HashMap<PathBuf, std::sync::Arc<tokio::sync::Mutex<WorktreeConfigRef>>>,
514 >,
515> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
516
517fn worktree_config_slot(repo: &Path) -> std::sync::Arc<tokio::sync::Mutex<WorktreeConfigRef>> {
519 let mut map = WORKTREE_CONFIG
520 .lock()
521 .unwrap_or_else(std::sync::PoisonError::into_inner);
522 map.entry(repo.to_path_buf())
523 .or_insert_with(|| {
524 std::sync::Arc::new(tokio::sync::Mutex::new(WorktreeConfigRef {
525 count: 0,
526 we_enabled: false,
527 }))
528 })
529 .clone()
530}
531
532pub async fn acquire_worktree_config(repo: &Path) -> Result<()> {
549 let slot = worktree_config_slot(repo);
550 let mut entry = slot.lock().await;
551 entry.count += 1;
552 if entry.count == 1 {
553 entry.we_enabled = enable_worktree_config(repo).await?;
554 }
555 Ok(())
556}
557
558pub async fn release_worktree_config(repo: &Path) -> Result<()> {
564 let slot = worktree_config_slot(repo);
565 let mut entry = slot.lock().await;
566 entry.count = entry.count.saturating_sub(1);
567 if entry.count == 0 && entry.we_enabled {
568 disable_worktree_config(repo).await?;
569 entry.we_enabled = false;
570 }
571 Ok(())
572}
573
574pub async fn set_worktree_hooks_path(worktree: &Path, hooks_dir: &Path) -> Result<()> {
580 let dir = hooks_dir.to_string_lossy().replace('\\', "/");
581 git(worktree, &["config", "--worktree", "core.hooksPath", &dir])
582 .await
583 .map(|_| ())
584}
585
586pub async fn local_exclude(worktree: &Path, pattern: &str) -> Result<()> {
588 let git_dir = git(worktree, &["rev-parse", "--git-path", "info/exclude"]).await?;
589 let path = worktree.join(git_dir);
590 if let Some(parent) = path.parent() {
591 tokio::fs::create_dir_all(parent).await.ok();
592 }
593 let mut body = tokio::fs::read_to_string(&path).await.unwrap_or_default();
594 if body.lines().any(|l| l.trim() == pattern) {
595 return Ok(());
596 }
597 if !body.is_empty() && !body.ends_with('\n') {
598 body.push('\n');
599 }
600 body.push_str(pattern);
601 body.push('\n');
602 tokio::fs::write(&path, body)
603 .await
604 .with_context(|| format!("write {}", path.display()))?;
605 Ok(())
606}
607
608pub async fn merge_no_ff(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
614 git_raw(
615 repo,
616 &["merge", "--no-ff", "--no-edit", "-m", message, branch],
617 )
618 .await
619}
620
621pub async fn merge_squash(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
632 let staged = git_raw(repo, &["merge", "--squash", branch]).await?;
633 if !staged.ok() {
634 return Ok(staged);
635 }
636 git_raw(repo, &["commit", "-m", message]).await
637}
638
639pub async fn merge_ff_only(repo: &Path, branch: &str) -> Result<GitOut> {
649 git_raw(repo, &["merge", "--ff-only", branch]).await
650}
651
652pub async fn push(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
654 git_raw(repo, &["push", "-u", remote, branch]).await
655}
656
657pub async fn push_rewritten(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
665 git_raw(repo, &["push", "--force-with-lease", remote, branch]).await
666}
667
668pub async fn push_pinned(
677 repo: &Path,
678 remote: &str,
679 branch: &str,
680 expected: &str,
681) -> Result<GitOut> {
682 let lease = format!("--force-with-lease=refs/heads/{branch}:{expected}");
683 let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
684 git_raw(repo, &["push", &lease, remote, &refspec]).await
685}
686
687pub async fn cherry(repo: &Path, upstream: &str, head: &str) -> Result<(Vec<String>, Vec<String>)> {
690 let out = git(repo, &["cherry", upstream, head]).await?;
691 let (mut unmatched, mut matched) = (Vec::new(), Vec::new());
692 for line in out.lines() {
693 if let Some(sha) = line.strip_prefix("+ ") {
694 unmatched.push(sha.trim().to_owned());
695 } else if let Some(sha) = line.strip_prefix("- ") {
696 matched.push(sha.trim().to_owned());
697 }
698 }
699 Ok((unmatched, matched))
700}
701
702#[derive(Debug, Clone, PartialEq, Eq)]
704pub enum RebaseStart {
705 Applied,
708 Conflicted(String),
711 Failed(String),
714}
715
716pub async fn rebase_start(
731 repo: &Path,
732 scratch: &Path,
733 branch: &str,
734 onto: &str,
735) -> Result<RebaseStart> {
736 worktree_remove(repo, scratch).await.ok();
739 git_raw(
740 repo,
741 &[
742 "worktree",
743 "add",
744 "--force",
745 &scratch.to_string_lossy(),
746 branch,
747 ],
748 )
749 .await?;
750
751 let out = git_raw(scratch, &["rebase", onto]).await?;
752 if out.ok() {
753 worktree_remove(repo, scratch).await.ok();
754 return Ok(RebaseStart::Applied);
755 }
756 let why = if out.stderr.trim().is_empty() {
757 out.stdout.trim().to_owned()
758 } else {
759 out.stderr.trim().to_owned()
760 };
761 if rebase_in_progress(scratch).await {
762 return Ok(RebaseStart::Conflicted(why));
763 }
764 worktree_remove(repo, scratch).await.ok();
765 Ok(RebaseStart::Failed(why))
766}
767
768pub async fn rebase_in_progress(worktree: &Path) -> bool {
770 for name in ["rebase-merge", "rebase-apply"] {
771 let Ok(p) = git(worktree, &["rev-parse", "--git-path", name]).await else {
772 continue;
773 };
774 let p = Path::new(p.trim());
775 let full = if p.is_absolute() {
776 p.to_path_buf()
777 } else {
778 worktree.join(p)
779 };
780 if full.exists() {
781 return true;
782 }
783 }
784 false
785}
786
787pub async fn unmerged_paths(worktree: &Path) -> Result<Vec<String>> {
789 let out = git(worktree, &["diff", "--name-only", "--diff-filter=U"]).await?;
790 Ok(out
791 .lines()
792 .map(str::trim)
793 .filter(|l| !l.is_empty())
794 .map(str::to_owned)
795 .collect())
796}
797
798pub async fn rebase_abort(repo: &Path, scratch: &Path) {
801 git_raw(scratch, &["rebase", "--abort"]).await.ok();
802 worktree_remove(repo, scratch).await.ok();
803}
804
805pub async fn rebase_branch_in_temp(
813 repo: &Path,
814 scratch: &Path,
815 branch: &str,
816 onto: &str,
817) -> Result<Option<String>> {
818 match rebase_start(repo, scratch, branch, onto).await? {
819 RebaseStart::Applied => Ok(None),
820 RebaseStart::Failed(why) => Ok(Some(why)),
821 RebaseStart::Conflicted(why) => {
822 rebase_abort(repo, scratch).await;
823 Ok(Some(why))
824 }
825 }
826}
827
828pub async fn sync_to_head(worktree: &Path) -> Result<()> {
841 git(worktree, &["reset", "--hard", "HEAD"]).await?;
842 git(worktree, &["clean", "-fdx"]).await?;
843 Ok(())
844}
845
846pub async fn fetch(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
865 let refspec = format!("+refs/heads/{branch}:refs/remotes/{remote}/{branch}");
866 git_raw(repo, &["fetch", "--quiet", remote, &refspec]).await
867}
868
869pub async fn is_ancestor(repo: &Path, ancestor: &str, of: &str) -> bool {
871 git_raw(repo, &["merge-base", "--is-ancestor", ancestor, of])
872 .await
873 .is_ok_and(|o| o.ok())
874}
875
876pub async fn ancestry(repo: &Path, ancestor: &str, of: &str) -> Result<bool> {
881 let out = git_raw(repo, &["merge-base", "--is-ancestor", ancestor, of]).await?;
882 match out.code {
883 Some(0) => Ok(true),
884 Some(1) => Ok(false),
885 _ => bail!(
886 "git merge-base --is-ancestor {ancestor} {of} failed (exit {:?}): {}",
887 out.code,
888 out.stderr
889 ),
890 }
891}
892
893pub async fn commit_of(repo: &Path, rev: &str) -> Option<String> {
895 let spec = format!("{rev}^{{commit}}");
896 let out = git_raw(repo, &["rev-parse", "--verify", "--quiet", &spec])
897 .await
898 .ok()?;
899 (out.ok() && !out.stdout.is_empty()).then_some(out.stdout)
900}
901
902pub async fn branches_containing(repo: &Path, commit: &str) -> Result<Vec<String>> {
904 let out = git(
905 repo,
906 &[
907 "branch",
908 "-a",
909 "--contains",
910 commit,
911 "--format=%(refname:short)",
912 ],
913 )
914 .await?;
915 Ok(out
916 .lines()
917 .map(str::trim)
918 .filter(|l| !l.is_empty() && !l.ends_with("/HEAD") && !l.contains("HEAD detached"))
919 .map(str::to_owned)
920 .collect())
921}
922
923pub async fn cherry_pick(worktree: &Path, commit: &str) -> Result<()> {
927 let out = git_raw(
928 worktree,
929 &[
930 "-c",
931 "user.name=magi candidate",
932 "-c",
933 "user.email=magi@localhost",
934 "cherry-pick",
935 "-x",
936 commit,
937 ],
938 )
939 .await?;
940 if out.ok() {
941 return Ok(());
942 }
943 let _ = git_raw(worktree, &["cherry-pick", "--abort"]).await;
944 bail!(
945 "cherry-pick of {commit} failed: {}",
946 if out.stderr.is_empty() {
947 out.stdout
948 } else {
949 out.stderr
950 }
951 )
952}
953
954pub async fn tree_of(repo: &Path, rev: &str) -> Result<String> {
956 git(repo, &["rev-parse", &format!("{rev}^{{tree}}")]).await
957}
958
959pub async fn rev_exists(repo: &Path, rev: &str) -> bool {
961 git_raw(repo, &["rev-parse", "--verify", "--quiet", rev])
962 .await
963 .is_ok_and(|o| o.ok())
964}
965
966#[cfg(test)]
967mod tests {
968 use super::*;
969
970 #[test]
971 fn worktree_holder_is_read_from_the_porcelain_listing() {
972 let listing = "worktree /repo\nHEAD aaa\nbranch refs/heads/main\n\n\
973 worktree /wt/cand-A\nHEAD bbb\nbranch refs/heads/magi/f82f/A\n\n\
974 worktree /wt/detached\nHEAD ccc\ndetached\n";
975 assert_eq!(
976 parse_worktree_holder(listing, "magi/f82f/A"),
977 Some(PathBuf::from("/wt/cand-A"))
978 );
979 assert_eq!(parse_worktree_holder(listing, "magi/f82f"), None);
980 assert_eq!(parse_worktree_holder(listing, "other"), None);
981 }
982
983 async fn scratch() -> (tempfile::TempDir, PathBuf) {
984 let dir = tempfile::tempdir().unwrap();
985 let repo = dir.path().join("repo");
986 tokio::fs::create_dir_all(&repo).await.unwrap();
987 git(&repo, &["init", "-b", "main"]).await.unwrap();
988 git(&repo, &["config", "user.name", "test"]).await.unwrap();
989 git(&repo, &["config", "user.email", "test@example.com"])
990 .await
991 .unwrap();
992 tokio::fs::write(repo.join("a.txt"), "one\n").await.unwrap();
993 git(&repo, &["add", "-A"]).await.unwrap();
994 git(&repo, &["commit", "-m", "init"]).await.unwrap();
995 (dir, repo)
996 }
997
998 #[tokio::test]
999 async fn a_branch_rebases_onto_a_moved_base_and_says_when_it_cannot() {
1000 let (_g, repo) = scratch().await;
1001
1002 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1004 tokio::fs::write(repo.join("b.txt"), "side\n")
1005 .await
1006 .unwrap();
1007 git(&repo, &["add", "-A"]).await.unwrap();
1008 git(&repo, &["commit", "-m", "side work"]).await.unwrap();
1009
1010 git(&repo, &["checkout", "main"]).await.unwrap();
1013 tokio::fs::write(repo.join("c.txt"), "main\n")
1014 .await
1015 .unwrap();
1016 git(&repo, &["add", "-A"]).await.unwrap();
1017 git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
1018
1019 let scratch_tree = repo.parent().unwrap().join("rebase-scratch");
1020 let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
1021 .await
1022 .unwrap();
1023 assert!(clean.is_none(), "a disjoint change rebases: {clean:?}");
1024 assert_eq!(
1025 commits_ahead(&repo, "main", "side").await.unwrap(),
1026 1,
1027 "one commit, replayed onto the new base"
1028 );
1029 assert!(
1030 !scratch_tree.exists(),
1031 "the throwaway worktree is not left behind"
1032 );
1033
1034 git(&repo, &["checkout", "-b", "clash"]).await.unwrap();
1036 tokio::fs::write(repo.join("a.txt"), "clash\n")
1037 .await
1038 .unwrap();
1039 git(&repo, &["add", "-A"]).await.unwrap();
1040 git(&repo, &["commit", "-m", "clash"]).await.unwrap();
1041 git(&repo, &["checkout", "main"]).await.unwrap();
1042 tokio::fs::write(repo.join("a.txt"), "main edit\n")
1043 .await
1044 .unwrap();
1045 git(&repo, &["add", "-A"]).await.unwrap();
1046 git(&repo, &["commit", "-m", "main edit"]).await.unwrap();
1047
1048 let before = rev_parse(&repo, "clash").await.unwrap();
1049 let why = rebase_branch_in_temp(&repo, &scratch_tree, "clash", "main")
1050 .await
1051 .unwrap()
1052 .expect("a same-line clash cannot be rebased silently");
1053 assert!(
1054 why.to_lowercase().contains("conflict"),
1055 "the reason is what git said, which is what a person needs: {why}"
1056 );
1057 assert_eq!(
1058 rev_parse(&repo, "clash").await.unwrap(),
1059 before,
1060 "a failed rebase leaves the branch exactly where it was"
1061 );
1062 assert!(!scratch_tree.exists(), "and cleans up after itself");
1063 }
1064
1065 #[tokio::test]
1066 async fn merge_squash_folds_the_branch_into_one_commit_under_the_given_message() {
1067 let (_g, repo) = scratch().await;
1068 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1069 for name in ["b.txt", "c.txt"] {
1070 tokio::fs::write(repo.join(name), "side\n").await.unwrap();
1071 git(&repo, &["add", "-A"]).await.unwrap();
1072 git(
1073 &repo,
1074 &["commit", "-m", "magi: candidate A (uncommitted work)"],
1075 )
1076 .await
1077 .unwrap();
1078 }
1079 git(&repo, &["checkout", "main"]).await.unwrap();
1080 let before = rev_parse(&repo, "main").await.unwrap();
1081
1082 let out = merge_squash(&repo, "side", "an explicit subject")
1083 .await
1084 .unwrap();
1085 assert!(out.ok(), "{}", out.stderr);
1086 assert_eq!(
1087 commits_ahead(&repo, &before, "main").await.unwrap(),
1088 1,
1089 "squash adds exactly one commit onto the tip, not one per candidate commit"
1090 );
1091 let subject = git(&repo, &["log", "-1", "--format=%s"]).await.unwrap();
1092 assert_eq!(
1093 subject, "an explicit subject",
1094 "the candidate's own placeholder subject must not survive: {subject}"
1095 );
1096 }
1097
1098 #[tokio::test]
1099 async fn merge_ff_only_fast_forwards_a_branch_already_rebased_onto_the_tip() {
1100 let (_g, repo) = scratch().await;
1101 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1102 tokio::fs::write(repo.join("b.txt"), "side\n")
1103 .await
1104 .unwrap();
1105 git(&repo, &["add", "-A"]).await.unwrap();
1106 git(&repo, &["commit", "-m", "side work"]).await.unwrap();
1107 git(&repo, &["checkout", "main"]).await.unwrap();
1108
1109 let before = rev_parse(&repo, "side").await.unwrap();
1110 let out = merge_ff_only(&repo, "side").await.unwrap();
1111 assert!(out.ok(), "{}", out.stderr);
1112 assert_eq!(
1113 rev_parse(&repo, "main").await.unwrap(),
1114 before,
1115 "a fast-forward moves the base tip to the branch, no merge commit"
1116 );
1117 }
1118
1119 #[tokio::test]
1120 async fn merge_ff_only_refuses_to_write_a_merge_commit() {
1121 let (_g, repo) = scratch().await;
1122 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1123 tokio::fs::write(repo.join("b.txt"), "side\n")
1124 .await
1125 .unwrap();
1126 git(&repo, &["add", "-A"]).await.unwrap();
1127 git(&repo, &["commit", "-m", "side work"]).await.unwrap();
1128
1129 git(&repo, &["checkout", "main"]).await.unwrap();
1131 tokio::fs::write(repo.join("c.txt"), "main\n")
1132 .await
1133 .unwrap();
1134 git(&repo, &["add", "-A"]).await.unwrap();
1135 git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
1136
1137 let before = rev_parse(&repo, "main").await.unwrap();
1138 let out = merge_ff_only(&repo, "side").await.unwrap();
1139 assert!(!out.ok(), "a divergent branch cannot fast-forward");
1140 assert_eq!(
1141 rev_parse(&repo, "main").await.unwrap(),
1142 before,
1143 "a refused fast-forward must not touch main"
1144 );
1145 }
1146
1147 #[tokio::test]
1148 async fn a_sibling_worktree_stays_stale_after_a_rebase_until_synced() {
1149 let (guard, repo) = scratch().await;
1150
1151 git(&repo, &["branch", "side"]).await.unwrap();
1155 let side_wt = guard.path().join("side-wt");
1156 git(
1157 &repo,
1158 &["worktree", "add", &side_wt.to_string_lossy(), "side"],
1159 )
1160 .await
1161 .unwrap();
1162 tokio::fs::write(side_wt.join("b.txt"), "candidate\n")
1163 .await
1164 .unwrap();
1165 git(&side_wt, &["add", "-A"]).await.unwrap();
1166 git(&side_wt, &["commit", "-m", "side work"]).await.unwrap();
1167
1168 git(&repo, &["checkout", "main"]).await.unwrap();
1170 tokio::fs::write(repo.join("c.txt"), "main\n")
1171 .await
1172 .unwrap();
1173 git(&repo, &["add", "-A"]).await.unwrap();
1174 git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
1175
1176 let scratch_tree = guard.path().join("rebase-scratch");
1178 let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
1179 .await
1180 .unwrap();
1181 assert!(clean.is_none());
1182
1183 assert_eq!(
1187 rev_parse(&side_wt, "HEAD").await.unwrap(),
1188 rev_parse(&repo, "side").await.unwrap(),
1189 "HEAD follows the moved ref"
1190 );
1191 assert!(
1192 !side_wt.join("c.txt").exists(),
1193 "stale until synced: main's new file has not reached this worktree's disk"
1194 );
1195
1196 sync_to_head(&side_wt).await.unwrap();
1197 assert!(side_wt.join("c.txt").is_file(), "synced now");
1198 assert!(
1199 side_wt.join("b.txt").is_file(),
1200 "the worktree's own committed work survives the sync"
1201 );
1202 assert!(is_clean(&side_wt).await.unwrap());
1203 }
1204
1205 #[tokio::test]
1206 async fn clean_repo_reports_clean_then_dirty() {
1207 let (_g, repo) = scratch().await;
1208 assert!(is_clean(&repo).await.unwrap());
1209 tokio::fs::write(repo.join("a.txt"), "two\n").await.unwrap();
1210 assert!(!is_clean(&repo).await.unwrap());
1211 }
1212
1213 async fn track(repo: &Path, name: &str, body: &str) {
1214 let p = repo.join(name);
1215 if let Some(d) = p.parent() {
1216 tokio::fs::create_dir_all(d).await.unwrap();
1217 }
1218 tokio::fs::write(&p, body).await.unwrap();
1219 git(repo, &["add", name]).await.unwrap();
1220 git(
1221 repo,
1222 &[
1223 "-c",
1224 "user.name=t",
1225 "-c",
1226 "user.email=t@localhost",
1227 "commit",
1228 "-q",
1229 "-m",
1230 "seed",
1231 ],
1232 )
1233 .await
1234 .unwrap();
1235 }
1236
1237 #[tokio::test]
1238 async fn rescue_withholds_a_foreign_lockfile() {
1239 let (_g, repo) = scratch().await;
1240 track(&repo, "web/bun.lock", "a\n").await;
1241 tokio::fs::write(repo.join("web/pnpm-lock.yaml"), "x\n")
1242 .await
1243 .unwrap();
1244 tokio::fs::write(repo.join("web/app.ts"), "real\n")
1245 .await
1246 .unwrap();
1247
1248 let r = rescue_commit(&repo, "rescue").await.unwrap();
1249 assert!(r.committed);
1250 assert_eq!(
1251 r.withheld,
1252 [Stray {
1253 path: "web/pnpm-lock.yaml".to_owned(),
1254 manager: "pnpm".to_owned(),
1255 kept_by: "web/bun.lock".to_owned(),
1256 }]
1257 );
1258 let files = git(&repo, &["show", "--name-only", "--format=", "HEAD"])
1259 .await
1260 .unwrap();
1261 assert!(files.contains("web/app.ts"), "{files}");
1262 assert!(!files.contains("pnpm-lock"), "{files}");
1263 assert!(repo.join("web/pnpm-lock.yaml").is_file(), "not deleted");
1264 }
1265
1266 #[tokio::test]
1267 async fn rescue_with_only_a_stray_commits_nothing() {
1268 let (_g, repo) = scratch().await;
1269 track(&repo, "bun.lock", "a\n").await;
1270 tokio::fs::write(repo.join("yarn.lock"), "x\n")
1271 .await
1272 .unwrap();
1273 let r = rescue_commit(&repo, "rescue").await.unwrap();
1274 assert!(!r.committed);
1275 assert_eq!(r.withheld.len(), 1);
1276 }
1277
1278 #[tokio::test]
1279 async fn rescue_keeps_a_same_manager_lockfile_update() {
1280 let (_g, repo) = scratch().await;
1281 track(&repo, "bun.lock", "a\n").await;
1282 tokio::fs::write(repo.join("bun.lock"), "b\n")
1283 .await
1284 .unwrap();
1285 let r = rescue_commit(&repo, "rescue").await.unwrap();
1286 assert!(r.committed);
1287 assert!(r.withheld.is_empty());
1288 let files = git(&repo, &["show", "--name-only", "--format=", "HEAD"])
1289 .await
1290 .unwrap();
1291 assert_eq!(files, "bun.lock");
1292 }
1293
1294 #[tokio::test]
1295 async fn rescue_keeps_the_first_lockfile_in_a_bare_directory() {
1296 let (_g, repo) = scratch().await;
1297 track(&repo, "other/bun.lock", "a\n").await;
1298 tokio::fs::create_dir_all(repo.join("web")).await.unwrap();
1299 tokio::fs::write(repo.join("web/package-lock.json"), "{}\n")
1300 .await
1301 .unwrap();
1302 let r = rescue_commit(&repo, "rescue").await.unwrap();
1303 assert!(r.committed);
1304 assert!(r.withheld.is_empty());
1305 }
1306
1307 #[test]
1308 fn a_cargo_lock_is_foreign_only_without_a_cargo_toml() {
1309 let s = |v: &[&str]| v.iter().map(|x| (*x).to_owned()).collect::<Vec<_>>();
1310 assert_eq!(stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&[])).len(), 1);
1311 assert!(stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&["a/Cargo.toml"])).is_empty());
1312 assert!(stray_lockfiles(&s(&["a/Cargo.lock", "a/Cargo.toml"]), &s(&[])).is_empty());
1313 assert_eq!(
1315 stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&["Cargo.toml"])).len(),
1316 1
1317 );
1318 }
1319
1320 #[tokio::test]
1321 async fn worktree_lifecycle_and_diff() {
1322 let (guard, repo) = scratch().await;
1323 let base = rev_parse(&repo, "HEAD").await.unwrap();
1324 let wt = guard.path().join("wt-a");
1325 worktree_add_branch(&repo, &wt, "magi/test/a", &base)
1326 .await
1327 .unwrap();
1328 tokio::fs::write(wt.join("b.txt"), "candidate\n")
1329 .await
1330 .unwrap();
1331
1332 assert!(commit_all(&wt, "candidate work").await.unwrap());
1333 assert!(!commit_all(&wt, "nothing left").await.unwrap());
1334
1335 assert_eq!(commits_ahead(&wt, &base, "HEAD").await.unwrap(), 1);
1336 let patch = diff(&wt, &base, "HEAD").await.unwrap();
1337 assert!(patch.contains("b.txt"), "patch was: {patch}");
1338 assert_eq!(
1339 changed_files(&wt, &base, "HEAD").await.unwrap(),
1340 ["b.txt".to_owned()]
1341 );
1342
1343 let author = git(&wt, &["log", "-1", "--format=%an <%ae>"])
1345 .await
1346 .unwrap();
1347 assert_eq!(author, "magi candidate <magi@localhost>");
1348
1349 assert!(worktree_remove(&repo, &wt).await.unwrap());
1350 assert!(branch_exists(&repo, "magi/test/a").await.unwrap());
1351 assert!(branch_delete(&repo, "magi/test/a").await.unwrap());
1352 assert!(!branch_exists(&repo, "magi/test/a").await.unwrap());
1353 }
1354
1355 #[tokio::test]
1356 async fn worktree_scoped_hooks_path_does_not_leak_to_primary() {
1357 let (guard, repo) = scratch().await;
1358 let base = rev_parse(&repo, "HEAD").await.unwrap();
1359 let wt = guard.path().join("wt-h");
1360 worktree_add_branch(&repo, &wt, "magi/test/h", &base)
1361 .await
1362 .unwrap();
1363 let hooks = guard.path().join("hooks");
1364 tokio::fs::create_dir_all(&hooks).await.unwrap();
1365
1366 assert!(enable_worktree_config(&repo).await.unwrap());
1367 set_worktree_hooks_path(&wt, &hooks).await.unwrap();
1368
1369 let in_wt = git(&wt, &["config", "--get", "core.hooksPath"])
1370 .await
1371 .unwrap();
1372 assert!(!in_wt.is_empty());
1373 let in_primary = git_raw(&repo, &["config", "--get", "core.hooksPath"])
1374 .await
1375 .unwrap();
1376 assert!(
1377 !in_primary.ok(),
1378 "primary worktree must keep its own hooks: {in_primary:?}"
1379 );
1380
1381 disable_worktree_config(&repo).await.unwrap();
1382 }
1383
1384 #[tokio::test]
1385 async fn worktree_config_stays_on_while_a_sibling_run_still_holds_it() {
1386 let (_g, repo) = scratch().await;
1387
1388 acquire_worktree_config(&repo).await.unwrap();
1391 acquire_worktree_config(&repo).await.unwrap();
1392
1393 let on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
1394 .await
1395 .unwrap();
1396 assert_eq!(on, "true");
1397
1398 release_worktree_config(&repo).await.unwrap();
1402 let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
1403 .await
1404 .unwrap();
1405 assert_eq!(
1406 still_on, "true",
1407 "a sibling run's release must not disable the setting for the one still working"
1408 );
1409
1410 release_worktree_config(&repo).await.unwrap();
1412 let after = git_raw(&repo, &["config", "--get", "extensions.worktreeConfig"])
1413 .await
1414 .unwrap();
1415 assert!(
1416 !after.ok(),
1417 "the last release must turn the setting back off: {after:?}"
1418 );
1419 }
1420
1421 #[tokio::test]
1422 async fn worktree_config_already_on_before_magi_touched_it_is_left_alone() {
1423 let (_g, repo) = scratch().await;
1424 git(&repo, &["config", "extensions.worktreeConfig", "true"])
1425 .await
1426 .unwrap();
1427
1428 acquire_worktree_config(&repo).await.unwrap();
1433 release_worktree_config(&repo).await.unwrap();
1434
1435 let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
1436 .await
1437 .unwrap();
1438 assert_eq!(still_on, "true");
1439 }
1440
1441 #[tokio::test]
1442 async fn local_exclude_is_idempotent() {
1443 let (_g, repo) = scratch().await;
1444 local_exclude(&repo, "/.magi/").await.unwrap();
1445 local_exclude(&repo, "/.magi/").await.unwrap();
1446 let path = repo.join(".git/info/exclude");
1447 let body = tokio::fs::read_to_string(&path).await.unwrap();
1448 assert_eq!(body.matches("/.magi/").count(), 1);
1449 }
1450}