1use std::path::{Path, PathBuf};
7use std::process::Stdio;
8
9use crate::proc::Quiet as _;
10use anyhow::{Context as _, Result, bail, ensure};
11use tokio::process::Command;
12
13#[derive(Debug)]
15pub struct GitOut {
16 pub code: Option<i32>,
18 pub stdout: String,
20 pub stderr: String,
22}
23
24impl GitOut {
25 pub fn ok(&self) -> bool {
27 self.code == Some(0)
28 }
29}
30
31pub async fn git_raw(cwd: &Path, args: &[&str]) -> Result<GitOut> {
34 git_raw_command(cwd, args, false).await
35}
36
37pub(crate) async fn git_raw_command(
38 cwd: &Path,
39 args: &[&str],
40 kill_on_drop: bool,
41) -> Result<GitOut> {
42 #[cfg(test)]
43 crate::web::request_cost::git();
44 let out = Command::new("git")
45 .args(args)
46 .current_dir(cwd)
47 .quiet()
48 .env("GIT_TERMINAL_PROMPT", "0")
51 .env("GIT_EDITOR", "true")
52 .stdin(Stdio::null())
53 .kill_on_drop(kill_on_drop)
54 .output()
55 .await
56 .with_context(|| format!("spawn git {}", args.join(" ")))?;
57 Ok(GitOut {
58 code: out.status.code(),
59 stdout: String::from_utf8_lossy(&out.stdout).trim_end().to_owned(),
60 stderr: String::from_utf8_lossy(&out.stderr).trim_end().to_owned(),
61 })
62}
63
64pub(crate) fn path_arg(path: &Path) -> String {
67 #[cfg(windows)]
68 let unicode = path.to_str().is_some();
69 let path = path.to_string_lossy();
70 #[cfg(windows)]
71 {
72 if unicode {
73 windows_cli_path(&path)
74 } else {
75 path.into_owned()
76 }
77 }
78 #[cfg(not(windows))]
79 {
80 path.into_owned()
81 }
82}
83
84#[cfg(any(windows, test))]
85fn windows_cli_path(path: &str) -> String {
86 let path = path.replace('\\', "/");
87 if path.starts_with("//?/")
88 && path[4..].split('/').any(|part| {
89 let name = part.split('.').next().unwrap_or("").to_ascii_uppercase();
90 part.ends_with(['.', ' '])
91 || matches!(
92 name.as_str(),
93 "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
94 )
95 || (name.len() == 4
96 && (name.starts_with("COM") || name.starts_with("LPT"))
97 && matches!(name.as_bytes()[3], b'1'..=b'9'))
98 })
99 {
100 return path;
103 }
104 if let Some(unc) = path.strip_prefix("//?/UNC/") {
105 return format!("//{unc}");
106 }
107 if let Some(drive) = path.strip_prefix("//?/")
108 && drive.as_bytes().get(1) == Some(&b':')
109 && drive.as_bytes().get(2) == Some(&b'/')
110 && drive.as_bytes()[0].is_ascii_alphabetic()
111 {
112 return drive.to_owned();
113 }
114 path
115}
116
117pub(crate) fn canonical_output_path(value: &str) -> Result<PathBuf> {
120 let path = PathBuf::from(value);
121 let canonical = path.canonicalize()?;
122 #[cfg(windows)]
123 let same_path = windows_cli_path(path.to_str().context("non UTF-8 Git path")?)
124 == windows_cli_path(canonical.to_str().context("non UTF-8 canonical Git path")?);
125 #[cfg(not(windows))]
126 let same_path = path == canonical;
127 ensure!(same_path, "noncanonical Git path: {}", path.display());
128 Ok(canonical)
129}
130
131pub async fn fetch_origin(cwd: &Path, timeout: std::time::Duration) -> Result<()> {
143 let url = git(cwd, &["remote", "get-url", "origin"]).await?;
144 #[cfg(test)]
145 crate::web::request_cost::git();
146 let fut = Command::new("git")
147 .args([
148 "fetch",
149 "--quiet",
150 "--no-tags",
151 "--no-recurse-submodules",
152 "--no-write-fetch-head",
153 "--",
154 url.as_str(),
155 "+refs/heads/*:refs/remotes/origin/*",
156 ])
157 .current_dir(cwd)
158 .quiet()
159 .env("GIT_TERMINAL_PROMPT", "0")
160 .stdin(Stdio::null())
161 .kill_on_drop(true)
162 .output();
163 let out = tokio::time::timeout(timeout, fut)
164 .await
165 .map_err(|_| anyhow::anyhow!("git fetch timed out after {}s", timeout.as_secs()))?
166 .context("spawn git fetch")?;
167 if !out.status.success() {
168 bail!(
169 "git fetch failed ({}): {}",
170 crate::notices::exit_status(out.status.code()),
171 String::from_utf8_lossy(&out.stderr).trim_end()
172 );
173 }
174 Ok(())
175}
176
177pub async fn git(cwd: &Path, args: &[&str]) -> Result<String> {
179 let out = git_raw(cwd, args).await?;
180 if !out.ok() {
181 bail!(
182 "git {} failed in {} ({}): {}",
183 args.join(" "),
184 cwd.display(),
185 crate::notices::exit_status(out.code),
186 if out.stderr.is_empty() {
187 out.stdout.as_str()
188 } else {
189 out.stderr.as_str()
190 }
191 );
192 }
193 Ok(out.stdout)
194}
195
196pub async fn toplevel(path: &Path) -> Result<PathBuf> {
198 let out = Command::from(toplevel_command(path))
199 .kill_on_drop(true)
200 .output()
201 .await;
202 toplevel_output(path, out)
203}
204
205pub(crate) fn toplevel_blocking(path: &Path) -> Result<PathBuf> {
207 toplevel_output(path, toplevel_command(path).output())?
208 .canonicalize()
209 .with_context(|| format!("canonicalize Git checkout root of {}", path.display()))
210}
211
212fn toplevel_command(path: &Path) -> std::process::Command {
213 #[cfg(test)]
214 crate::web::request_cost::git();
215 let mut command = std::process::Command::new("git");
216 command
217 .args(["rev-parse", "--show-toplevel"])
218 .current_dir(path)
219 .quiet()
220 .stdin(Stdio::null());
221 for key in [
223 "GIT_DIR",
224 "GIT_WORK_TREE",
225 "GIT_IMPLICIT_WORK_TREE",
226 "GIT_COMMON_DIR",
227 "GIT_CONFIG",
228 "GIT_CONFIG_PARAMETERS",
229 "GIT_CONFIG_COUNT",
230 "GIT_CONFIG_GLOBAL",
231 "GIT_CONFIG_SYSTEM",
232 "GIT_CEILING_DIRECTORIES",
233 "GIT_DISCOVERY_ACROSS_FILESYSTEM",
234 "GIT_PREFIX",
235 ] {
236 command.env_remove(key);
237 }
238 command
239}
240
241fn toplevel_output(path: &Path, out: std::io::Result<std::process::Output>) -> Result<PathBuf> {
242 let out = out.with_context(|| format!("read Git checkout root of {}", path.display()))?;
243 ensure!(
244 out.status.success(),
245 "cannot read Git checkout root of {}: {}",
246 path.display(),
247 String::from_utf8_lossy(&out.stderr).trim_end()
248 );
249 Ok(PathBuf::from(
250 std::str::from_utf8(&out.stdout)?.trim_end_matches(['\r', '\n']),
251 ))
252}
253
254pub(crate) fn same_checkout(left: &Path, right: &Path) -> Result<bool> {
257 if left == right {
258 return Ok(true);
259 }
260 let canonical = |path: &Path| {
261 path.canonicalize()
262 .with_context(|| format!("resolve repository {}", path.display()))
263 };
264 let left = canonical(left)?;
265 let right = canonical(right)?;
266 Ok(left == right || toplevel_blocking(&left)? == toplevel_blocking(&right)?)
267}
268
269pub async fn rev_parse(repo: &Path, rev: &str) -> Result<String> {
271 git(repo, &["rev-parse", rev]).await
272}
273
274pub async fn current_branch(repo: &Path) -> Result<Option<String>> {
276 let out = git_raw(repo, &["symbolic-ref", "--quiet", "--short", "HEAD"]).await?;
277 Ok(if out.ok() && !out.stdout.is_empty() {
278 Some(out.stdout)
279 } else {
280 None
281 })
282}
283
284pub fn remote_head_branch(remote: &str, symref: &str) -> Option<String> {
289 symref
290 .trim()
291 .strip_prefix(&format!("refs/remotes/{remote}/"))
292 .filter(|b| !b.is_empty() && *b != "HEAD")
293 .map(str::to_owned)
294}
295
296pub async fn ensure_remote_head(repo: &Path, remote: &str, base: &str) {
302 let head = format!("refs/remotes/{remote}/HEAD");
303 if git_raw(repo, &["symbolic-ref", "--quiet", &head])
304 .await
305 .is_ok_and(|o| o.ok())
306 {
307 return;
308 }
309 let target = format!("refs/remotes/{remote}/{base}");
310 let _ = git_raw(repo, &["symbolic-ref", &head, &target]).await;
311}
312
313fn symref_branch(out: &str) -> Option<String> {
316 out.lines()
317 .find_map(|l| l.strip_prefix("ref: refs/heads/"))
318 .and_then(|l| l.split_whitespace().next())
319 .map(str::to_owned)
320}
321
322pub async fn merge_base_branch(
329 repo: &Path,
330 remote: &str,
331 explicit: Option<&str>,
332) -> Result<String> {
333 if let Some(b) = explicit.map(str::trim).filter(|b| !b.is_empty()) {
334 return Ok(b.to_owned());
335 }
336 let head = format!("refs/remotes/{remote}/HEAD");
337 let read = || async {
338 let out = git_raw(repo, &["symbolic-ref", "--quiet", &head])
339 .await
340 .ok()?;
341 if out.ok() {
342 remote_head_branch(remote, &out.stdout)
343 } else {
344 None
345 }
346 };
347 if let Some(b) = read().await {
348 return Ok(b);
349 }
350 let set = git_raw(repo, &["remote", "set-head", remote, "-a"]).await;
351 if let Some(b) = read().await {
352 return Ok(b);
353 }
354 if let Ok(o) = git_raw(repo, &["ls-remote", "--symref", remote, "HEAD"]).await
359 && o.ok()
360 && let Some(b) = symref_branch(&o.stdout)
361 {
362 return Ok(b);
363 }
364 let why = match set {
365 Ok(o) if !o.ok() => o.stderr.lines().next().unwrap_or("").trim().to_owned(),
366 Ok(_) => "the remote reported no default branch".to_owned(),
367 Err(e) => e.to_string(),
368 };
369 bail!(
370 "cannot tell which branch of `{remote}` is the base ({why}): set [merge] base \
371 (and remote) in magi.toml, or run `git remote set-head {remote} -a`. magi does \
372 not fall back to the checked-out branch, which may be detached or stale"
373 )
374}
375
376pub async fn is_clean(repo: &Path) -> Result<bool> {
378 Ok(git(repo, &["status", "--porcelain"]).await?.is_empty())
379}
380
381pub async fn status_porcelain(repo: &Path) -> Result<String> {
383 git(repo, &["status", "--porcelain"]).await
384}
385
386pub async fn worktree_add_branch(repo: &Path, path: &Path, branch: &str, base: &str) -> Result<()> {
388 if let Some(parent) = path.parent() {
389 tokio::fs::create_dir_all(parent).await.ok();
390 }
391 let path_s = path_arg(path);
392 git(repo, &["worktree", "add", "-b", branch, &path_s, base])
393 .await
394 .map(|_| ())
395}
396
397pub(crate) async fn worktree_add_existing(
399 repo: &Path,
400 path: &Path,
401 branch: &str,
402 force: bool,
403) -> Result<()> {
404 if let Some(parent) = path.parent() {
405 tokio::fs::create_dir_all(parent).await.ok();
406 }
407 let path_s = path_arg(path);
408 if force {
409 git(repo, &["worktree", "add", "--force", &path_s, branch]).await
410 } else {
411 git(repo, &["worktree", "add", &path_s, branch]).await
412 }
413 .map(|_| ())
414}
415
416pub async fn worktree_add_detached(repo: &Path, path: &Path, rev: &str) -> Result<()> {
418 if let Some(parent) = path.parent() {
419 tokio::fs::create_dir_all(parent).await.ok();
420 }
421 let path_s = path_arg(path);
422 git(repo, &["worktree", "add", "--detach", &path_s, rev])
423 .await
424 .map(|_| ())
425}
426
427pub async fn reset_detached(worktree: &Path, rev: &str) -> Result<()> {
429 reset_detached_keep_ignored(worktree, rev).await?;
430 clean_all(worktree).await
431}
432
433pub async fn reset_detached_keep_ignored(worktree: &Path, rev: &str) -> Result<()> {
436 git(worktree, &["checkout", "--detach", rev]).await?;
437 git(worktree, &["reset", "--hard", rev]).await.map(|_| ())
438}
439
440pub async fn worktree_holding(repo: &Path, branch: &str) -> Result<Option<PathBuf>> {
445 let listing = git(repo, &["worktree", "list", "--porcelain"]).await?;
446 Ok(parse_worktree_holder(&listing, branch))
447}
448
449fn parse_worktree_holder(listing: &str, branch: &str) -> Option<PathBuf> {
450 let want = format!("refs/heads/{branch}");
451 let mut path: Option<PathBuf> = None;
452 for line in listing.lines() {
453 if let Some(p) = line.strip_prefix("worktree ") {
454 path = Some(PathBuf::from(p));
455 } else if line.strip_prefix("branch ") == Some(want.as_str()) {
456 return path;
457 }
458 }
459 None
460}
461
462pub async fn worktree_remove(repo: &Path, path: &Path) -> Result<bool> {
466 let path_s = path_arg(path);
467 let out = git_raw(repo, &["worktree", "remove", "--force", &path_s]).await?;
468 if out.ok() {
469 return Ok(true);
470 }
471 if !path.exists() {
473 git_raw(repo, &["worktree", "prune"]).await?;
474 }
475 Ok(false)
476}
477
478pub async fn worktree_remove_clean(repo: &Path, path: &Path) -> Result<bool> {
482 let path_s = path_arg(path);
483 Ok(git_raw(repo, &["worktree", "remove", &path_s]).await?.ok())
484}
485
486pub async fn remove_worktree_from_linked(dir: &Path) {
495 let Ok(link) = std::fs::read_to_string(dir.join(".git")) else {
496 return;
497 };
498 let Some(admin) = link.strip_prefix("gitdir:").map(str::trim) else {
499 return;
500 };
501 let admin = Path::new(admin);
504 let Some(common) = admin.parent().and_then(Path::parent) else {
505 return;
506 };
507 let common_s = common.to_string_lossy();
508 let _ = git_raw(dir, &["--git-dir", &common_s, "worktree", "prune"]).await;
509}
510
511pub async fn worktree_prune(repo: &Path) -> Result<()> {
520 git(repo, &["worktree", "prune"]).await.map(|_| ())
521}
522
523pub async fn branch_delete(repo: &Path, branch: &str) -> Result<bool> {
525 Ok(git_raw(repo, &["branch", "-D", branch]).await?.ok())
526}
527
528pub async fn branch_exists(repo: &Path, branch: &str) -> Result<bool> {
530 let refname = format!("refs/heads/{branch}");
531 Ok(
532 git_raw(repo, &["show-ref", "--verify", "--quiet", &refname])
533 .await?
534 .ok(),
535 )
536}
537
538pub async fn remote_has_branch(repo: &Path, remote: &str, branch: &str) -> Result<bool> {
541 let refname = format!("refs/heads/{branch}");
542 let out = git_raw(repo, &["ls-remote", "--exit-code", remote, &refname]).await?;
543 match out.code {
544 Some(0) => Ok(true),
545 Some(2) => Ok(false),
546 code => bail!(
547 "git ls-remote {remote} failed ({}): {}",
548 crate::notices::exit_status(code),
549 out.stderr
550 ),
551 }
552}
553
554pub async fn diff(worktree: &Path, base: &str, head: &str) -> Result<String> {
556 let range = format!("{base}...{head}");
557 git(
558 worktree,
559 &["diff", "--no-color", "--no-ext-diff", "-M", &range],
560 )
561 .await
562}
563
564pub async fn diff_stat(worktree: &Path, base: &str, head: &str) -> Result<String> {
566 let range = format!("{base}...{head}");
567 git(worktree, &["diff", "--no-color", "--stat", &range]).await
568}
569
570pub async fn changed_lines(worktree: &Path, base: &str, head: &str) -> Option<usize> {
574 let out = git_raw(worktree, &["diff", "--numstat", base, head])
575 .await
576 .ok()?;
577 if !out.ok() {
578 return None;
579 }
580 let mut total = 0usize;
581 for line in out.stdout.lines().filter(|l| !l.trim().is_empty()) {
582 let mut cols = line.split('\t');
583 let added: usize = cols.next()?.parse().ok()?;
584 let removed: usize = cols.next()?.parse().ok()?;
585 total = total.saturating_add(added).saturating_add(removed);
586 }
587 Some(total)
588}
589
590pub async fn restore_to(worktree: &Path, rev: &str) -> Result<()> {
594 git(worktree, &["reset", "--hard", "-q", rev]).await?;
595 git(worktree, &["clean", "-ffdq"]).await?;
598 git(
604 worktree,
605 &[
606 "submodule",
607 "--quiet",
608 "update",
609 "--recursive",
610 "--force",
611 "--checkout",
612 ],
613 )
614 .await?;
615 git(
616 worktree,
617 &[
618 "submodule",
619 "--quiet",
620 "foreach",
621 "--recursive",
622 "git clean -ffdq",
623 ],
624 )
625 .await?;
626 Ok(())
627}
628
629pub async fn changed_files(worktree: &Path, base: &str, head: &str) -> Result<Vec<String>> {
631 let range = format!("{base}...{head}");
632 let out = git(worktree, &["diff", "--name-only", &range]).await?;
633 Ok(out.lines().map(str::to_owned).collect())
634}
635
636pub async fn commit_log(worktree: &Path, base: &str, head: &str) -> Result<Vec<(String, String)>> {
640 let range = format!("{base}..{head}");
641 let out = git(
642 worktree,
643 &[
644 "log",
645 "--reverse",
646 "--no-color",
647 "--format=%s%x1f%b%x00",
648 &range,
649 ],
650 )
651 .await?;
652 Ok(out
653 .split('\0')
654 .filter_map(|rec| {
655 let rec = rec.trim_start_matches('\n');
656 if rec.trim().is_empty() {
657 return None;
658 }
659 let (subject, body) = rec.split_once('\x1f').unwrap_or((rec, ""));
660 Some((subject.trim().to_owned(), body.trim().to_owned()))
661 })
662 .collect())
663}
664
665pub async fn log_oneline(worktree: &Path, base: &str, head: &str) -> Result<String> {
667 let range = format!("{base}..{head}");
668 git(
669 worktree,
670 &["log", "--reverse", "--format=%s%n%b%n--", &range],
671 )
672 .await
673}
674
675pub async fn subjects(worktree: &Path, base: &str, head: &str) -> Result<Vec<String>> {
678 let range = format!("{base}..{head}");
679 let out = git(worktree, &["log", "--reverse", "--format=%s%x00", &range]).await?;
680 let mut parts: Vec<String> = out.split('\0').map(|s| s.trim().to_owned()).collect();
681 parts.pop();
683 Ok(parts)
684}
685
686pub async fn commits_ahead(worktree: &Path, base: &str, head: &str) -> Result<usize> {
688 let range = format!("{base}..{head}");
689 let out = git(worktree, &["rev-list", "--count", &range]).await?;
690 Ok(out.trim().parse().unwrap_or(0))
691}
692
693pub async fn commit_all(worktree: &Path, message: &str) -> Result<bool> {
700 if git(worktree, &["status", "--porcelain"]).await?.is_empty() {
701 return Ok(false);
702 }
703 git(worktree, &["add", "-A"]).await?;
704 if !crate::worktree_setup::withheld_paths(worktree)
706 .await
707 .is_empty()
708 {
709 crate::worktree_setup::unstage_products(worktree).await?;
710 if git_raw(worktree, &["diff", "--cached", "--quiet"])
711 .await?
712 .ok()
713 {
714 return Ok(false);
715 }
716 }
717 let out = git_raw(
718 worktree,
719 &[
720 "-c",
721 "user.name=magi candidate",
722 "-c",
723 "user.email=magi@localhost",
724 "commit",
725 "--no-verify",
726 "-m",
727 message,
728 ],
729 )
730 .await?;
731 if !out.ok() {
732 bail!("rescue commit failed: {}", out.stderr);
733 }
734 Ok(true)
735}
736
737#[derive(Debug, Clone, PartialEq, Eq)]
740pub struct Stray {
741 pub path: String,
743 pub manager: String,
745 pub kept_by: String,
748}
749
750#[derive(Debug, Default)]
752pub struct Rescue {
753 pub committed: bool,
755 pub withheld: Vec<Stray>,
757}
758
759fn lock_kind(name: &str) -> Option<(&'static str, &'static str)> {
761 Some(match name {
762 "package-lock.json" | "npm-shrinkwrap.json" => ("node", "npm"),
763 "yarn.lock" => ("node", "yarn"),
764 "pnpm-lock.yaml" => ("node", "pnpm"),
765 "bun.lock" | "bun.lockb" => ("node", "bun"),
766 "poetry.lock" => ("python", "poetry"),
767 "uv.lock" => ("python", "uv"),
768 "Pipfile.lock" => ("python", "pipenv"),
769 "pdm.lock" => ("python", "pdm"),
770 "Cargo.lock" => ("rust", "cargo"),
771 _ => return None,
772 })
773}
774
775fn split_dir(path: &str) -> (&str, &str) {
776 path.rsplit_once('/').unwrap_or(("", path))
777}
778
779pub fn stray_lockfiles(untracked: &[String], tracked: &[String]) -> Vec<Stray> {
787 let mut out = Vec::new();
788 for path in untracked {
789 let (dir, name) = split_dir(path);
790 let Some((eco, manager)) = lock_kind(name) else {
791 continue;
792 };
793 let beside = |other: &String| split_dir(other).0 == dir;
794 let kept_by = if manager == "cargo" {
795 let has_manifest = tracked
796 .iter()
797 .chain(untracked)
798 .any(|p| beside(p) && split_dir(p).1 == "Cargo.toml");
799 if has_manifest {
800 continue;
801 }
802 "no Cargo.toml in the directory".to_owned()
803 } else {
804 let Some(other) = tracked.iter().find(|p| {
805 beside(p)
806 && lock_kind(split_dir(p).1).is_some_and(|(e, m)| e == eco && m != manager)
807 }) else {
808 continue;
809 };
810 other.clone()
811 };
812 out.push(Stray {
813 path: path.clone(),
814 manager: manager.to_owned(),
815 kept_by,
816 });
817 }
818 out
819}
820
821async fn nul_list(worktree: &Path, args: &[&str]) -> Result<Vec<String>> {
822 let out = git(worktree, args).await?;
823 Ok(out
824 .split('\0')
825 .filter(|s| !s.is_empty())
826 .map(str::to_owned)
827 .collect())
828}
829
830pub async fn snapshot_uncommitted(worktree: &Path, destination: &Path) -> Result<()> {
834 if destination.exists() {
835 if destination.join("complete").exists() {
836 return Ok(());
837 }
838 bail!("earlier recovery snapshot is incomplete; retain original worktree");
839 }
840 std::fs::create_dir_all(destination)?;
841 for (name, args) in [
842 ("status.txt", vec!["status", "--porcelain=v1"]),
843 ("staged.patch", vec!["diff", "--binary", "--cached"]),
844 ("unstaged.patch", vec!["diff", "--binary"]),
845 ] {
846 let out = Command::new("git")
849 .args(&args)
850 .current_dir(worktree)
851 .quiet()
852 .stdin(Stdio::null())
853 .output()
854 .await?;
855 if !out.status.success() {
856 bail!(
857 "recovery snapshot failed: {}",
858 String::from_utf8_lossy(&out.stderr)
859 );
860 }
861 std::fs::write(destination.join(name), out.stdout)?;
862 }
863 let paths = nul_list(
864 worktree,
865 &["ls-files", "-z", "--others", "--exclude-standard"],
866 )
867 .await?;
868 for name in paths {
869 let relative = Path::new(&name);
870 if relative
871 .components()
872 .any(|c| !matches!(c, std::path::Component::Normal(_)))
873 {
874 bail!("unsafe recovery path");
875 }
876 let source = worktree.join(relative);
877 let target = destination.join("untracked").join(relative);
878 std::fs::create_dir_all(target.parent().context("untracked recovery parent")?)?;
879 if std::fs::symlink_metadata(&source)?.file_type().is_symlink() {
880 bail!("untracked symlink requires manual recovery: {name}");
882 }
883 std::fs::copy(source, target)?;
884 }
885 std::fs::write(destination.join("complete"), "snapshot captured\n")?;
886 Ok(())
887}
888
889pub async fn rescue_commit(worktree: &Path, message: &str) -> Result<Rescue> {
895 if git(worktree, &["status", "--porcelain"]).await?.is_empty() {
896 return Ok(Rescue::default());
897 }
898 let untracked = nul_list(
899 worktree,
900 &["ls-files", "-z", "--others", "--exclude-standard"],
901 )
902 .await?;
903 let tracked = nul_list(worktree, &["ls-files", "-z"]).await?;
904 let withheld = stray_lockfiles(&untracked, &tracked);
905
906 git(worktree, &["add", "-A"]).await?;
907 if !withheld.is_empty() {
908 let mut args = vec!["reset", "-q", "--"];
909 args.extend(withheld.iter().map(|s| s.path.as_str()));
910 git(worktree, &args).await?;
911 }
912 crate::worktree_setup::unstage_products(worktree).await?;
913 if git_raw(worktree, &["diff", "--cached", "--quiet"])
914 .await?
915 .ok()
916 {
917 return Ok(Rescue {
918 committed: false,
919 withheld,
920 });
921 }
922 let out = git_raw(
923 worktree,
924 &[
925 "-c",
926 "user.name=magi candidate",
927 "-c",
928 "user.email=magi@localhost",
929 "commit",
930 "--no-verify",
931 "-m",
932 message,
933 ],
934 )
935 .await?;
936 if !out.ok() {
937 bail!("rescue commit failed: {}", out.stderr);
938 }
939 Ok(Rescue {
940 committed: true,
941 withheld,
942 })
943}
944
945pub async fn enable_worktree_config(repo: &Path) -> Result<bool> {
950 let out = git_raw(repo, &["config", "--get", "extensions.worktreeConfig"]).await?;
951 if out.ok() && out.stdout.trim() == "true" {
952 return Ok(false);
953 }
954 git(repo, &["config", "extensions.worktreeConfig", "true"]).await?;
955 Ok(true)
956}
957
958pub async fn disable_worktree_config(repo: &Path) -> Result<()> {
960 git_raw(repo, &["config", "--unset", "extensions.worktreeConfig"]).await?;
961 Ok(())
962}
963
964struct WorktreeConfigRef {
967 count: usize,
969 we_enabled: bool,
975}
976
977static WORKTREE_CONFIG: std::sync::LazyLock<
984 std::sync::Mutex<
985 std::collections::HashMap<PathBuf, std::sync::Arc<tokio::sync::Mutex<WorktreeConfigRef>>>,
986 >,
987> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
988
989fn worktree_config_slot(repo: &Path) -> std::sync::Arc<tokio::sync::Mutex<WorktreeConfigRef>> {
991 let mut map = WORKTREE_CONFIG
992 .lock()
993 .unwrap_or_else(std::sync::PoisonError::into_inner);
994 map.entry(repo.to_path_buf())
995 .or_insert_with(|| {
996 std::sync::Arc::new(tokio::sync::Mutex::new(WorktreeConfigRef {
997 count: 0,
998 we_enabled: false,
999 }))
1000 })
1001 .clone()
1002}
1003
1004pub async fn acquire_worktree_config(repo: &Path) -> Result<()> {
1021 let slot = worktree_config_slot(repo);
1022 let mut entry = slot.lock().await;
1023 entry.count += 1;
1024 if entry.count == 1 {
1025 entry.we_enabled = enable_worktree_config(repo).await?;
1026 }
1027 Ok(())
1028}
1029
1030pub async fn release_worktree_config(repo: &Path) -> Result<()> {
1036 let slot = worktree_config_slot(repo);
1037 let mut entry = slot.lock().await;
1038 entry.count = entry.count.saturating_sub(1);
1039 if entry.count == 0 && entry.we_enabled {
1040 disable_worktree_config(repo).await?;
1041 entry.we_enabled = false;
1042 }
1043 Ok(())
1044}
1045
1046pub async fn set_worktree_hooks_path(worktree: &Path, hooks_dir: &Path) -> Result<()> {
1052 let dir = hooks_dir.to_string_lossy().replace('\\', "/");
1053 git(worktree, &["config", "--worktree", "core.hooksPath", &dir])
1054 .await
1055 .map(|_| ())
1056}
1057
1058pub async fn local_exclude(worktree: &Path, pattern: &str) -> Result<()> {
1060 let git_dir = git(worktree, &["rev-parse", "--git-path", "info/exclude"]).await?;
1061 let path = worktree.join(git_dir);
1062 if let Some(parent) = path.parent() {
1063 tokio::fs::create_dir_all(parent).await.ok();
1064 }
1065 let mut body = tokio::fs::read_to_string(&path).await.unwrap_or_default();
1066 if body.lines().any(|l| l.trim() == pattern) {
1067 return Ok(());
1068 }
1069 if !body.is_empty() && !body.ends_with('\n') {
1070 body.push('\n');
1071 }
1072 body.push_str(pattern);
1073 body.push('\n');
1074 tokio::fs::write(&path, body)
1075 .await
1076 .with_context(|| format!("write {}", path.display()))?;
1077 Ok(())
1078}
1079
1080pub async fn merge_no_ff(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
1086 git_raw(
1087 repo,
1088 &["merge", "--no-ff", "--no-edit", "-m", message, branch],
1089 )
1090 .await
1091}
1092
1093pub async fn merge_squash(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
1104 let staged = git_raw(repo, &["merge", "--squash", branch]).await?;
1105 if !staged.ok() {
1106 return Ok(staged);
1107 }
1108 git_raw(repo, &["commit", "-m", message]).await
1109}
1110
1111pub async fn merge_ff_only(repo: &Path, branch: &str) -> Result<GitOut> {
1121 git_raw(repo, &["merge", "--ff-only", branch]).await
1122}
1123
1124pub async fn push(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
1126 git_raw(repo, &["push", "-u", remote, branch]).await
1127}
1128
1129pub async fn push_as(
1132 repo: &Path,
1133 remote: &str,
1134 local: &str,
1135 head: &str,
1136 expected: &str,
1137) -> Result<GitOut> {
1138 let lease = format!("--force-with-lease=refs/heads/{head}:{expected}");
1139 let refspec = format!("refs/heads/{local}:refs/heads/{head}");
1140 git_raw(repo, &["push", &lease, remote, &refspec]).await
1141}
1142
1143pub async fn remote_head(repo: &Path, remote: &str, branch: &str) -> Result<Option<String>> {
1145 let reference = format!("refs/heads/{branch}");
1146 let out = git(repo, &["ls-remote", "--refs", remote, &reference]).await?;
1147 Ok(out.split_whitespace().next().map(str::to_owned))
1148}
1149
1150pub async fn push_rewritten(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
1158 git_raw(repo, &["push", "--force-with-lease", remote, branch]).await
1159}
1160
1161pub async fn push_pinned(
1170 repo: &Path,
1171 remote: &str,
1172 branch: &str,
1173 expected: &str,
1174) -> Result<GitOut> {
1175 let lease = format!("--force-with-lease=refs/heads/{branch}:{expected}");
1176 let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1177 git_raw(repo, &["push", &lease, remote, &refspec]).await
1178}
1179
1180pub async fn cherry(repo: &Path, upstream: &str, head: &str) -> Result<(Vec<String>, Vec<String>)> {
1183 let out = git(repo, &["cherry", upstream, head]).await?;
1184 let (mut unmatched, mut matched) = (Vec::new(), Vec::new());
1185 for line in out.lines() {
1186 if let Some(sha) = line.strip_prefix("+ ") {
1187 unmatched.push(sha.trim().to_owned());
1188 } else if let Some(sha) = line.strip_prefix("- ") {
1189 matched.push(sha.trim().to_owned());
1190 }
1191 }
1192 Ok((unmatched, matched))
1193}
1194
1195#[derive(Debug)]
1197pub struct RebaseRecord {
1198 pub picks: Vec<String>,
1200 pub heads: Vec<String>,
1202}
1203
1204const REBASE_EXEC: &str = "git rev-parse HEAD >> \"$(git rev-parse --git-path magi-rebase-heads)\"";
1205
1206async fn rebase_file(scratch: &Path, name: &str) -> Result<PathBuf> {
1207 let path = git(scratch, &["rev-parse", "--git-path", name]).await?;
1208 let path = Path::new(path.trim());
1209 Ok(if path.is_absolute() {
1210 path.to_path_buf()
1211 } else {
1212 scratch.join(path)
1213 })
1214}
1215
1216async fn full_commit(scratch: &Path, sha: &str) -> Result<String> {
1217 anyhow::ensure!(
1218 !sha.is_empty() && sha.bytes().all(|b| b.is_ascii_hexdigit()),
1219 "invalid rebase commit id: {sha}"
1220 );
1221 rev_parse(scratch, &format!("{sha}^{{commit}}")).await
1222}
1223
1224async fn save_rebase_picks(scratch: &Path) -> Result<()> {
1227 let mut picks = Vec::new();
1228 for name in ["rebase-merge/done", "rebase-merge/git-rebase-todo"] {
1229 let text = std::fs::read_to_string(rebase_file(scratch, name).await?)?;
1230 for line in text.lines().map(str::trim) {
1231 if line.is_empty() || line.starts_with('#') {
1232 continue;
1233 }
1234 let mut words = line.split_whitespace();
1235 match words.next() {
1236 Some("pick" | "p") => {
1237 picks.push(
1238 full_commit(scratch, words.next().context("pick without commit")?).await?,
1239 );
1240 }
1241 Some("exec" | "x")
1242 if line
1243 .split_once(' ')
1244 .is_some_and(|(_, cmd)| cmd == REBASE_EXEC) => {}
1245 _ => bail!("unexpected rebase instruction: {line}"),
1246 }
1247 }
1248 }
1249 let path = rebase_file(scratch, "magi-rebase-picks").await?;
1250 let tmp = path.with_extension("tmp");
1251 std::fs::write(&tmp, picks.join("\n") + "\n")?;
1252 std::fs::rename(tmp, path)?;
1253 Ok(())
1254}
1255
1256pub async fn rebase_record(scratch: &Path) -> Result<RebaseRecord> {
1258 let mut lists = Vec::new();
1259 for name in ["magi-rebase-picks", "magi-rebase-heads"] {
1260 let text = std::fs::read_to_string(rebase_file(scratch, name).await?)
1261 .with_context(|| format!("read {name}"))?;
1262 let mut commits = Vec::new();
1263 for sha in text.lines() {
1264 let full = full_commit(scratch, sha).await?;
1265 anyhow::ensure!(full == sha, "non-full commit id in {name}");
1266 commits.push(full);
1267 }
1268 lists.push(commits);
1269 }
1270 let heads = lists.pop().unwrap();
1271 let picks = lists.pop().unwrap();
1272 anyhow::ensure!(
1273 !picks.is_empty() && picks.len() == heads.len(),
1274 "rebase pick/HEAD count mismatch"
1275 );
1276 Ok(RebaseRecord { picks, heads })
1277}
1278
1279pub fn rebase_said(text: &str) -> String {
1281 text.trim()
1282 .split(['\r', '\n'])
1283 .filter(|line| !line.trim_start().starts_with("Executing:"))
1284 .collect::<Vec<_>>()
1285 .join("\n")
1286}
1287
1288#[derive(Debug, Clone, PartialEq, Eq)]
1290pub enum RebaseStart {
1291 Applied,
1294 Conflicted(String),
1297 Failed(String),
1300}
1301
1302pub async fn rebase_start(
1317 repo: &Path,
1318 scratch: &Path,
1319 branch: &str,
1320 onto: &str,
1321) -> Result<RebaseStart> {
1322 rebase_prepare(repo, scratch, branch).await?;
1323 rebase_execute(repo, scratch, onto).await
1324}
1325
1326#[derive(Debug)]
1328pub struct RebasePreparationError(pub String);
1329
1330impl std::fmt::Display for RebasePreparationError {
1331 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1332 f.write_str(&self.0)
1333 }
1334}
1335
1336impl std::error::Error for RebasePreparationError {}
1337
1338pub(crate) async fn rebase_prepare(repo: &Path, scratch: &Path, branch: &str) -> Result<()> {
1341 if rebase_in_progress(scratch).await {
1342 return Ok(());
1343 }
1344 let result = async {
1345 worktree_remove(repo, scratch).await.ok();
1346 let path = path_arg(scratch);
1347 let args = ["worktree", "add", "--force", &path, branch];
1348 let out = git_raw(repo, &args).await?;
1349 ensure!(
1350 out.ok(),
1351 "git {} (exit {:?}): {}",
1352 args.join(" "),
1353 out.code,
1354 if out.stderr.trim().is_empty() {
1355 &out.stdout
1356 } else {
1357 &out.stderr
1358 }
1359 );
1360 std::fs::write(rebase_file(scratch, "magi-rebase-heads").await?, "")?;
1361 Ok::<_, anyhow::Error>(())
1362 }
1363 .await;
1364 result.map_err(|e| {
1365 RebasePreparationError(format!(
1366 "prepare rebase scratch {}: {e:#}",
1367 scratch.display()
1368 ))
1369 .into()
1370 })
1371}
1372
1373pub(crate) async fn rebase_execute(repo: &Path, scratch: &Path, onto: &str) -> Result<RebaseStart> {
1375 let out = git_raw(
1376 scratch,
1377 &["rebase", "--empty=drop", "--exec", REBASE_EXEC, onto],
1378 )
1379 .await?;
1380 if out.ok() {
1381 worktree_remove(repo, scratch).await.ok();
1382 return Ok(RebaseStart::Applied);
1383 }
1384 let why = rebase_said(&if out.stderr.trim().is_empty() {
1385 out.stdout.trim().to_owned()
1386 } else {
1387 out.stderr.trim().to_owned()
1388 });
1389 if rebase_in_progress(scratch).await {
1390 if let Err(error) = save_rebase_picks(scratch).await {
1391 rebase_abort(repo, scratch).await;
1392 return Ok(RebaseStart::Failed(format!(
1393 "cannot record rebase picks: {error:#}"
1394 )));
1395 }
1396 return Ok(RebaseStart::Conflicted(why));
1397 }
1398 worktree_remove(repo, scratch).await.ok();
1399 Ok(RebaseStart::Failed(why))
1400}
1401
1402pub async fn rebase_in_progress(worktree: &Path) -> bool {
1404 for name in ["rebase-merge", "rebase-apply"] {
1405 let Ok(p) = git(worktree, &["rev-parse", "--git-path", name]).await else {
1406 continue;
1407 };
1408 let p = Path::new(p.trim());
1409 let full = if p.is_absolute() {
1410 p.to_path_buf()
1411 } else {
1412 worktree.join(p)
1413 };
1414 if full.exists() {
1415 return true;
1416 }
1417 }
1418 false
1419}
1420
1421pub async fn unmerged_paths(worktree: &Path) -> Result<Vec<String>> {
1423 let out = git(worktree, &["diff", "--name-only", "--diff-filter=U", "-z"]).await?;
1424 Ok(out
1425 .split('\0')
1426 .filter(|l| !l.is_empty())
1427 .map(str::to_owned)
1428 .collect())
1429}
1430
1431pub async fn rebase_abort(repo: &Path, scratch: &Path) {
1434 git_raw(scratch, &["rebase", "--abort"]).await.ok();
1435 worktree_remove(repo, scratch).await.ok();
1436}
1437
1438pub async fn rebase_branch_in_temp(
1446 repo: &Path,
1447 scratch: &Path,
1448 branch: &str,
1449 onto: &str,
1450) -> Result<Option<String>> {
1451 match rebase_start(repo, scratch, branch, onto).await? {
1452 RebaseStart::Applied => Ok(None),
1453 RebaseStart::Failed(why) => Ok(Some(why)),
1454 RebaseStart::Conflicted(why) => {
1455 rebase_abort(repo, scratch).await;
1456 Ok(Some(why))
1457 }
1458 }
1459}
1460
1461pub async fn sync_to_head(worktree: &Path) -> Result<()> {
1474 reset_hard_head(worktree).await?;
1475 clean_all(worktree).await
1476}
1477
1478pub async fn reset_hard_head(worktree: &Path) -> Result<()> {
1480 git(worktree, &["reset", "--hard", "HEAD"])
1481 .await
1482 .map(|_| ())
1483}
1484
1485pub async fn clean_all(worktree: &Path) -> Result<()> {
1487 git(worktree, &["clean", "-fdx"]).await.map(|_| ())
1488}
1489
1490pub async fn fetch(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
1509 let refspec = format!("+refs/heads/{branch}:refs/remotes/{remote}/{branch}");
1510 git_raw(repo, &["fetch", "--quiet", remote, &refspec]).await
1511}
1512
1513pub async fn merge_base(repo: &Path, a: &str, b: &str) -> Result<String> {
1515 Ok(git(repo, &["merge-base", a, b]).await?.trim().to_owned())
1516}
1517
1518pub async fn is_ancestor(repo: &Path, ancestor: &str, of: &str) -> bool {
1520 git_raw(repo, &["merge-base", "--is-ancestor", ancestor, of])
1521 .await
1522 .is_ok_and(|o| o.ok())
1523}
1524
1525pub async fn ancestry(repo: &Path, ancestor: &str, of: &str) -> Result<bool> {
1530 let out = git_raw(repo, &["merge-base", "--is-ancestor", ancestor, of]).await?;
1531 match out.code {
1532 Some(0) => Ok(true),
1533 Some(1) => Ok(false),
1534 _ => bail!(
1535 "git merge-base --is-ancestor {ancestor} {of} failed ({}): {}",
1536 crate::notices::exit_status(out.code),
1537 out.stderr
1538 ),
1539 }
1540}
1541
1542pub async fn commit_of(repo: &Path, rev: &str) -> Option<String> {
1544 let spec = format!("{rev}^{{commit}}");
1545 let out = git_raw(repo, &["rev-parse", "--verify", "--quiet", &spec])
1546 .await
1547 .ok()?;
1548 (out.ok() && !out.stdout.is_empty()).then_some(out.stdout)
1549}
1550
1551pub async fn branches_containing(repo: &Path, commit: &str) -> Result<Vec<String>> {
1553 let out = git(
1554 repo,
1555 &[
1556 "branch",
1557 "-a",
1558 "--contains",
1559 commit,
1560 "--format=%(refname:short)",
1561 ],
1562 )
1563 .await?;
1564 Ok(out
1565 .lines()
1566 .map(str::trim)
1567 .filter(|l| !l.is_empty() && !l.ends_with("/HEAD") && !l.contains("HEAD detached"))
1568 .map(str::to_owned)
1569 .collect())
1570}
1571
1572pub async fn cherry_pick(worktree: &Path, commit: &str) -> Result<()> {
1576 let out = git_raw(
1577 worktree,
1578 &[
1579 "-c",
1580 "user.name=magi candidate",
1581 "-c",
1582 "user.email=magi@localhost",
1583 "cherry-pick",
1584 "-x",
1585 commit,
1586 ],
1587 )
1588 .await?;
1589 if out.ok() {
1590 return Ok(());
1591 }
1592 let _ = git_raw(worktree, &["cherry-pick", "--abort"]).await;
1593 bail!(
1594 "cherry-pick of {commit} failed: {}",
1595 if out.stderr.is_empty() {
1596 out.stdout
1597 } else {
1598 out.stderr
1599 }
1600 )
1601}
1602
1603pub async fn tree_of(repo: &Path, rev: &str) -> Result<String> {
1605 git(repo, &["rev-parse", &format!("{rev}^{{tree}}")]).await
1606}
1607
1608pub async fn rev_exists(repo: &Path, rev: &str) -> bool {
1610 git_raw(repo, &["rev-parse", "--verify", "--quiet", rev])
1611 .await
1612 .is_ok_and(|o| o.ok())
1613}
1614
1615#[cfg(test)]
1616mod tests {
1617 #[tokio::test]
1618 async fn checkout_discovery_ignores_inherited_git_target() {
1619 const FIXTURE: &str = "MAGI_TEST_CHECKOUT_DISCOVERY_ROOT";
1620 if let Some(root) = std::env::var_os(FIXTURE) {
1621 let root = std::path::PathBuf::from(root);
1622 let first = root.join("first");
1623 let second = root.join("second");
1624 let plain = root.join("plain");
1625 assert_eq!(
1626 super::toplevel(&second)
1627 .await
1628 .unwrap()
1629 .canonicalize()
1630 .unwrap(),
1631 second.canonicalize().unwrap()
1632 );
1633 assert!(super::toplevel(&plain).await.is_err());
1634 assert!(!super::same_checkout(&first, &second).unwrap());
1635 assert!(super::same_checkout(&first, &plain).is_err());
1636 assert!(super::same_checkout(&first, &first.join("src")).unwrap());
1637 return;
1638 }
1639 let fixture = tempfile::tempdir().unwrap();
1640 let root = fixture.path();
1641 for name in ["first", "second"] {
1642 let checkout = root.join(name);
1643 std::fs::create_dir_all(checkout.join("src")).unwrap();
1644 super::git(&checkout, &["init", "-q"]).await.unwrap();
1645 }
1646 std::fs::create_dir(root.join("plain")).unwrap();
1647 let output = std::process::Command::new(std::env::current_exe().unwrap())
1648 .args([
1649 "--exact",
1650 "git::tests::checkout_discovery_ignores_inherited_git_target",
1651 ])
1652 .env(FIXTURE, root)
1653 .env("GIT_DIR", root.join("first/.git"))
1654 .env("GIT_WORK_TREE", root.join("first"))
1655 .env("GIT_CONFIG_COUNT", "1")
1656 .env("GIT_CONFIG_KEY_0", "core.worktree")
1657 .env("GIT_CONFIG_VALUE_0", root.join("first"))
1658 .output()
1659 .unwrap();
1660 let stdout = String::from_utf8_lossy(&output.stdout);
1661 assert!(
1662 output.status.success() && stdout.contains("1 passed"),
1663 "{stdout}"
1664 );
1665 }
1666
1667 #[test]
1668 fn git_cli_path_spelling_handles_windows_canonical_prefixes() {
1669 for (native, expected) in [
1670 (r"\\?\C:\temp\work tree", "C:/temp/work tree"),
1671 (
1672 r"\\?\UNC\server\share\work tree",
1673 "//server/share/work tree",
1674 ),
1675 (r"C:\temp\work tree", "C:/temp/work tree"),
1676 ("C:/temp/work tree", "C:/temp/work tree"),
1677 ] {
1678 assert_eq!(super::windows_cli_path(native), expected);
1679 }
1680 }
1681
1682 #[test]
1683 fn git_cli_path_spelling_does_not_alias_extended_only_names() {
1684 for path in [
1685 r"\\?\C:\temp.\copy",
1686 r"\\?\C:\temp \copy",
1687 r"\\?\C:\NUL.txt\copy",
1688 r"\\?\C:\COM1\copy",
1689 ] {
1690 assert!(super::windows_cli_path(path).starts_with("//?/"));
1691 }
1692 }
1693
1694 #[cfg(unix)]
1695 #[test]
1696 fn git_cli_path_spelling_preserves_native_paths_on_unix() {
1697 assert_eq!(
1698 super::path_arg(std::path::Path::new(r"/tmp/back\slash")),
1699 r"/tmp/back\slash"
1700 );
1701 }
1702
1703 #[test]
1704 fn git_cli_canonical_output_accepts_platform_spelling_and_rejects_aliases() {
1705 let temp = tempfile::tempdir().unwrap();
1706 let canonical = temp.path().canonicalize().unwrap();
1707 let printed = super::path_arg(&canonical);
1708 assert_eq!(super::canonical_output_path(&printed).unwrap(), canonical);
1709 let noncanonical = format!("{printed}/child/..");
1712 std::fs::create_dir(canonical.join("child")).unwrap();
1713 assert!(super::canonical_output_path(&noncanonical).is_err());
1714 #[cfg(unix)]
1715 {
1716 let alias = canonical.join("alias");
1717 std::os::unix::fs::symlink(canonical.join("child"), &alias).unwrap();
1718 assert!(super::canonical_output_path(alias.to_str().unwrap()).is_err());
1719 }
1720 }
1721
1722 use super::*;
1723
1724 #[test]
1725 fn worktree_holder_is_read_from_the_porcelain_listing() {
1726 let listing = "worktree /repo\nHEAD aaa\nbranch refs/heads/main\n\n\
1727 worktree /wt/cand-A\nHEAD bbb\nbranch refs/heads/magi/f82f/A\n\n\
1728 worktree /wt/detached\nHEAD ccc\ndetached\n";
1729 assert_eq!(
1730 parse_worktree_holder(listing, "magi/f82f/A"),
1731 Some(PathBuf::from("/wt/cand-A"))
1732 );
1733 assert_eq!(parse_worktree_holder(listing, "magi/f82f"), None);
1734 assert_eq!(parse_worktree_holder(listing, "other"), None);
1735 }
1736
1737 async fn scratch() -> (tempfile::TempDir, PathBuf) {
1738 let dir = tempfile::tempdir().unwrap();
1739 let repo = dir.path().join("repo");
1740 tokio::fs::create_dir_all(&repo).await.unwrap();
1741 git(&repo, &["init", "-b", "main"]).await.unwrap();
1742 git(&repo, &["config", "user.name", "test"]).await.unwrap();
1743 git(&repo, &["config", "user.email", "test@example.com"])
1744 .await
1745 .unwrap();
1746 tokio::fs::write(repo.join("a.txt"), "one\n").await.unwrap();
1747 git(&repo, &["add", "-A"]).await.unwrap();
1748 git(&repo, &["commit", "-m", "init"]).await.unwrap();
1749 (dir, repo)
1750 }
1751
1752 #[tokio::test]
1753 async fn restore_to_removes_nested_repositories_inside_submodules() {
1754 let (_parent_dir, repo) = scratch().await;
1755 let (_source_dir, source) = scratch().await;
1756 sh(
1757 &repo,
1758 &[
1759 "-c",
1760 "protocol.file.allow=always",
1761 "submodule",
1762 "add",
1763 &source.to_string_lossy(),
1764 "sub",
1765 ],
1766 );
1767 sh(&repo, &["commit", "-am", "add submodule"]);
1768 let pre = rev_parse(&repo, "HEAD").await.unwrap();
1769 let sub = repo.join("sub");
1770 sh(&sub, &["init", "nested"]);
1771 tokio::fs::write(sub.join("nested/rejected.txt"), "rejected\n")
1772 .await
1773 .unwrap();
1774
1775 restore_to(&repo, &pre).await.unwrap();
1776
1777 assert!(!sub.join("nested").exists());
1778 assert_eq!(rev_parse(&repo, "HEAD").await.unwrap(), pre);
1779 assert_eq!(
1780 rev_parse(&sub, "HEAD").await.unwrap(),
1781 rev_parse(&source, "HEAD").await.unwrap()
1782 );
1783 assert!(
1784 git(&repo, &["status", "--porcelain"])
1785 .await
1786 .unwrap()
1787 .is_empty()
1788 );
1789 }
1790
1791 #[tokio::test]
1792 async fn a_branch_rebases_onto_a_moved_base_and_says_when_it_cannot() {
1793 let (_g, repo) = scratch().await;
1794
1795 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1797 tokio::fs::write(repo.join("b.txt"), "side\n")
1798 .await
1799 .unwrap();
1800 git(&repo, &["add", "-A"]).await.unwrap();
1801 git(&repo, &["commit", "-m", "side work"]).await.unwrap();
1802
1803 git(&repo, &["checkout", "main"]).await.unwrap();
1806 tokio::fs::write(repo.join("c.txt"), "main\n")
1807 .await
1808 .unwrap();
1809 git(&repo, &["add", "-A"]).await.unwrap();
1810 git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
1811
1812 let scratch_tree = repo.parent().unwrap().join("rebase-scratch");
1813 let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
1814 .await
1815 .unwrap();
1816 assert!(clean.is_none(), "a disjoint change rebases: {clean:?}");
1817 assert_eq!(
1818 commits_ahead(&repo, "main", "side").await.unwrap(),
1819 1,
1820 "one commit, replayed onto the new base"
1821 );
1822 assert!(
1823 !scratch_tree.exists(),
1824 "the throwaway worktree is not left behind"
1825 );
1826
1827 git(&repo, &["checkout", "-b", "clash"]).await.unwrap();
1829 tokio::fs::write(repo.join("a.txt"), "clash\n")
1830 .await
1831 .unwrap();
1832 git(&repo, &["add", "-A"]).await.unwrap();
1833 git(&repo, &["commit", "-m", "clash"]).await.unwrap();
1834 git(&repo, &["checkout", "main"]).await.unwrap();
1835 tokio::fs::write(repo.join("a.txt"), "main edit\n")
1836 .await
1837 .unwrap();
1838 git(&repo, &["add", "-A"]).await.unwrap();
1839 git(&repo, &["commit", "-m", "main edit"]).await.unwrap();
1840
1841 let before = rev_parse(&repo, "clash").await.unwrap();
1842 let why = rebase_branch_in_temp(&repo, &scratch_tree, "clash", "main")
1843 .await
1844 .unwrap()
1845 .expect("a same-line clash cannot be rebased silently");
1846 assert!(
1847 why.to_lowercase().contains("conflict"),
1848 "the reason is what git said, which is what a person needs: {why}"
1849 );
1850 assert_eq!(
1851 rev_parse(&repo, "clash").await.unwrap(),
1852 before,
1853 "a failed rebase leaves the branch exactly where it was"
1854 );
1855 assert!(!scratch_tree.exists(), "and cleans up after itself");
1856 }
1857
1858 #[tokio::test]
1859 async fn merge_squash_folds_the_branch_into_one_commit_under_the_given_message() {
1860 let (_g, repo) = scratch().await;
1861 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1862 for name in ["b.txt", "c.txt"] {
1863 tokio::fs::write(repo.join(name), "side\n").await.unwrap();
1864 git(&repo, &["add", "-A"]).await.unwrap();
1865 git(
1866 &repo,
1867 &["commit", "-m", "magi: candidate A (uncommitted work)"],
1868 )
1869 .await
1870 .unwrap();
1871 }
1872 git(&repo, &["checkout", "main"]).await.unwrap();
1873 let before = rev_parse(&repo, "main").await.unwrap();
1874
1875 let out = merge_squash(&repo, "side", "an explicit subject")
1876 .await
1877 .unwrap();
1878 assert!(out.ok(), "{}", out.stderr);
1879 assert_eq!(
1880 commits_ahead(&repo, &before, "main").await.unwrap(),
1881 1,
1882 "squash adds exactly one commit onto the tip, not one per candidate commit"
1883 );
1884 let subject = git(&repo, &["log", "-1", "--format=%s"]).await.unwrap();
1885 assert_eq!(
1886 subject, "an explicit subject",
1887 "the candidate's own placeholder subject must not survive: {subject}"
1888 );
1889 }
1890
1891 #[tokio::test]
1892 async fn merge_ff_only_fast_forwards_a_branch_already_rebased_onto_the_tip() {
1893 let (_g, repo) = scratch().await;
1894 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1895 tokio::fs::write(repo.join("b.txt"), "side\n")
1896 .await
1897 .unwrap();
1898 git(&repo, &["add", "-A"]).await.unwrap();
1899 git(&repo, &["commit", "-m", "side work"]).await.unwrap();
1900 git(&repo, &["checkout", "main"]).await.unwrap();
1901
1902 let before = rev_parse(&repo, "side").await.unwrap();
1903 let out = merge_ff_only(&repo, "side").await.unwrap();
1904 assert!(out.ok(), "{}", out.stderr);
1905 assert_eq!(
1906 rev_parse(&repo, "main").await.unwrap(),
1907 before,
1908 "a fast-forward moves the base tip to the branch, no merge commit"
1909 );
1910 }
1911
1912 #[tokio::test]
1913 async fn merge_ff_only_refuses_to_write_a_merge_commit() {
1914 let (_g, repo) = scratch().await;
1915 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1916 tokio::fs::write(repo.join("b.txt"), "side\n")
1917 .await
1918 .unwrap();
1919 git(&repo, &["add", "-A"]).await.unwrap();
1920 git(&repo, &["commit", "-m", "side work"]).await.unwrap();
1921
1922 git(&repo, &["checkout", "main"]).await.unwrap();
1924 tokio::fs::write(repo.join("c.txt"), "main\n")
1925 .await
1926 .unwrap();
1927 git(&repo, &["add", "-A"]).await.unwrap();
1928 git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
1929
1930 let before = rev_parse(&repo, "main").await.unwrap();
1931 let out = merge_ff_only(&repo, "side").await.unwrap();
1932 assert!(!out.ok(), "a divergent branch cannot fast-forward");
1933 assert_eq!(
1934 rev_parse(&repo, "main").await.unwrap(),
1935 before,
1936 "a refused fast-forward must not touch main"
1937 );
1938 }
1939
1940 #[tokio::test]
1941 async fn a_sibling_worktree_stays_stale_after_a_rebase_until_synced() {
1942 let (guard, repo) = scratch().await;
1943
1944 git(&repo, &["branch", "side"]).await.unwrap();
1948 let side_wt = guard.path().join("side-wt");
1949 git(
1950 &repo,
1951 &["worktree", "add", &side_wt.to_string_lossy(), "side"],
1952 )
1953 .await
1954 .unwrap();
1955 tokio::fs::write(side_wt.join("b.txt"), "candidate\n")
1956 .await
1957 .unwrap();
1958 git(&side_wt, &["add", "-A"]).await.unwrap();
1959 git(&side_wt, &["commit", "-m", "side work"]).await.unwrap();
1960
1961 git(&repo, &["checkout", "main"]).await.unwrap();
1963 tokio::fs::write(repo.join("c.txt"), "main\n")
1964 .await
1965 .unwrap();
1966 git(&repo, &["add", "-A"]).await.unwrap();
1967 git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
1968
1969 let scratch_tree = guard.path().join("rebase-scratch");
1971 let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
1972 .await
1973 .unwrap();
1974 assert!(clean.is_none());
1975
1976 assert_eq!(
1980 rev_parse(&side_wt, "HEAD").await.unwrap(),
1981 rev_parse(&repo, "side").await.unwrap(),
1982 "HEAD follows the moved ref"
1983 );
1984 assert!(
1985 !side_wt.join("c.txt").exists(),
1986 "stale until synced: main's new file has not reached this worktree's disk"
1987 );
1988
1989 sync_to_head(&side_wt).await.unwrap();
1990 assert!(side_wt.join("c.txt").is_file(), "synced now");
1991 assert!(
1992 side_wt.join("b.txt").is_file(),
1993 "the worktree's own committed work survives the sync"
1994 );
1995 assert!(is_clean(&side_wt).await.unwrap());
1996 }
1997
1998 #[tokio::test]
1999 async fn clean_repo_reports_clean_then_dirty() {
2000 let (_g, repo) = scratch().await;
2001 assert!(is_clean(&repo).await.unwrap());
2002 tokio::fs::write(repo.join("a.txt"), "two\n").await.unwrap();
2003 assert!(!is_clean(&repo).await.unwrap());
2004 }
2005
2006 async fn track(repo: &Path, name: &str, body: &str) {
2007 let p = repo.join(name);
2008 if let Some(d) = p.parent() {
2009 tokio::fs::create_dir_all(d).await.unwrap();
2010 }
2011 tokio::fs::write(&p, body).await.unwrap();
2012 git(repo, &["add", name]).await.unwrap();
2013 git(
2014 repo,
2015 &[
2016 "-c",
2017 "user.name=t",
2018 "-c",
2019 "user.email=t@localhost",
2020 "commit",
2021 "-q",
2022 "-m",
2023 "seed",
2024 ],
2025 )
2026 .await
2027 .unwrap();
2028 }
2029
2030 #[tokio::test]
2031 async fn rescue_withholds_a_foreign_lockfile() {
2032 let (_g, repo) = scratch().await;
2033 track(&repo, "web/bun.lock", "a\n").await;
2034 tokio::fs::write(repo.join("web/pnpm-lock.yaml"), "x\n")
2035 .await
2036 .unwrap();
2037 tokio::fs::write(repo.join("web/app.ts"), "real\n")
2038 .await
2039 .unwrap();
2040
2041 let r = rescue_commit(&repo, "rescue").await.unwrap();
2042 assert!(r.committed);
2043 assert_eq!(
2044 r.withheld,
2045 [Stray {
2046 path: "web/pnpm-lock.yaml".to_owned(),
2047 manager: "pnpm".to_owned(),
2048 kept_by: "web/bun.lock".to_owned(),
2049 }]
2050 );
2051 let files = git(&repo, &["show", "--name-only", "--format=", "HEAD"])
2052 .await
2053 .unwrap();
2054 assert!(files.contains("web/app.ts"), "{files}");
2055 assert!(!files.contains("pnpm-lock"), "{files}");
2056 assert!(repo.join("web/pnpm-lock.yaml").is_file(), "not deleted");
2057 }
2058
2059 #[tokio::test]
2060 async fn rescue_with_only_a_stray_commits_nothing() {
2061 let (_g, repo) = scratch().await;
2062 track(&repo, "bun.lock", "a\n").await;
2063 tokio::fs::write(repo.join("yarn.lock"), "x\n")
2064 .await
2065 .unwrap();
2066 let r = rescue_commit(&repo, "rescue").await.unwrap();
2067 assert!(!r.committed);
2068 assert_eq!(r.withheld.len(), 1);
2069 }
2070
2071 #[tokio::test]
2072 async fn rescue_keeps_a_same_manager_lockfile_update() {
2073 let (_g, repo) = scratch().await;
2074 track(&repo, "bun.lock", "a\n").await;
2075 tokio::fs::write(repo.join("bun.lock"), "b\n")
2076 .await
2077 .unwrap();
2078 let r = rescue_commit(&repo, "rescue").await.unwrap();
2079 assert!(r.committed);
2080 assert!(r.withheld.is_empty());
2081 let files = git(&repo, &["show", "--name-only", "--format=", "HEAD"])
2082 .await
2083 .unwrap();
2084 assert_eq!(files, "bun.lock");
2085 }
2086
2087 #[tokio::test]
2088 async fn rescue_keeps_the_first_lockfile_in_a_bare_directory() {
2089 let (_g, repo) = scratch().await;
2090 track(&repo, "other/bun.lock", "a\n").await;
2091 tokio::fs::create_dir_all(repo.join("web")).await.unwrap();
2092 tokio::fs::write(repo.join("web/package-lock.json"), "{}\n")
2093 .await
2094 .unwrap();
2095 let r = rescue_commit(&repo, "rescue").await.unwrap();
2096 assert!(r.committed);
2097 assert!(r.withheld.is_empty());
2098 }
2099
2100 #[test]
2101 fn a_cargo_lock_is_foreign_only_without_a_cargo_toml() {
2102 let s = |v: &[&str]| v.iter().map(|x| (*x).to_owned()).collect::<Vec<_>>();
2103 assert_eq!(stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&[])).len(), 1);
2104 assert!(stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&["a/Cargo.toml"])).is_empty());
2105 assert!(stray_lockfiles(&s(&["a/Cargo.lock", "a/Cargo.toml"]), &s(&[])).is_empty());
2106 assert_eq!(
2108 stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&["Cargo.toml"])).len(),
2109 1
2110 );
2111 }
2112
2113 #[tokio::test]
2114 async fn clean_removal_preserves_edits_while_scratch_removal_discards_them() {
2115 let (guard, repo) = scratch().await;
2116 let wt = guard.path().join("scratch-wt");
2117 worktree_add_detached(&repo, &wt, "HEAD").await.unwrap();
2118 tokio::fs::write(wt.join("built.txt"), "build output")
2119 .await
2120 .unwrap();
2121 assert!(!worktree_remove_clean(&repo, &wt).await.unwrap());
2122 assert!(wt.join("built.txt").exists());
2123 let listing = git(&repo, &["worktree", "list", "--porcelain"])
2124 .await
2125 .unwrap();
2126 let registered = listing
2127 .lines()
2128 .filter_map(|line| line.strip_prefix("worktree "))
2129 .map(PathBuf::from)
2130 .find(|path| path.canonicalize().unwrap() == wt.canonicalize().unwrap())
2131 .expect("the refused removal must retain the worktree registration");
2132 assert!(worktree_remove(&repo, &wt).await.unwrap());
2133 assert!(!wt.exists());
2134 let listing = git(&repo, &["worktree", "list", "--porcelain"])
2135 .await
2136 .unwrap();
2137 assert!(!listing.lines().any(|line| {
2138 line.strip_prefix("worktree ")
2139 .is_some_and(|path| Path::new(path) == registered)
2140 }));
2141 }
2142
2143 #[tokio::test]
2144 async fn worktree_lifecycle_and_diff() {
2145 let (guard, repo) = scratch().await;
2146 let base = rev_parse(&repo, "HEAD").await.unwrap();
2147 let wt = guard.path().join("wt-a");
2148 worktree_add_branch(&repo, &wt, "magi/test/a", &base)
2149 .await
2150 .unwrap();
2151 tokio::fs::write(wt.join("b.txt"), "candidate\n")
2152 .await
2153 .unwrap();
2154
2155 assert!(commit_all(&wt, "candidate work").await.unwrap());
2156 assert!(!commit_all(&wt, "nothing left").await.unwrap());
2157
2158 assert_eq!(commits_ahead(&wt, &base, "HEAD").await.unwrap(), 1);
2159 let patch = diff(&wt, &base, "HEAD").await.unwrap();
2160 assert!(patch.contains("b.txt"), "patch was: {patch}");
2161 assert_eq!(
2162 changed_files(&wt, &base, "HEAD").await.unwrap(),
2163 ["b.txt".to_owned()]
2164 );
2165
2166 let author = git(&wt, &["log", "-1", "--format=%an <%ae>"])
2168 .await
2169 .unwrap();
2170 assert_eq!(author, "magi candidate <magi@localhost>");
2171
2172 assert!(worktree_remove(&repo, &wt).await.unwrap());
2173 assert!(branch_exists(&repo, "magi/test/a").await.unwrap());
2174 assert!(branch_delete(&repo, "magi/test/a").await.unwrap());
2175 assert!(!branch_exists(&repo, "magi/test/a").await.unwrap());
2176 }
2177
2178 #[tokio::test]
2179 async fn worktree_scoped_hooks_path_does_not_leak_to_primary() {
2180 let (guard, repo) = scratch().await;
2181 let base = rev_parse(&repo, "HEAD").await.unwrap();
2182 let wt = guard.path().join("wt-h");
2183 worktree_add_branch(&repo, &wt, "magi/test/h", &base)
2184 .await
2185 .unwrap();
2186 let hooks = guard.path().join("hooks");
2187 tokio::fs::create_dir_all(&hooks).await.unwrap();
2188
2189 assert!(enable_worktree_config(&repo).await.unwrap());
2190 set_worktree_hooks_path(&wt, &hooks).await.unwrap();
2191
2192 let in_wt = git(&wt, &["config", "--get", "core.hooksPath"])
2193 .await
2194 .unwrap();
2195 assert!(!in_wt.is_empty());
2196 let in_primary = git_raw(&repo, &["config", "--get", "core.hooksPath"])
2197 .await
2198 .unwrap();
2199 assert!(
2200 !in_primary.ok(),
2201 "primary worktree must keep its own hooks: {in_primary:?}"
2202 );
2203
2204 disable_worktree_config(&repo).await.unwrap();
2205 }
2206
2207 #[tokio::test]
2208 async fn worktree_config_stays_on_while_a_sibling_run_still_holds_it() {
2209 let (_g, repo) = scratch().await;
2210
2211 acquire_worktree_config(&repo).await.unwrap();
2214 acquire_worktree_config(&repo).await.unwrap();
2215
2216 let on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
2217 .await
2218 .unwrap();
2219 assert_eq!(on, "true");
2220
2221 release_worktree_config(&repo).await.unwrap();
2225 let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
2226 .await
2227 .unwrap();
2228 assert_eq!(
2229 still_on, "true",
2230 "a sibling run's release must not disable the setting for the one still working"
2231 );
2232
2233 release_worktree_config(&repo).await.unwrap();
2235 let after = git_raw(&repo, &["config", "--get", "extensions.worktreeConfig"])
2236 .await
2237 .unwrap();
2238 assert!(
2239 !after.ok(),
2240 "the last release must turn the setting back off: {after:?}"
2241 );
2242 }
2243
2244 #[tokio::test]
2245 async fn worktree_config_already_on_before_magi_touched_it_is_left_alone() {
2246 let (_g, repo) = scratch().await;
2247 git(&repo, &["config", "extensions.worktreeConfig", "true"])
2248 .await
2249 .unwrap();
2250
2251 acquire_worktree_config(&repo).await.unwrap();
2256 release_worktree_config(&repo).await.unwrap();
2257
2258 let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
2259 .await
2260 .unwrap();
2261 assert_eq!(still_on, "true");
2262 }
2263
2264 #[tokio::test]
2265 async fn local_exclude_is_idempotent() {
2266 let (_g, repo) = scratch().await;
2267 local_exclude(&repo, "/.magi/").await.unwrap();
2268 local_exclude(&repo, "/.magi/").await.unwrap();
2269 let path = repo.join(".git/info/exclude");
2270 let body = tokio::fs::read_to_string(&path).await.unwrap();
2271 assert_eq!(body.matches("/.magi/").count(), 1);
2272 }
2273
2274 fn sh(cwd: &Path, args: &[&str]) {
2275 let out = std::process::Command::new("git")
2276 .quiet()
2277 .args(args)
2278 .current_dir(cwd)
2279 .output()
2280 .unwrap();
2281 assert!(
2282 out.status.success(),
2283 "git {args:?}: {}",
2284 String::from_utf8_lossy(&out.stderr)
2285 );
2286 }
2287
2288 async fn with_remote() -> (tempfile::TempDir, PathBuf) {
2291 let (g, repo) = scratch().await;
2292 let bare = g.path().join("bare.git");
2293 sh(g.path(), &["init", "--bare", "-b", "trunk", "bare.git"]);
2294 sh(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
2295 sh(&repo, &["push", "origin", "HEAD:refs/heads/trunk"]);
2296 sh(&repo, &["fetch", "origin"]);
2297 (g, repo)
2298 }
2299
2300 #[test]
2301 fn remote_head_branch_strips_only_the_matching_remote() {
2302 assert_eq!(
2303 remote_head_branch("origin", "refs/remotes/origin/main\n").as_deref(),
2304 Some("main")
2305 );
2306 assert_eq!(remote_head_branch("up", "refs/remotes/origin/main"), None);
2307 assert_eq!(remote_head_branch("origin", "refs/remotes/origin/"), None);
2308 }
2309
2310 #[tokio::test]
2311 async fn merge_base_branch_reads_origin_head_when_present() {
2312 let (_g, repo) = with_remote().await;
2313 sh(&repo, &["remote", "set-head", "origin", "trunk"]);
2314 assert_eq!(
2315 merge_base_branch(&repo, "origin", None).await.unwrap(),
2316 "trunk"
2317 );
2318 }
2319
2320 #[tokio::test]
2321 async fn merge_base_branch_recovers_a_missing_origin_head() {
2322 let (_g, repo) = with_remote().await;
2323 sh(&repo, &["remote", "set-head", "origin", "-d"]);
2325 let head = git_raw(
2326 &repo,
2327 &["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"],
2328 )
2329 .await
2330 .unwrap();
2331 assert!(!head.ok(), "precondition: no origin/HEAD");
2332 assert_eq!(
2333 merge_base_branch(&repo, "origin", None).await.unwrap(),
2334 "trunk"
2335 );
2336 }
2337
2338 #[tokio::test]
2339 async fn merge_base_branch_errors_without_a_remote_and_never_uses_head() {
2340 let (_g, repo) = scratch().await;
2341 let err = merge_base_branch(&repo, "origin", None).await.unwrap_err();
2342 assert!(format!("{err:#}").contains("[merge] base"), "{err:#}");
2343 }
2344
2345 #[tokio::test]
2346 async fn merge_base_branch_prefers_the_explicit_base() {
2347 let (_g, repo) = with_remote().await;
2348 assert_eq!(
2349 merge_base_branch(&repo, "origin", Some("release"))
2350 .await
2351 .unwrap(),
2352 "release"
2353 );
2354 }
2355
2356 #[tokio::test]
2357 async fn merge_base_branch_names_an_unfetched_default_branch() {
2358 let (g, repo) = scratch().await;
2361 let bare = g.path().join("bare.git");
2362 sh(g.path(), &["init", "--bare", "-b", "trunk", "bare.git"]);
2363 sh(
2364 &repo,
2365 &["push", &bare.to_string_lossy(), "HEAD:refs/heads/trunk"],
2366 );
2367 sh(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
2368 assert!(!rev_exists(&repo, "refs/remotes/origin/trunk").await);
2369 assert_eq!(
2370 merge_base_branch(&repo, "origin", None).await.unwrap(),
2371 "trunk"
2372 );
2373 }
2374
2375 #[test]
2376 fn symref_branch_reads_ls_remote_output() {
2377 assert_eq!(
2378 symref_branch("ref: refs/heads/main\tHEAD\nabc\tHEAD\n").as_deref(),
2379 Some("main")
2380 );
2381 assert_eq!(symref_branch("abc\tHEAD\n"), None);
2382 }
2383}