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 #[cfg(test)]
35 crate::web::request_cost::git();
36 let out = Command::new("git")
37 .args(args)
38 .current_dir(cwd)
39 .quiet()
40 .env("GIT_TERMINAL_PROMPT", "0")
43 .env("GIT_EDITOR", "true")
44 .stdin(Stdio::null())
45 .output()
46 .await
47 .with_context(|| format!("spawn git {}", args.join(" ")))?;
48 Ok(GitOut {
49 code: out.status.code(),
50 stdout: String::from_utf8_lossy(&out.stdout).trim_end().to_owned(),
51 stderr: String::from_utf8_lossy(&out.stderr).trim_end().to_owned(),
52 })
53}
54
55pub(crate) fn path_arg(path: &Path) -> String {
58 #[cfg(windows)]
59 let unicode = path.to_str().is_some();
60 let path = path.to_string_lossy();
61 #[cfg(windows)]
62 {
63 if unicode {
64 windows_cli_path(&path)
65 } else {
66 path.into_owned()
67 }
68 }
69 #[cfg(not(windows))]
70 {
71 path.into_owned()
72 }
73}
74
75#[cfg(any(windows, test))]
76fn windows_cli_path(path: &str) -> String {
77 let path = path.replace('\\', "/");
78 if path.starts_with("//?/")
79 && path[4..].split('/').any(|part| {
80 let name = part.split('.').next().unwrap_or("").to_ascii_uppercase();
81 part.ends_with(['.', ' '])
82 || matches!(
83 name.as_str(),
84 "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
85 )
86 || (name.len() == 4
87 && (name.starts_with("COM") || name.starts_with("LPT"))
88 && matches!(name.as_bytes()[3], b'1'..=b'9'))
89 })
90 {
91 return path;
94 }
95 if let Some(unc) = path.strip_prefix("//?/UNC/") {
96 return format!("//{unc}");
97 }
98 if let Some(drive) = path.strip_prefix("//?/")
99 && drive.as_bytes().get(1) == Some(&b':')
100 && drive.as_bytes().get(2) == Some(&b'/')
101 && drive.as_bytes()[0].is_ascii_alphabetic()
102 {
103 return drive.to_owned();
104 }
105 path
106}
107
108pub(crate) fn canonical_output_path(value: &str) -> Result<PathBuf> {
111 let path = PathBuf::from(value);
112 let canonical = path.canonicalize()?;
113 #[cfg(windows)]
114 let same_path = windows_cli_path(path.to_str().context("non UTF-8 Git path")?)
115 == windows_cli_path(canonical.to_str().context("non UTF-8 canonical Git path")?);
116 #[cfg(not(windows))]
117 let same_path = path == canonical;
118 ensure!(same_path, "noncanonical Git path: {}", path.display());
119 Ok(canonical)
120}
121
122pub async fn fetch_origin(cwd: &Path, timeout: std::time::Duration) -> Result<()> {
134 let url = git(cwd, &["remote", "get-url", "origin"]).await?;
135 #[cfg(test)]
136 crate::web::request_cost::git();
137 let fut = Command::new("git")
138 .args([
139 "fetch",
140 "--quiet",
141 "--no-tags",
142 "--no-recurse-submodules",
143 "--no-write-fetch-head",
144 "--",
145 url.as_str(),
146 "+refs/heads/*:refs/remotes/origin/*",
147 ])
148 .current_dir(cwd)
149 .quiet()
150 .env("GIT_TERMINAL_PROMPT", "0")
151 .stdin(Stdio::null())
152 .kill_on_drop(true)
153 .output();
154 let out = tokio::time::timeout(timeout, fut)
155 .await
156 .map_err(|_| anyhow::anyhow!("git fetch timed out after {}s", timeout.as_secs()))?
157 .context("spawn git fetch")?;
158 if !out.status.success() {
159 bail!(
160 "git fetch failed ({}): {}",
161 crate::notices::exit_status(out.status.code()),
162 String::from_utf8_lossy(&out.stderr).trim_end()
163 );
164 }
165 Ok(())
166}
167
168pub async fn git(cwd: &Path, args: &[&str]) -> Result<String> {
170 let out = git_raw(cwd, args).await?;
171 if !out.ok() {
172 bail!(
173 "git {} failed in {} ({}): {}",
174 args.join(" "),
175 cwd.display(),
176 crate::notices::exit_status(out.code),
177 if out.stderr.is_empty() {
178 out.stdout.as_str()
179 } else {
180 out.stderr.as_str()
181 }
182 );
183 }
184 Ok(out.stdout)
185}
186
187pub async fn toplevel(path: &Path) -> Result<PathBuf> {
189 let out = git(path, &["rev-parse", "--show-toplevel"]).await?;
190 Ok(PathBuf::from(out))
191}
192
193pub async fn rev_parse(repo: &Path, rev: &str) -> Result<String> {
195 git(repo, &["rev-parse", rev]).await
196}
197
198pub async fn current_branch(repo: &Path) -> Result<Option<String>> {
200 let out = git_raw(repo, &["symbolic-ref", "--quiet", "--short", "HEAD"]).await?;
201 Ok(if out.ok() && !out.stdout.is_empty() {
202 Some(out.stdout)
203 } else {
204 None
205 })
206}
207
208pub fn remote_head_branch(remote: &str, symref: &str) -> Option<String> {
213 symref
214 .trim()
215 .strip_prefix(&format!("refs/remotes/{remote}/"))
216 .filter(|b| !b.is_empty() && *b != "HEAD")
217 .map(str::to_owned)
218}
219
220pub async fn ensure_remote_head(repo: &Path, remote: &str, base: &str) {
226 let head = format!("refs/remotes/{remote}/HEAD");
227 if git_raw(repo, &["symbolic-ref", "--quiet", &head])
228 .await
229 .is_ok_and(|o| o.ok())
230 {
231 return;
232 }
233 let target = format!("refs/remotes/{remote}/{base}");
234 let _ = git_raw(repo, &["symbolic-ref", &head, &target]).await;
235}
236
237fn symref_branch(out: &str) -> Option<String> {
240 out.lines()
241 .find_map(|l| l.strip_prefix("ref: refs/heads/"))
242 .and_then(|l| l.split_whitespace().next())
243 .map(str::to_owned)
244}
245
246pub async fn merge_base_branch(
253 repo: &Path,
254 remote: &str,
255 explicit: Option<&str>,
256) -> Result<String> {
257 if let Some(b) = explicit.map(str::trim).filter(|b| !b.is_empty()) {
258 return Ok(b.to_owned());
259 }
260 let head = format!("refs/remotes/{remote}/HEAD");
261 let read = || async {
262 let out = git_raw(repo, &["symbolic-ref", "--quiet", &head])
263 .await
264 .ok()?;
265 if out.ok() {
266 remote_head_branch(remote, &out.stdout)
267 } else {
268 None
269 }
270 };
271 if let Some(b) = read().await {
272 return Ok(b);
273 }
274 let set = git_raw(repo, &["remote", "set-head", remote, "-a"]).await;
275 if let Some(b) = read().await {
276 return Ok(b);
277 }
278 if let Ok(o) = git_raw(repo, &["ls-remote", "--symref", remote, "HEAD"]).await
283 && o.ok()
284 && let Some(b) = symref_branch(&o.stdout)
285 {
286 return Ok(b);
287 }
288 let why = match set {
289 Ok(o) if !o.ok() => o.stderr.lines().next().unwrap_or("").trim().to_owned(),
290 Ok(_) => "the remote reported no default branch".to_owned(),
291 Err(e) => e.to_string(),
292 };
293 bail!(
294 "cannot tell which branch of `{remote}` is the base ({why}): set [merge] base \
295 (and remote) in magi.toml, or run `git remote set-head {remote} -a`. magi does \
296 not fall back to the checked-out branch, which may be detached or stale"
297 )
298}
299
300pub async fn is_clean(repo: &Path) -> Result<bool> {
302 Ok(git(repo, &["status", "--porcelain"]).await?.is_empty())
303}
304
305pub async fn status_porcelain(repo: &Path) -> Result<String> {
307 git(repo, &["status", "--porcelain"]).await
308}
309
310pub async fn worktree_add_branch(repo: &Path, path: &Path, branch: &str, base: &str) -> Result<()> {
312 if let Some(parent) = path.parent() {
313 tokio::fs::create_dir_all(parent).await.ok();
314 }
315 let path_s = path_arg(path);
316 git(repo, &["worktree", "add", "-b", branch, &path_s, base])
317 .await
318 .map(|_| ())
319}
320
321pub(crate) async fn worktree_add_existing(
323 repo: &Path,
324 path: &Path,
325 branch: &str,
326 force: bool,
327) -> Result<()> {
328 if let Some(parent) = path.parent() {
329 tokio::fs::create_dir_all(parent).await.ok();
330 }
331 let path_s = path_arg(path);
332 if force {
333 git(repo, &["worktree", "add", "--force", &path_s, branch]).await
334 } else {
335 git(repo, &["worktree", "add", &path_s, branch]).await
336 }
337 .map(|_| ())
338}
339
340pub async fn worktree_add_detached(repo: &Path, path: &Path, rev: &str) -> Result<()> {
342 if let Some(parent) = path.parent() {
343 tokio::fs::create_dir_all(parent).await.ok();
344 }
345 let path_s = path_arg(path);
346 git(repo, &["worktree", "add", "--detach", &path_s, rev])
347 .await
348 .map(|_| ())
349}
350
351pub async fn reset_detached(worktree: &Path, rev: &str) -> Result<()> {
353 reset_detached_keep_ignored(worktree, rev).await?;
354 clean_all(worktree).await
355}
356
357pub async fn reset_detached_keep_ignored(worktree: &Path, rev: &str) -> Result<()> {
360 git(worktree, &["checkout", "--detach", rev]).await?;
361 git(worktree, &["reset", "--hard", rev]).await.map(|_| ())
362}
363
364pub async fn worktree_holding(repo: &Path, branch: &str) -> Result<Option<PathBuf>> {
369 let listing = git(repo, &["worktree", "list", "--porcelain"]).await?;
370 Ok(parse_worktree_holder(&listing, branch))
371}
372
373fn parse_worktree_holder(listing: &str, branch: &str) -> Option<PathBuf> {
374 let want = format!("refs/heads/{branch}");
375 let mut path: Option<PathBuf> = None;
376 for line in listing.lines() {
377 if let Some(p) = line.strip_prefix("worktree ") {
378 path = Some(PathBuf::from(p));
379 } else if line.strip_prefix("branch ") == Some(want.as_str()) {
380 return path;
381 }
382 }
383 None
384}
385
386pub async fn worktree_remove(repo: &Path, path: &Path) -> Result<bool> {
390 let path_s = path_arg(path);
391 let out = git_raw(repo, &["worktree", "remove", "--force", &path_s]).await?;
392 if out.ok() {
393 return Ok(true);
394 }
395 if !path.exists() {
397 git_raw(repo, &["worktree", "prune"]).await?;
398 }
399 Ok(false)
400}
401
402pub async fn worktree_remove_clean(repo: &Path, path: &Path) -> Result<bool> {
406 let path_s = path_arg(path);
407 Ok(git_raw(repo, &["worktree", "remove", &path_s]).await?.ok())
408}
409
410pub async fn remove_worktree_from_linked(dir: &Path) {
419 let Ok(link) = std::fs::read_to_string(dir.join(".git")) else {
420 return;
421 };
422 let Some(admin) = link.strip_prefix("gitdir:").map(str::trim) else {
423 return;
424 };
425 let admin = Path::new(admin);
428 let Some(common) = admin.parent().and_then(Path::parent) else {
429 return;
430 };
431 let common_s = common.to_string_lossy();
432 let _ = git_raw(dir, &["--git-dir", &common_s, "worktree", "prune"]).await;
433}
434
435pub async fn worktree_prune(repo: &Path) -> Result<()> {
444 git(repo, &["worktree", "prune"]).await.map(|_| ())
445}
446
447pub async fn branch_delete(repo: &Path, branch: &str) -> Result<bool> {
449 Ok(git_raw(repo, &["branch", "-D", branch]).await?.ok())
450}
451
452pub async fn branch_exists(repo: &Path, branch: &str) -> Result<bool> {
454 let refname = format!("refs/heads/{branch}");
455 Ok(
456 git_raw(repo, &["show-ref", "--verify", "--quiet", &refname])
457 .await?
458 .ok(),
459 )
460}
461
462pub async fn remote_has_branch(repo: &Path, remote: &str, branch: &str) -> Result<bool> {
465 let refname = format!("refs/heads/{branch}");
466 let out = git_raw(repo, &["ls-remote", "--exit-code", remote, &refname]).await?;
467 match out.code {
468 Some(0) => Ok(true),
469 Some(2) => Ok(false),
470 code => bail!(
471 "git ls-remote {remote} failed ({}): {}",
472 crate::notices::exit_status(code),
473 out.stderr
474 ),
475 }
476}
477
478pub async fn diff(worktree: &Path, base: &str, head: &str) -> Result<String> {
480 let range = format!("{base}...{head}");
481 git(
482 worktree,
483 &["diff", "--no-color", "--no-ext-diff", "-M", &range],
484 )
485 .await
486}
487
488pub async fn diff_stat(worktree: &Path, base: &str, head: &str) -> Result<String> {
490 let range = format!("{base}...{head}");
491 git(worktree, &["diff", "--no-color", "--stat", &range]).await
492}
493
494pub async fn changed_lines(worktree: &Path, base: &str, head: &str) -> Option<usize> {
498 let out = git_raw(worktree, &["diff", "--numstat", base, head])
499 .await
500 .ok()?;
501 if !out.ok() {
502 return None;
503 }
504 let mut total = 0usize;
505 for line in out.stdout.lines().filter(|l| !l.trim().is_empty()) {
506 let mut cols = line.split('\t');
507 let added: usize = cols.next()?.parse().ok()?;
508 let removed: usize = cols.next()?.parse().ok()?;
509 total = total.saturating_add(added).saturating_add(removed);
510 }
511 Some(total)
512}
513
514pub async fn restore_to(worktree: &Path, rev: &str) -> Result<()> {
518 git(worktree, &["reset", "--hard", "-q", rev]).await?;
519 git(worktree, &["clean", "-ffdq"]).await?;
522 git(
528 worktree,
529 &[
530 "submodule",
531 "--quiet",
532 "update",
533 "--recursive",
534 "--force",
535 "--checkout",
536 ],
537 )
538 .await?;
539 git(
540 worktree,
541 &[
542 "submodule",
543 "--quiet",
544 "foreach",
545 "--recursive",
546 "git clean -ffdq",
547 ],
548 )
549 .await?;
550 Ok(())
551}
552
553pub async fn changed_files(worktree: &Path, base: &str, head: &str) -> Result<Vec<String>> {
555 let range = format!("{base}...{head}");
556 let out = git(worktree, &["diff", "--name-only", &range]).await?;
557 Ok(out.lines().map(str::to_owned).collect())
558}
559
560pub async fn commit_log(worktree: &Path, base: &str, head: &str) -> Result<Vec<(String, String)>> {
564 let range = format!("{base}..{head}");
565 let out = git(
566 worktree,
567 &[
568 "log",
569 "--reverse",
570 "--no-color",
571 "--format=%s%x1f%b%x00",
572 &range,
573 ],
574 )
575 .await?;
576 Ok(out
577 .split('\0')
578 .filter_map(|rec| {
579 let rec = rec.trim_start_matches('\n');
580 if rec.trim().is_empty() {
581 return None;
582 }
583 let (subject, body) = rec.split_once('\x1f').unwrap_or((rec, ""));
584 Some((subject.trim().to_owned(), body.trim().to_owned()))
585 })
586 .collect())
587}
588
589pub async fn log_oneline(worktree: &Path, base: &str, head: &str) -> Result<String> {
591 let range = format!("{base}..{head}");
592 git(
593 worktree,
594 &["log", "--reverse", "--format=%s%n%b%n--", &range],
595 )
596 .await
597}
598
599pub async fn subjects(worktree: &Path, base: &str, head: &str) -> Result<Vec<String>> {
602 let range = format!("{base}..{head}");
603 let out = git(worktree, &["log", "--reverse", "--format=%s%x00", &range]).await?;
604 let mut parts: Vec<String> = out.split('\0').map(|s| s.trim().to_owned()).collect();
605 parts.pop();
607 Ok(parts)
608}
609
610pub async fn commits_ahead(worktree: &Path, base: &str, head: &str) -> Result<usize> {
612 let range = format!("{base}..{head}");
613 let out = git(worktree, &["rev-list", "--count", &range]).await?;
614 Ok(out.trim().parse().unwrap_or(0))
615}
616
617pub async fn commit_all(worktree: &Path, message: &str) -> Result<bool> {
624 if git(worktree, &["status", "--porcelain"]).await?.is_empty() {
625 return Ok(false);
626 }
627 git(worktree, &["add", "-A"]).await?;
628 if !crate::worktree_setup::withheld_paths(worktree)
630 .await
631 .is_empty()
632 {
633 crate::worktree_setup::unstage_products(worktree).await?;
634 if git_raw(worktree, &["diff", "--cached", "--quiet"])
635 .await?
636 .ok()
637 {
638 return Ok(false);
639 }
640 }
641 let out = git_raw(
642 worktree,
643 &[
644 "-c",
645 "user.name=magi candidate",
646 "-c",
647 "user.email=magi@localhost",
648 "commit",
649 "--no-verify",
650 "-m",
651 message,
652 ],
653 )
654 .await?;
655 if !out.ok() {
656 bail!("rescue commit failed: {}", out.stderr);
657 }
658 Ok(true)
659}
660
661#[derive(Debug, Clone, PartialEq, Eq)]
664pub struct Stray {
665 pub path: String,
667 pub manager: String,
669 pub kept_by: String,
672}
673
674#[derive(Debug, Default)]
676pub struct Rescue {
677 pub committed: bool,
679 pub withheld: Vec<Stray>,
681}
682
683fn lock_kind(name: &str) -> Option<(&'static str, &'static str)> {
685 Some(match name {
686 "package-lock.json" | "npm-shrinkwrap.json" => ("node", "npm"),
687 "yarn.lock" => ("node", "yarn"),
688 "pnpm-lock.yaml" => ("node", "pnpm"),
689 "bun.lock" | "bun.lockb" => ("node", "bun"),
690 "poetry.lock" => ("python", "poetry"),
691 "uv.lock" => ("python", "uv"),
692 "Pipfile.lock" => ("python", "pipenv"),
693 "pdm.lock" => ("python", "pdm"),
694 "Cargo.lock" => ("rust", "cargo"),
695 _ => return None,
696 })
697}
698
699fn split_dir(path: &str) -> (&str, &str) {
700 path.rsplit_once('/').unwrap_or(("", path))
701}
702
703pub fn stray_lockfiles(untracked: &[String], tracked: &[String]) -> Vec<Stray> {
711 let mut out = Vec::new();
712 for path in untracked {
713 let (dir, name) = split_dir(path);
714 let Some((eco, manager)) = lock_kind(name) else {
715 continue;
716 };
717 let beside = |other: &String| split_dir(other).0 == dir;
718 let kept_by = if manager == "cargo" {
719 let has_manifest = tracked
720 .iter()
721 .chain(untracked)
722 .any(|p| beside(p) && split_dir(p).1 == "Cargo.toml");
723 if has_manifest {
724 continue;
725 }
726 "no Cargo.toml in the directory".to_owned()
727 } else {
728 let Some(other) = tracked.iter().find(|p| {
729 beside(p)
730 && lock_kind(split_dir(p).1).is_some_and(|(e, m)| e == eco && m != manager)
731 }) else {
732 continue;
733 };
734 other.clone()
735 };
736 out.push(Stray {
737 path: path.clone(),
738 manager: manager.to_owned(),
739 kept_by,
740 });
741 }
742 out
743}
744
745async fn nul_list(worktree: &Path, args: &[&str]) -> Result<Vec<String>> {
746 let out = git(worktree, args).await?;
747 Ok(out
748 .split('\0')
749 .filter(|s| !s.is_empty())
750 .map(str::to_owned)
751 .collect())
752}
753
754pub async fn snapshot_uncommitted(worktree: &Path, destination: &Path) -> Result<()> {
758 if destination.exists() {
759 if destination.join("complete").exists() {
760 return Ok(());
761 }
762 bail!("earlier recovery snapshot is incomplete; retain original worktree");
763 }
764 std::fs::create_dir_all(destination)?;
765 for (name, args) in [
766 ("status.txt", vec!["status", "--porcelain=v1"]),
767 ("staged.patch", vec!["diff", "--binary", "--cached"]),
768 ("unstaged.patch", vec!["diff", "--binary"]),
769 ] {
770 let out = Command::new("git")
773 .args(&args)
774 .current_dir(worktree)
775 .quiet()
776 .stdin(Stdio::null())
777 .output()
778 .await?;
779 if !out.status.success() {
780 bail!(
781 "recovery snapshot failed: {}",
782 String::from_utf8_lossy(&out.stderr)
783 );
784 }
785 std::fs::write(destination.join(name), out.stdout)?;
786 }
787 let paths = nul_list(
788 worktree,
789 &["ls-files", "-z", "--others", "--exclude-standard"],
790 )
791 .await?;
792 for name in paths {
793 let relative = Path::new(&name);
794 if relative
795 .components()
796 .any(|c| !matches!(c, std::path::Component::Normal(_)))
797 {
798 bail!("unsafe recovery path");
799 }
800 let source = worktree.join(relative);
801 let target = destination.join("untracked").join(relative);
802 std::fs::create_dir_all(target.parent().context("untracked recovery parent")?)?;
803 if std::fs::symlink_metadata(&source)?.file_type().is_symlink() {
804 bail!("untracked symlink requires manual recovery: {name}");
806 }
807 std::fs::copy(source, target)?;
808 }
809 std::fs::write(destination.join("complete"), "snapshot captured\n")?;
810 Ok(())
811}
812
813pub async fn rescue_commit(worktree: &Path, message: &str) -> Result<Rescue> {
819 if git(worktree, &["status", "--porcelain"]).await?.is_empty() {
820 return Ok(Rescue::default());
821 }
822 let untracked = nul_list(
823 worktree,
824 &["ls-files", "-z", "--others", "--exclude-standard"],
825 )
826 .await?;
827 let tracked = nul_list(worktree, &["ls-files", "-z"]).await?;
828 let withheld = stray_lockfiles(&untracked, &tracked);
829
830 git(worktree, &["add", "-A"]).await?;
831 if !withheld.is_empty() {
832 let mut args = vec!["reset", "-q", "--"];
833 args.extend(withheld.iter().map(|s| s.path.as_str()));
834 git(worktree, &args).await?;
835 }
836 crate::worktree_setup::unstage_products(worktree).await?;
837 if git_raw(worktree, &["diff", "--cached", "--quiet"])
838 .await?
839 .ok()
840 {
841 return Ok(Rescue {
842 committed: false,
843 withheld,
844 });
845 }
846 let out = git_raw(
847 worktree,
848 &[
849 "-c",
850 "user.name=magi candidate",
851 "-c",
852 "user.email=magi@localhost",
853 "commit",
854 "--no-verify",
855 "-m",
856 message,
857 ],
858 )
859 .await?;
860 if !out.ok() {
861 bail!("rescue commit failed: {}", out.stderr);
862 }
863 Ok(Rescue {
864 committed: true,
865 withheld,
866 })
867}
868
869pub async fn enable_worktree_config(repo: &Path) -> Result<bool> {
874 let out = git_raw(repo, &["config", "--get", "extensions.worktreeConfig"]).await?;
875 if out.ok() && out.stdout.trim() == "true" {
876 return Ok(false);
877 }
878 git(repo, &["config", "extensions.worktreeConfig", "true"]).await?;
879 Ok(true)
880}
881
882pub async fn disable_worktree_config(repo: &Path) -> Result<()> {
884 git_raw(repo, &["config", "--unset", "extensions.worktreeConfig"]).await?;
885 Ok(())
886}
887
888struct WorktreeConfigRef {
891 count: usize,
893 we_enabled: bool,
899}
900
901static WORKTREE_CONFIG: std::sync::LazyLock<
908 std::sync::Mutex<
909 std::collections::HashMap<PathBuf, std::sync::Arc<tokio::sync::Mutex<WorktreeConfigRef>>>,
910 >,
911> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
912
913fn worktree_config_slot(repo: &Path) -> std::sync::Arc<tokio::sync::Mutex<WorktreeConfigRef>> {
915 let mut map = WORKTREE_CONFIG
916 .lock()
917 .unwrap_or_else(std::sync::PoisonError::into_inner);
918 map.entry(repo.to_path_buf())
919 .or_insert_with(|| {
920 std::sync::Arc::new(tokio::sync::Mutex::new(WorktreeConfigRef {
921 count: 0,
922 we_enabled: false,
923 }))
924 })
925 .clone()
926}
927
928pub async fn acquire_worktree_config(repo: &Path) -> Result<()> {
945 let slot = worktree_config_slot(repo);
946 let mut entry = slot.lock().await;
947 entry.count += 1;
948 if entry.count == 1 {
949 entry.we_enabled = enable_worktree_config(repo).await?;
950 }
951 Ok(())
952}
953
954pub async fn release_worktree_config(repo: &Path) -> Result<()> {
960 let slot = worktree_config_slot(repo);
961 let mut entry = slot.lock().await;
962 entry.count = entry.count.saturating_sub(1);
963 if entry.count == 0 && entry.we_enabled {
964 disable_worktree_config(repo).await?;
965 entry.we_enabled = false;
966 }
967 Ok(())
968}
969
970pub async fn set_worktree_hooks_path(worktree: &Path, hooks_dir: &Path) -> Result<()> {
976 let dir = hooks_dir.to_string_lossy().replace('\\', "/");
977 git(worktree, &["config", "--worktree", "core.hooksPath", &dir])
978 .await
979 .map(|_| ())
980}
981
982pub async fn local_exclude(worktree: &Path, pattern: &str) -> Result<()> {
984 let git_dir = git(worktree, &["rev-parse", "--git-path", "info/exclude"]).await?;
985 let path = worktree.join(git_dir);
986 if let Some(parent) = path.parent() {
987 tokio::fs::create_dir_all(parent).await.ok();
988 }
989 let mut body = tokio::fs::read_to_string(&path).await.unwrap_or_default();
990 if body.lines().any(|l| l.trim() == pattern) {
991 return Ok(());
992 }
993 if !body.is_empty() && !body.ends_with('\n') {
994 body.push('\n');
995 }
996 body.push_str(pattern);
997 body.push('\n');
998 tokio::fs::write(&path, body)
999 .await
1000 .with_context(|| format!("write {}", path.display()))?;
1001 Ok(())
1002}
1003
1004pub async fn merge_no_ff(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
1010 git_raw(
1011 repo,
1012 &["merge", "--no-ff", "--no-edit", "-m", message, branch],
1013 )
1014 .await
1015}
1016
1017pub async fn merge_squash(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
1028 let staged = git_raw(repo, &["merge", "--squash", branch]).await?;
1029 if !staged.ok() {
1030 return Ok(staged);
1031 }
1032 git_raw(repo, &["commit", "-m", message]).await
1033}
1034
1035pub async fn merge_ff_only(repo: &Path, branch: &str) -> Result<GitOut> {
1045 git_raw(repo, &["merge", "--ff-only", branch]).await
1046}
1047
1048pub async fn push(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
1050 git_raw(repo, &["push", "-u", remote, branch]).await
1051}
1052
1053pub async fn push_as(
1056 repo: &Path,
1057 remote: &str,
1058 local: &str,
1059 head: &str,
1060 expected: &str,
1061) -> Result<GitOut> {
1062 let lease = format!("--force-with-lease=refs/heads/{head}:{expected}");
1063 let refspec = format!("refs/heads/{local}:refs/heads/{head}");
1064 git_raw(repo, &["push", &lease, remote, &refspec]).await
1065}
1066
1067pub async fn remote_head(repo: &Path, remote: &str, branch: &str) -> Result<Option<String>> {
1069 let reference = format!("refs/heads/{branch}");
1070 let out = git(repo, &["ls-remote", "--refs", remote, &reference]).await?;
1071 Ok(out.split_whitespace().next().map(str::to_owned))
1072}
1073
1074pub async fn push_rewritten(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
1082 git_raw(repo, &["push", "--force-with-lease", remote, branch]).await
1083}
1084
1085pub async fn push_pinned(
1094 repo: &Path,
1095 remote: &str,
1096 branch: &str,
1097 expected: &str,
1098) -> Result<GitOut> {
1099 let lease = format!("--force-with-lease=refs/heads/{branch}:{expected}");
1100 let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1101 git_raw(repo, &["push", &lease, remote, &refspec]).await
1102}
1103
1104pub async fn cherry(repo: &Path, upstream: &str, head: &str) -> Result<(Vec<String>, Vec<String>)> {
1107 let out = git(repo, &["cherry", upstream, head]).await?;
1108 let (mut unmatched, mut matched) = (Vec::new(), Vec::new());
1109 for line in out.lines() {
1110 if let Some(sha) = line.strip_prefix("+ ") {
1111 unmatched.push(sha.trim().to_owned());
1112 } else if let Some(sha) = line.strip_prefix("- ") {
1113 matched.push(sha.trim().to_owned());
1114 }
1115 }
1116 Ok((unmatched, matched))
1117}
1118
1119#[derive(Debug)]
1121pub struct RebaseRecord {
1122 pub picks: Vec<String>,
1124 pub heads: Vec<String>,
1126}
1127
1128const REBASE_EXEC: &str = "git rev-parse HEAD >> \"$(git rev-parse --git-path magi-rebase-heads)\"";
1129
1130async fn rebase_file(scratch: &Path, name: &str) -> Result<PathBuf> {
1131 let path = git(scratch, &["rev-parse", "--git-path", name]).await?;
1132 let path = Path::new(path.trim());
1133 Ok(if path.is_absolute() {
1134 path.to_path_buf()
1135 } else {
1136 scratch.join(path)
1137 })
1138}
1139
1140async fn full_commit(scratch: &Path, sha: &str) -> Result<String> {
1141 anyhow::ensure!(
1142 !sha.is_empty() && sha.bytes().all(|b| b.is_ascii_hexdigit()),
1143 "invalid rebase commit id: {sha}"
1144 );
1145 rev_parse(scratch, &format!("{sha}^{{commit}}")).await
1146}
1147
1148async fn save_rebase_picks(scratch: &Path) -> Result<()> {
1151 let mut picks = Vec::new();
1152 for name in ["rebase-merge/done", "rebase-merge/git-rebase-todo"] {
1153 let text = std::fs::read_to_string(rebase_file(scratch, name).await?)?;
1154 for line in text.lines().map(str::trim) {
1155 if line.is_empty() || line.starts_with('#') {
1156 continue;
1157 }
1158 let mut words = line.split_whitespace();
1159 match words.next() {
1160 Some("pick" | "p") => {
1161 picks.push(
1162 full_commit(scratch, words.next().context("pick without commit")?).await?,
1163 );
1164 }
1165 Some("exec" | "x")
1166 if line
1167 .split_once(' ')
1168 .is_some_and(|(_, cmd)| cmd == REBASE_EXEC) => {}
1169 _ => bail!("unexpected rebase instruction: {line}"),
1170 }
1171 }
1172 }
1173 let path = rebase_file(scratch, "magi-rebase-picks").await?;
1174 let tmp = path.with_extension("tmp");
1175 std::fs::write(&tmp, picks.join("\n") + "\n")?;
1176 std::fs::rename(tmp, path)?;
1177 Ok(())
1178}
1179
1180pub async fn rebase_record(scratch: &Path) -> Result<RebaseRecord> {
1182 let mut lists = Vec::new();
1183 for name in ["magi-rebase-picks", "magi-rebase-heads"] {
1184 let text = std::fs::read_to_string(rebase_file(scratch, name).await?)
1185 .with_context(|| format!("read {name}"))?;
1186 let mut commits = Vec::new();
1187 for sha in text.lines() {
1188 let full = full_commit(scratch, sha).await?;
1189 anyhow::ensure!(full == sha, "non-full commit id in {name}");
1190 commits.push(full);
1191 }
1192 lists.push(commits);
1193 }
1194 let heads = lists.pop().unwrap();
1195 let picks = lists.pop().unwrap();
1196 anyhow::ensure!(
1197 !picks.is_empty() && picks.len() == heads.len(),
1198 "rebase pick/HEAD count mismatch"
1199 );
1200 Ok(RebaseRecord { picks, heads })
1201}
1202
1203pub fn rebase_said(text: &str) -> String {
1205 text.trim()
1206 .split(['\r', '\n'])
1207 .filter(|line| !line.trim_start().starts_with("Executing:"))
1208 .collect::<Vec<_>>()
1209 .join("\n")
1210}
1211
1212#[derive(Debug, Clone, PartialEq, Eq)]
1214pub enum RebaseStart {
1215 Applied,
1218 Conflicted(String),
1221 Failed(String),
1224}
1225
1226pub async fn rebase_start(
1241 repo: &Path,
1242 scratch: &Path,
1243 branch: &str,
1244 onto: &str,
1245) -> Result<RebaseStart> {
1246 rebase_prepare(repo, scratch, branch).await?;
1247 rebase_execute(repo, scratch, onto).await
1248}
1249
1250#[derive(Debug)]
1252pub struct RebasePreparationError(pub String);
1253
1254impl std::fmt::Display for RebasePreparationError {
1255 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1256 f.write_str(&self.0)
1257 }
1258}
1259
1260impl std::error::Error for RebasePreparationError {}
1261
1262pub(crate) async fn rebase_prepare(repo: &Path, scratch: &Path, branch: &str) -> Result<()> {
1265 if rebase_in_progress(scratch).await {
1266 return Ok(());
1267 }
1268 let result = async {
1269 worktree_remove(repo, scratch).await.ok();
1270 let path = path_arg(scratch);
1271 let args = ["worktree", "add", "--force", &path, branch];
1272 let out = git_raw(repo, &args).await?;
1273 ensure!(
1274 out.ok(),
1275 "git {} (exit {:?}): {}",
1276 args.join(" "),
1277 out.code,
1278 if out.stderr.trim().is_empty() {
1279 &out.stdout
1280 } else {
1281 &out.stderr
1282 }
1283 );
1284 std::fs::write(rebase_file(scratch, "magi-rebase-heads").await?, "")?;
1285 Ok::<_, anyhow::Error>(())
1286 }
1287 .await;
1288 result.map_err(|e| {
1289 RebasePreparationError(format!(
1290 "prepare rebase scratch {}: {e:#}",
1291 scratch.display()
1292 ))
1293 .into()
1294 })
1295}
1296
1297pub(crate) async fn rebase_execute(repo: &Path, scratch: &Path, onto: &str) -> Result<RebaseStart> {
1299 let out = git_raw(
1300 scratch,
1301 &["rebase", "--empty=drop", "--exec", REBASE_EXEC, onto],
1302 )
1303 .await?;
1304 if out.ok() {
1305 worktree_remove(repo, scratch).await.ok();
1306 return Ok(RebaseStart::Applied);
1307 }
1308 let why = rebase_said(&if out.stderr.trim().is_empty() {
1309 out.stdout.trim().to_owned()
1310 } else {
1311 out.stderr.trim().to_owned()
1312 });
1313 if rebase_in_progress(scratch).await {
1314 if let Err(error) = save_rebase_picks(scratch).await {
1315 rebase_abort(repo, scratch).await;
1316 return Ok(RebaseStart::Failed(format!(
1317 "cannot record rebase picks: {error:#}"
1318 )));
1319 }
1320 return Ok(RebaseStart::Conflicted(why));
1321 }
1322 worktree_remove(repo, scratch).await.ok();
1323 Ok(RebaseStart::Failed(why))
1324}
1325
1326pub async fn rebase_in_progress(worktree: &Path) -> bool {
1328 for name in ["rebase-merge", "rebase-apply"] {
1329 let Ok(p) = git(worktree, &["rev-parse", "--git-path", name]).await else {
1330 continue;
1331 };
1332 let p = Path::new(p.trim());
1333 let full = if p.is_absolute() {
1334 p.to_path_buf()
1335 } else {
1336 worktree.join(p)
1337 };
1338 if full.exists() {
1339 return true;
1340 }
1341 }
1342 false
1343}
1344
1345pub async fn unmerged_paths(worktree: &Path) -> Result<Vec<String>> {
1347 let out = git(worktree, &["diff", "--name-only", "--diff-filter=U", "-z"]).await?;
1348 Ok(out
1349 .split('\0')
1350 .filter(|l| !l.is_empty())
1351 .map(str::to_owned)
1352 .collect())
1353}
1354
1355pub async fn rebase_abort(repo: &Path, scratch: &Path) {
1358 git_raw(scratch, &["rebase", "--abort"]).await.ok();
1359 worktree_remove(repo, scratch).await.ok();
1360}
1361
1362pub async fn rebase_branch_in_temp(
1370 repo: &Path,
1371 scratch: &Path,
1372 branch: &str,
1373 onto: &str,
1374) -> Result<Option<String>> {
1375 match rebase_start(repo, scratch, branch, onto).await? {
1376 RebaseStart::Applied => Ok(None),
1377 RebaseStart::Failed(why) => Ok(Some(why)),
1378 RebaseStart::Conflicted(why) => {
1379 rebase_abort(repo, scratch).await;
1380 Ok(Some(why))
1381 }
1382 }
1383}
1384
1385pub async fn sync_to_head(worktree: &Path) -> Result<()> {
1398 reset_hard_head(worktree).await?;
1399 clean_all(worktree).await
1400}
1401
1402pub async fn reset_hard_head(worktree: &Path) -> Result<()> {
1404 git(worktree, &["reset", "--hard", "HEAD"])
1405 .await
1406 .map(|_| ())
1407}
1408
1409pub async fn clean_all(worktree: &Path) -> Result<()> {
1411 git(worktree, &["clean", "-fdx"]).await.map(|_| ())
1412}
1413
1414pub async fn fetch(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
1433 let refspec = format!("+refs/heads/{branch}:refs/remotes/{remote}/{branch}");
1434 git_raw(repo, &["fetch", "--quiet", remote, &refspec]).await
1435}
1436
1437pub async fn merge_base(repo: &Path, a: &str, b: &str) -> Result<String> {
1439 Ok(git(repo, &["merge-base", a, b]).await?.trim().to_owned())
1440}
1441
1442pub async fn is_ancestor(repo: &Path, ancestor: &str, of: &str) -> bool {
1444 git_raw(repo, &["merge-base", "--is-ancestor", ancestor, of])
1445 .await
1446 .is_ok_and(|o| o.ok())
1447}
1448
1449pub async fn ancestry(repo: &Path, ancestor: &str, of: &str) -> Result<bool> {
1454 let out = git_raw(repo, &["merge-base", "--is-ancestor", ancestor, of]).await?;
1455 match out.code {
1456 Some(0) => Ok(true),
1457 Some(1) => Ok(false),
1458 _ => bail!(
1459 "git merge-base --is-ancestor {ancestor} {of} failed ({}): {}",
1460 crate::notices::exit_status(out.code),
1461 out.stderr
1462 ),
1463 }
1464}
1465
1466pub async fn commit_of(repo: &Path, rev: &str) -> Option<String> {
1468 let spec = format!("{rev}^{{commit}}");
1469 let out = git_raw(repo, &["rev-parse", "--verify", "--quiet", &spec])
1470 .await
1471 .ok()?;
1472 (out.ok() && !out.stdout.is_empty()).then_some(out.stdout)
1473}
1474
1475pub async fn branches_containing(repo: &Path, commit: &str) -> Result<Vec<String>> {
1477 let out = git(
1478 repo,
1479 &[
1480 "branch",
1481 "-a",
1482 "--contains",
1483 commit,
1484 "--format=%(refname:short)",
1485 ],
1486 )
1487 .await?;
1488 Ok(out
1489 .lines()
1490 .map(str::trim)
1491 .filter(|l| !l.is_empty() && !l.ends_with("/HEAD") && !l.contains("HEAD detached"))
1492 .map(str::to_owned)
1493 .collect())
1494}
1495
1496pub async fn cherry_pick(worktree: &Path, commit: &str) -> Result<()> {
1500 let out = git_raw(
1501 worktree,
1502 &[
1503 "-c",
1504 "user.name=magi candidate",
1505 "-c",
1506 "user.email=magi@localhost",
1507 "cherry-pick",
1508 "-x",
1509 commit,
1510 ],
1511 )
1512 .await?;
1513 if out.ok() {
1514 return Ok(());
1515 }
1516 let _ = git_raw(worktree, &["cherry-pick", "--abort"]).await;
1517 bail!(
1518 "cherry-pick of {commit} failed: {}",
1519 if out.stderr.is_empty() {
1520 out.stdout
1521 } else {
1522 out.stderr
1523 }
1524 )
1525}
1526
1527pub async fn tree_of(repo: &Path, rev: &str) -> Result<String> {
1529 git(repo, &["rev-parse", &format!("{rev}^{{tree}}")]).await
1530}
1531
1532pub async fn rev_exists(repo: &Path, rev: &str) -> bool {
1534 git_raw(repo, &["rev-parse", "--verify", "--quiet", rev])
1535 .await
1536 .is_ok_and(|o| o.ok())
1537}
1538
1539#[cfg(test)]
1540mod tests {
1541 #[test]
1542 fn git_cli_path_spelling_handles_windows_canonical_prefixes() {
1543 for (native, expected) in [
1544 (r"\\?\C:\temp\work tree", "C:/temp/work tree"),
1545 (
1546 r"\\?\UNC\server\share\work tree",
1547 "//server/share/work tree",
1548 ),
1549 (r"C:\temp\work tree", "C:/temp/work tree"),
1550 ("C:/temp/work tree", "C:/temp/work tree"),
1551 ] {
1552 assert_eq!(super::windows_cli_path(native), expected);
1553 }
1554 }
1555
1556 #[test]
1557 fn git_cli_path_spelling_does_not_alias_extended_only_names() {
1558 for path in [
1559 r"\\?\C:\temp.\copy",
1560 r"\\?\C:\temp \copy",
1561 r"\\?\C:\NUL.txt\copy",
1562 r"\\?\C:\COM1\copy",
1563 ] {
1564 assert!(super::windows_cli_path(path).starts_with("//?/"));
1565 }
1566 }
1567
1568 #[cfg(unix)]
1569 #[test]
1570 fn git_cli_path_spelling_preserves_native_paths_on_unix() {
1571 assert_eq!(
1572 super::path_arg(std::path::Path::new(r"/tmp/back\slash")),
1573 r"/tmp/back\slash"
1574 );
1575 }
1576
1577 #[test]
1578 fn git_cli_canonical_output_accepts_platform_spelling_and_rejects_aliases() {
1579 let temp = tempfile::tempdir().unwrap();
1580 let canonical = temp.path().canonicalize().unwrap();
1581 let printed = super::path_arg(&canonical);
1582 assert_eq!(super::canonical_output_path(&printed).unwrap(), canonical);
1583 let noncanonical = format!("{printed}/child/..");
1586 std::fs::create_dir(canonical.join("child")).unwrap();
1587 assert!(super::canonical_output_path(&noncanonical).is_err());
1588 #[cfg(unix)]
1589 {
1590 let alias = canonical.join("alias");
1591 std::os::unix::fs::symlink(canonical.join("child"), &alias).unwrap();
1592 assert!(super::canonical_output_path(alias.to_str().unwrap()).is_err());
1593 }
1594 }
1595
1596 use super::*;
1597
1598 #[test]
1599 fn worktree_holder_is_read_from_the_porcelain_listing() {
1600 let listing = "worktree /repo\nHEAD aaa\nbranch refs/heads/main\n\n\
1601 worktree /wt/cand-A\nHEAD bbb\nbranch refs/heads/magi/f82f/A\n\n\
1602 worktree /wt/detached\nHEAD ccc\ndetached\n";
1603 assert_eq!(
1604 parse_worktree_holder(listing, "magi/f82f/A"),
1605 Some(PathBuf::from("/wt/cand-A"))
1606 );
1607 assert_eq!(parse_worktree_holder(listing, "magi/f82f"), None);
1608 assert_eq!(parse_worktree_holder(listing, "other"), None);
1609 }
1610
1611 async fn scratch() -> (tempfile::TempDir, PathBuf) {
1612 let dir = tempfile::tempdir().unwrap();
1613 let repo = dir.path().join("repo");
1614 tokio::fs::create_dir_all(&repo).await.unwrap();
1615 git(&repo, &["init", "-b", "main"]).await.unwrap();
1616 git(&repo, &["config", "user.name", "test"]).await.unwrap();
1617 git(&repo, &["config", "user.email", "test@example.com"])
1618 .await
1619 .unwrap();
1620 tokio::fs::write(repo.join("a.txt"), "one\n").await.unwrap();
1621 git(&repo, &["add", "-A"]).await.unwrap();
1622 git(&repo, &["commit", "-m", "init"]).await.unwrap();
1623 (dir, repo)
1624 }
1625
1626 #[tokio::test]
1627 async fn restore_to_removes_nested_repositories_inside_submodules() {
1628 let (_parent_dir, repo) = scratch().await;
1629 let (_source_dir, source) = scratch().await;
1630 sh(
1631 &repo,
1632 &[
1633 "-c",
1634 "protocol.file.allow=always",
1635 "submodule",
1636 "add",
1637 &source.to_string_lossy(),
1638 "sub",
1639 ],
1640 );
1641 sh(&repo, &["commit", "-am", "add submodule"]);
1642 let pre = rev_parse(&repo, "HEAD").await.unwrap();
1643 let sub = repo.join("sub");
1644 sh(&sub, &["init", "nested"]);
1645 tokio::fs::write(sub.join("nested/rejected.txt"), "rejected\n")
1646 .await
1647 .unwrap();
1648
1649 restore_to(&repo, &pre).await.unwrap();
1650
1651 assert!(!sub.join("nested").exists());
1652 assert_eq!(rev_parse(&repo, "HEAD").await.unwrap(), pre);
1653 assert_eq!(
1654 rev_parse(&sub, "HEAD").await.unwrap(),
1655 rev_parse(&source, "HEAD").await.unwrap()
1656 );
1657 assert!(
1658 git(&repo, &["status", "--porcelain"])
1659 .await
1660 .unwrap()
1661 .is_empty()
1662 );
1663 }
1664
1665 #[tokio::test]
1666 async fn a_branch_rebases_onto_a_moved_base_and_says_when_it_cannot() {
1667 let (_g, repo) = scratch().await;
1668
1669 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1671 tokio::fs::write(repo.join("b.txt"), "side\n")
1672 .await
1673 .unwrap();
1674 git(&repo, &["add", "-A"]).await.unwrap();
1675 git(&repo, &["commit", "-m", "side work"]).await.unwrap();
1676
1677 git(&repo, &["checkout", "main"]).await.unwrap();
1680 tokio::fs::write(repo.join("c.txt"), "main\n")
1681 .await
1682 .unwrap();
1683 git(&repo, &["add", "-A"]).await.unwrap();
1684 git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
1685
1686 let scratch_tree = repo.parent().unwrap().join("rebase-scratch");
1687 let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
1688 .await
1689 .unwrap();
1690 assert!(clean.is_none(), "a disjoint change rebases: {clean:?}");
1691 assert_eq!(
1692 commits_ahead(&repo, "main", "side").await.unwrap(),
1693 1,
1694 "one commit, replayed onto the new base"
1695 );
1696 assert!(
1697 !scratch_tree.exists(),
1698 "the throwaway worktree is not left behind"
1699 );
1700
1701 git(&repo, &["checkout", "-b", "clash"]).await.unwrap();
1703 tokio::fs::write(repo.join("a.txt"), "clash\n")
1704 .await
1705 .unwrap();
1706 git(&repo, &["add", "-A"]).await.unwrap();
1707 git(&repo, &["commit", "-m", "clash"]).await.unwrap();
1708 git(&repo, &["checkout", "main"]).await.unwrap();
1709 tokio::fs::write(repo.join("a.txt"), "main edit\n")
1710 .await
1711 .unwrap();
1712 git(&repo, &["add", "-A"]).await.unwrap();
1713 git(&repo, &["commit", "-m", "main edit"]).await.unwrap();
1714
1715 let before = rev_parse(&repo, "clash").await.unwrap();
1716 let why = rebase_branch_in_temp(&repo, &scratch_tree, "clash", "main")
1717 .await
1718 .unwrap()
1719 .expect("a same-line clash cannot be rebased silently");
1720 assert!(
1721 why.to_lowercase().contains("conflict"),
1722 "the reason is what git said, which is what a person needs: {why}"
1723 );
1724 assert_eq!(
1725 rev_parse(&repo, "clash").await.unwrap(),
1726 before,
1727 "a failed rebase leaves the branch exactly where it was"
1728 );
1729 assert!(!scratch_tree.exists(), "and cleans up after itself");
1730 }
1731
1732 #[tokio::test]
1733 async fn merge_squash_folds_the_branch_into_one_commit_under_the_given_message() {
1734 let (_g, repo) = scratch().await;
1735 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1736 for name in ["b.txt", "c.txt"] {
1737 tokio::fs::write(repo.join(name), "side\n").await.unwrap();
1738 git(&repo, &["add", "-A"]).await.unwrap();
1739 git(
1740 &repo,
1741 &["commit", "-m", "magi: candidate A (uncommitted work)"],
1742 )
1743 .await
1744 .unwrap();
1745 }
1746 git(&repo, &["checkout", "main"]).await.unwrap();
1747 let before = rev_parse(&repo, "main").await.unwrap();
1748
1749 let out = merge_squash(&repo, "side", "an explicit subject")
1750 .await
1751 .unwrap();
1752 assert!(out.ok(), "{}", out.stderr);
1753 assert_eq!(
1754 commits_ahead(&repo, &before, "main").await.unwrap(),
1755 1,
1756 "squash adds exactly one commit onto the tip, not one per candidate commit"
1757 );
1758 let subject = git(&repo, &["log", "-1", "--format=%s"]).await.unwrap();
1759 assert_eq!(
1760 subject, "an explicit subject",
1761 "the candidate's own placeholder subject must not survive: {subject}"
1762 );
1763 }
1764
1765 #[tokio::test]
1766 async fn merge_ff_only_fast_forwards_a_branch_already_rebased_onto_the_tip() {
1767 let (_g, repo) = scratch().await;
1768 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1769 tokio::fs::write(repo.join("b.txt"), "side\n")
1770 .await
1771 .unwrap();
1772 git(&repo, &["add", "-A"]).await.unwrap();
1773 git(&repo, &["commit", "-m", "side work"]).await.unwrap();
1774 git(&repo, &["checkout", "main"]).await.unwrap();
1775
1776 let before = rev_parse(&repo, "side").await.unwrap();
1777 let out = merge_ff_only(&repo, "side").await.unwrap();
1778 assert!(out.ok(), "{}", out.stderr);
1779 assert_eq!(
1780 rev_parse(&repo, "main").await.unwrap(),
1781 before,
1782 "a fast-forward moves the base tip to the branch, no merge commit"
1783 );
1784 }
1785
1786 #[tokio::test]
1787 async fn merge_ff_only_refuses_to_write_a_merge_commit() {
1788 let (_g, repo) = scratch().await;
1789 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1790 tokio::fs::write(repo.join("b.txt"), "side\n")
1791 .await
1792 .unwrap();
1793 git(&repo, &["add", "-A"]).await.unwrap();
1794 git(&repo, &["commit", "-m", "side work"]).await.unwrap();
1795
1796 git(&repo, &["checkout", "main"]).await.unwrap();
1798 tokio::fs::write(repo.join("c.txt"), "main\n")
1799 .await
1800 .unwrap();
1801 git(&repo, &["add", "-A"]).await.unwrap();
1802 git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
1803
1804 let before = rev_parse(&repo, "main").await.unwrap();
1805 let out = merge_ff_only(&repo, "side").await.unwrap();
1806 assert!(!out.ok(), "a divergent branch cannot fast-forward");
1807 assert_eq!(
1808 rev_parse(&repo, "main").await.unwrap(),
1809 before,
1810 "a refused fast-forward must not touch main"
1811 );
1812 }
1813
1814 #[tokio::test]
1815 async fn a_sibling_worktree_stays_stale_after_a_rebase_until_synced() {
1816 let (guard, repo) = scratch().await;
1817
1818 git(&repo, &["branch", "side"]).await.unwrap();
1822 let side_wt = guard.path().join("side-wt");
1823 git(
1824 &repo,
1825 &["worktree", "add", &side_wt.to_string_lossy(), "side"],
1826 )
1827 .await
1828 .unwrap();
1829 tokio::fs::write(side_wt.join("b.txt"), "candidate\n")
1830 .await
1831 .unwrap();
1832 git(&side_wt, &["add", "-A"]).await.unwrap();
1833 git(&side_wt, &["commit", "-m", "side work"]).await.unwrap();
1834
1835 git(&repo, &["checkout", "main"]).await.unwrap();
1837 tokio::fs::write(repo.join("c.txt"), "main\n")
1838 .await
1839 .unwrap();
1840 git(&repo, &["add", "-A"]).await.unwrap();
1841 git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
1842
1843 let scratch_tree = guard.path().join("rebase-scratch");
1845 let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
1846 .await
1847 .unwrap();
1848 assert!(clean.is_none());
1849
1850 assert_eq!(
1854 rev_parse(&side_wt, "HEAD").await.unwrap(),
1855 rev_parse(&repo, "side").await.unwrap(),
1856 "HEAD follows the moved ref"
1857 );
1858 assert!(
1859 !side_wt.join("c.txt").exists(),
1860 "stale until synced: main's new file has not reached this worktree's disk"
1861 );
1862
1863 sync_to_head(&side_wt).await.unwrap();
1864 assert!(side_wt.join("c.txt").is_file(), "synced now");
1865 assert!(
1866 side_wt.join("b.txt").is_file(),
1867 "the worktree's own committed work survives the sync"
1868 );
1869 assert!(is_clean(&side_wt).await.unwrap());
1870 }
1871
1872 #[tokio::test]
1873 async fn clean_repo_reports_clean_then_dirty() {
1874 let (_g, repo) = scratch().await;
1875 assert!(is_clean(&repo).await.unwrap());
1876 tokio::fs::write(repo.join("a.txt"), "two\n").await.unwrap();
1877 assert!(!is_clean(&repo).await.unwrap());
1878 }
1879
1880 async fn track(repo: &Path, name: &str, body: &str) {
1881 let p = repo.join(name);
1882 if let Some(d) = p.parent() {
1883 tokio::fs::create_dir_all(d).await.unwrap();
1884 }
1885 tokio::fs::write(&p, body).await.unwrap();
1886 git(repo, &["add", name]).await.unwrap();
1887 git(
1888 repo,
1889 &[
1890 "-c",
1891 "user.name=t",
1892 "-c",
1893 "user.email=t@localhost",
1894 "commit",
1895 "-q",
1896 "-m",
1897 "seed",
1898 ],
1899 )
1900 .await
1901 .unwrap();
1902 }
1903
1904 #[tokio::test]
1905 async fn rescue_withholds_a_foreign_lockfile() {
1906 let (_g, repo) = scratch().await;
1907 track(&repo, "web/bun.lock", "a\n").await;
1908 tokio::fs::write(repo.join("web/pnpm-lock.yaml"), "x\n")
1909 .await
1910 .unwrap();
1911 tokio::fs::write(repo.join("web/app.ts"), "real\n")
1912 .await
1913 .unwrap();
1914
1915 let r = rescue_commit(&repo, "rescue").await.unwrap();
1916 assert!(r.committed);
1917 assert_eq!(
1918 r.withheld,
1919 [Stray {
1920 path: "web/pnpm-lock.yaml".to_owned(),
1921 manager: "pnpm".to_owned(),
1922 kept_by: "web/bun.lock".to_owned(),
1923 }]
1924 );
1925 let files = git(&repo, &["show", "--name-only", "--format=", "HEAD"])
1926 .await
1927 .unwrap();
1928 assert!(files.contains("web/app.ts"), "{files}");
1929 assert!(!files.contains("pnpm-lock"), "{files}");
1930 assert!(repo.join("web/pnpm-lock.yaml").is_file(), "not deleted");
1931 }
1932
1933 #[tokio::test]
1934 async fn rescue_with_only_a_stray_commits_nothing() {
1935 let (_g, repo) = scratch().await;
1936 track(&repo, "bun.lock", "a\n").await;
1937 tokio::fs::write(repo.join("yarn.lock"), "x\n")
1938 .await
1939 .unwrap();
1940 let r = rescue_commit(&repo, "rescue").await.unwrap();
1941 assert!(!r.committed);
1942 assert_eq!(r.withheld.len(), 1);
1943 }
1944
1945 #[tokio::test]
1946 async fn rescue_keeps_a_same_manager_lockfile_update() {
1947 let (_g, repo) = scratch().await;
1948 track(&repo, "bun.lock", "a\n").await;
1949 tokio::fs::write(repo.join("bun.lock"), "b\n")
1950 .await
1951 .unwrap();
1952 let r = rescue_commit(&repo, "rescue").await.unwrap();
1953 assert!(r.committed);
1954 assert!(r.withheld.is_empty());
1955 let files = git(&repo, &["show", "--name-only", "--format=", "HEAD"])
1956 .await
1957 .unwrap();
1958 assert_eq!(files, "bun.lock");
1959 }
1960
1961 #[tokio::test]
1962 async fn rescue_keeps_the_first_lockfile_in_a_bare_directory() {
1963 let (_g, repo) = scratch().await;
1964 track(&repo, "other/bun.lock", "a\n").await;
1965 tokio::fs::create_dir_all(repo.join("web")).await.unwrap();
1966 tokio::fs::write(repo.join("web/package-lock.json"), "{}\n")
1967 .await
1968 .unwrap();
1969 let r = rescue_commit(&repo, "rescue").await.unwrap();
1970 assert!(r.committed);
1971 assert!(r.withheld.is_empty());
1972 }
1973
1974 #[test]
1975 fn a_cargo_lock_is_foreign_only_without_a_cargo_toml() {
1976 let s = |v: &[&str]| v.iter().map(|x| (*x).to_owned()).collect::<Vec<_>>();
1977 assert_eq!(stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&[])).len(), 1);
1978 assert!(stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&["a/Cargo.toml"])).is_empty());
1979 assert!(stray_lockfiles(&s(&["a/Cargo.lock", "a/Cargo.toml"]), &s(&[])).is_empty());
1980 assert_eq!(
1982 stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&["Cargo.toml"])).len(),
1983 1
1984 );
1985 }
1986
1987 #[tokio::test]
1988 async fn clean_removal_preserves_edits_while_scratch_removal_discards_them() {
1989 let (guard, repo) = scratch().await;
1990 let wt = guard.path().join("scratch-wt");
1991 worktree_add_detached(&repo, &wt, "HEAD").await.unwrap();
1992 tokio::fs::write(wt.join("built.txt"), "build output")
1993 .await
1994 .unwrap();
1995 assert!(!worktree_remove_clean(&repo, &wt).await.unwrap());
1996 assert!(wt.join("built.txt").exists());
1997 let listing = git(&repo, &["worktree", "list", "--porcelain"])
1998 .await
1999 .unwrap();
2000 let registered = listing
2001 .lines()
2002 .filter_map(|line| line.strip_prefix("worktree "))
2003 .map(PathBuf::from)
2004 .find(|path| path.canonicalize().unwrap() == wt.canonicalize().unwrap())
2005 .expect("the refused removal must retain the worktree registration");
2006 assert!(worktree_remove(&repo, &wt).await.unwrap());
2007 assert!(!wt.exists());
2008 let listing = git(&repo, &["worktree", "list", "--porcelain"])
2009 .await
2010 .unwrap();
2011 assert!(!listing.lines().any(|line| {
2012 line.strip_prefix("worktree ")
2013 .is_some_and(|path| Path::new(path) == registered)
2014 }));
2015 }
2016
2017 #[tokio::test]
2018 async fn worktree_lifecycle_and_diff() {
2019 let (guard, repo) = scratch().await;
2020 let base = rev_parse(&repo, "HEAD").await.unwrap();
2021 let wt = guard.path().join("wt-a");
2022 worktree_add_branch(&repo, &wt, "magi/test/a", &base)
2023 .await
2024 .unwrap();
2025 tokio::fs::write(wt.join("b.txt"), "candidate\n")
2026 .await
2027 .unwrap();
2028
2029 assert!(commit_all(&wt, "candidate work").await.unwrap());
2030 assert!(!commit_all(&wt, "nothing left").await.unwrap());
2031
2032 assert_eq!(commits_ahead(&wt, &base, "HEAD").await.unwrap(), 1);
2033 let patch = diff(&wt, &base, "HEAD").await.unwrap();
2034 assert!(patch.contains("b.txt"), "patch was: {patch}");
2035 assert_eq!(
2036 changed_files(&wt, &base, "HEAD").await.unwrap(),
2037 ["b.txt".to_owned()]
2038 );
2039
2040 let author = git(&wt, &["log", "-1", "--format=%an <%ae>"])
2042 .await
2043 .unwrap();
2044 assert_eq!(author, "magi candidate <magi@localhost>");
2045
2046 assert!(worktree_remove(&repo, &wt).await.unwrap());
2047 assert!(branch_exists(&repo, "magi/test/a").await.unwrap());
2048 assert!(branch_delete(&repo, "magi/test/a").await.unwrap());
2049 assert!(!branch_exists(&repo, "magi/test/a").await.unwrap());
2050 }
2051
2052 #[tokio::test]
2053 async fn worktree_scoped_hooks_path_does_not_leak_to_primary() {
2054 let (guard, repo) = scratch().await;
2055 let base = rev_parse(&repo, "HEAD").await.unwrap();
2056 let wt = guard.path().join("wt-h");
2057 worktree_add_branch(&repo, &wt, "magi/test/h", &base)
2058 .await
2059 .unwrap();
2060 let hooks = guard.path().join("hooks");
2061 tokio::fs::create_dir_all(&hooks).await.unwrap();
2062
2063 assert!(enable_worktree_config(&repo).await.unwrap());
2064 set_worktree_hooks_path(&wt, &hooks).await.unwrap();
2065
2066 let in_wt = git(&wt, &["config", "--get", "core.hooksPath"])
2067 .await
2068 .unwrap();
2069 assert!(!in_wt.is_empty());
2070 let in_primary = git_raw(&repo, &["config", "--get", "core.hooksPath"])
2071 .await
2072 .unwrap();
2073 assert!(
2074 !in_primary.ok(),
2075 "primary worktree must keep its own hooks: {in_primary:?}"
2076 );
2077
2078 disable_worktree_config(&repo).await.unwrap();
2079 }
2080
2081 #[tokio::test]
2082 async fn worktree_config_stays_on_while_a_sibling_run_still_holds_it() {
2083 let (_g, repo) = scratch().await;
2084
2085 acquire_worktree_config(&repo).await.unwrap();
2088 acquire_worktree_config(&repo).await.unwrap();
2089
2090 let on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
2091 .await
2092 .unwrap();
2093 assert_eq!(on, "true");
2094
2095 release_worktree_config(&repo).await.unwrap();
2099 let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
2100 .await
2101 .unwrap();
2102 assert_eq!(
2103 still_on, "true",
2104 "a sibling run's release must not disable the setting for the one still working"
2105 );
2106
2107 release_worktree_config(&repo).await.unwrap();
2109 let after = git_raw(&repo, &["config", "--get", "extensions.worktreeConfig"])
2110 .await
2111 .unwrap();
2112 assert!(
2113 !after.ok(),
2114 "the last release must turn the setting back off: {after:?}"
2115 );
2116 }
2117
2118 #[tokio::test]
2119 async fn worktree_config_already_on_before_magi_touched_it_is_left_alone() {
2120 let (_g, repo) = scratch().await;
2121 git(&repo, &["config", "extensions.worktreeConfig", "true"])
2122 .await
2123 .unwrap();
2124
2125 acquire_worktree_config(&repo).await.unwrap();
2130 release_worktree_config(&repo).await.unwrap();
2131
2132 let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
2133 .await
2134 .unwrap();
2135 assert_eq!(still_on, "true");
2136 }
2137
2138 #[tokio::test]
2139 async fn local_exclude_is_idempotent() {
2140 let (_g, repo) = scratch().await;
2141 local_exclude(&repo, "/.magi/").await.unwrap();
2142 local_exclude(&repo, "/.magi/").await.unwrap();
2143 let path = repo.join(".git/info/exclude");
2144 let body = tokio::fs::read_to_string(&path).await.unwrap();
2145 assert_eq!(body.matches("/.magi/").count(), 1);
2146 }
2147
2148 fn sh(cwd: &Path, args: &[&str]) {
2149 let out = std::process::Command::new("git")
2150 .quiet()
2151 .args(args)
2152 .current_dir(cwd)
2153 .output()
2154 .unwrap();
2155 assert!(
2156 out.status.success(),
2157 "git {args:?}: {}",
2158 String::from_utf8_lossy(&out.stderr)
2159 );
2160 }
2161
2162 async fn with_remote() -> (tempfile::TempDir, PathBuf) {
2165 let (g, repo) = scratch().await;
2166 let bare = g.path().join("bare.git");
2167 sh(g.path(), &["init", "--bare", "-b", "trunk", "bare.git"]);
2168 sh(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
2169 sh(&repo, &["push", "origin", "HEAD:refs/heads/trunk"]);
2170 sh(&repo, &["fetch", "origin"]);
2171 (g, repo)
2172 }
2173
2174 #[test]
2175 fn remote_head_branch_strips_only_the_matching_remote() {
2176 assert_eq!(
2177 remote_head_branch("origin", "refs/remotes/origin/main\n").as_deref(),
2178 Some("main")
2179 );
2180 assert_eq!(remote_head_branch("up", "refs/remotes/origin/main"), None);
2181 assert_eq!(remote_head_branch("origin", "refs/remotes/origin/"), None);
2182 }
2183
2184 #[tokio::test]
2185 async fn merge_base_branch_reads_origin_head_when_present() {
2186 let (_g, repo) = with_remote().await;
2187 sh(&repo, &["remote", "set-head", "origin", "trunk"]);
2188 assert_eq!(
2189 merge_base_branch(&repo, "origin", None).await.unwrap(),
2190 "trunk"
2191 );
2192 }
2193
2194 #[tokio::test]
2195 async fn merge_base_branch_recovers_a_missing_origin_head() {
2196 let (_g, repo) = with_remote().await;
2197 sh(&repo, &["remote", "set-head", "origin", "-d"]);
2199 let head = git_raw(
2200 &repo,
2201 &["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"],
2202 )
2203 .await
2204 .unwrap();
2205 assert!(!head.ok(), "precondition: no origin/HEAD");
2206 assert_eq!(
2207 merge_base_branch(&repo, "origin", None).await.unwrap(),
2208 "trunk"
2209 );
2210 }
2211
2212 #[tokio::test]
2213 async fn merge_base_branch_errors_without_a_remote_and_never_uses_head() {
2214 let (_g, repo) = scratch().await;
2215 let err = merge_base_branch(&repo, "origin", None).await.unwrap_err();
2216 assert!(format!("{err:#}").contains("[merge] base"), "{err:#}");
2217 }
2218
2219 #[tokio::test]
2220 async fn merge_base_branch_prefers_the_explicit_base() {
2221 let (_g, repo) = with_remote().await;
2222 assert_eq!(
2223 merge_base_branch(&repo, "origin", Some("release"))
2224 .await
2225 .unwrap(),
2226 "release"
2227 );
2228 }
2229
2230 #[tokio::test]
2231 async fn merge_base_branch_names_an_unfetched_default_branch() {
2232 let (g, repo) = scratch().await;
2235 let bare = g.path().join("bare.git");
2236 sh(g.path(), &["init", "--bare", "-b", "trunk", "bare.git"]);
2237 sh(
2238 &repo,
2239 &["push", &bare.to_string_lossy(), "HEAD:refs/heads/trunk"],
2240 );
2241 sh(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
2242 assert!(!rev_exists(&repo, "refs/remotes/origin/trunk").await);
2243 assert_eq!(
2244 merge_base_branch(&repo, "origin", None).await.unwrap(),
2245 "trunk"
2246 );
2247 }
2248
2249 #[test]
2250 fn symref_branch_reads_ls_remote_output() {
2251 assert_eq!(
2252 symref_branch("ref: refs/heads/main\tHEAD\nabc\tHEAD\n").as_deref(),
2253 Some("main")
2254 );
2255 assert_eq!(symref_branch("abc\tHEAD\n"), None);
2256 }
2257}