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 = Command::from(toplevel_command(path))
190 .kill_on_drop(true)
191 .output()
192 .await;
193 toplevel_output(path, out)
194}
195
196pub(crate) fn toplevel_blocking(path: &Path) -> Result<PathBuf> {
198 toplevel_output(path, toplevel_command(path).output())?
199 .canonicalize()
200 .with_context(|| format!("canonicalize Git checkout root of {}", path.display()))
201}
202
203fn toplevel_command(path: &Path) -> std::process::Command {
204 #[cfg(test)]
205 crate::web::request_cost::git();
206 let mut command = std::process::Command::new("git");
207 command
208 .args(["rev-parse", "--show-toplevel"])
209 .current_dir(path)
210 .quiet()
211 .stdin(Stdio::null());
212 for key in [
214 "GIT_DIR",
215 "GIT_WORK_TREE",
216 "GIT_IMPLICIT_WORK_TREE",
217 "GIT_COMMON_DIR",
218 "GIT_CONFIG",
219 "GIT_CONFIG_PARAMETERS",
220 "GIT_CONFIG_COUNT",
221 "GIT_CONFIG_GLOBAL",
222 "GIT_CONFIG_SYSTEM",
223 "GIT_CEILING_DIRECTORIES",
224 "GIT_DISCOVERY_ACROSS_FILESYSTEM",
225 "GIT_PREFIX",
226 ] {
227 command.env_remove(key);
228 }
229 command
230}
231
232fn toplevel_output(path: &Path, out: std::io::Result<std::process::Output>) -> Result<PathBuf> {
233 let out = out.with_context(|| format!("read Git checkout root of {}", path.display()))?;
234 ensure!(
235 out.status.success(),
236 "cannot read Git checkout root of {}: {}",
237 path.display(),
238 String::from_utf8_lossy(&out.stderr).trim_end()
239 );
240 Ok(PathBuf::from(
241 std::str::from_utf8(&out.stdout)?.trim_end_matches(['\r', '\n']),
242 ))
243}
244
245pub(crate) fn same_checkout(left: &Path, right: &Path) -> Result<bool> {
248 if left == right {
249 return Ok(true);
250 }
251 let canonical = |path: &Path| {
252 path.canonicalize()
253 .with_context(|| format!("resolve repository {}", path.display()))
254 };
255 let left = canonical(left)?;
256 let right = canonical(right)?;
257 Ok(left == right || toplevel_blocking(&left)? == toplevel_blocking(&right)?)
258}
259
260pub async fn rev_parse(repo: &Path, rev: &str) -> Result<String> {
262 git(repo, &["rev-parse", rev]).await
263}
264
265pub async fn current_branch(repo: &Path) -> Result<Option<String>> {
267 let out = git_raw(repo, &["symbolic-ref", "--quiet", "--short", "HEAD"]).await?;
268 Ok(if out.ok() && !out.stdout.is_empty() {
269 Some(out.stdout)
270 } else {
271 None
272 })
273}
274
275pub fn remote_head_branch(remote: &str, symref: &str) -> Option<String> {
280 symref
281 .trim()
282 .strip_prefix(&format!("refs/remotes/{remote}/"))
283 .filter(|b| !b.is_empty() && *b != "HEAD")
284 .map(str::to_owned)
285}
286
287pub async fn ensure_remote_head(repo: &Path, remote: &str, base: &str) {
293 let head = format!("refs/remotes/{remote}/HEAD");
294 if git_raw(repo, &["symbolic-ref", "--quiet", &head])
295 .await
296 .is_ok_and(|o| o.ok())
297 {
298 return;
299 }
300 let target = format!("refs/remotes/{remote}/{base}");
301 let _ = git_raw(repo, &["symbolic-ref", &head, &target]).await;
302}
303
304fn symref_branch(out: &str) -> Option<String> {
307 out.lines()
308 .find_map(|l| l.strip_prefix("ref: refs/heads/"))
309 .and_then(|l| l.split_whitespace().next())
310 .map(str::to_owned)
311}
312
313pub async fn merge_base_branch(
320 repo: &Path,
321 remote: &str,
322 explicit: Option<&str>,
323) -> Result<String> {
324 if let Some(b) = explicit.map(str::trim).filter(|b| !b.is_empty()) {
325 return Ok(b.to_owned());
326 }
327 let head = format!("refs/remotes/{remote}/HEAD");
328 let read = || async {
329 let out = git_raw(repo, &["symbolic-ref", "--quiet", &head])
330 .await
331 .ok()?;
332 if out.ok() {
333 remote_head_branch(remote, &out.stdout)
334 } else {
335 None
336 }
337 };
338 if let Some(b) = read().await {
339 return Ok(b);
340 }
341 let set = git_raw(repo, &["remote", "set-head", remote, "-a"]).await;
342 if let Some(b) = read().await {
343 return Ok(b);
344 }
345 if let Ok(o) = git_raw(repo, &["ls-remote", "--symref", remote, "HEAD"]).await
350 && o.ok()
351 && let Some(b) = symref_branch(&o.stdout)
352 {
353 return Ok(b);
354 }
355 let why = match set {
356 Ok(o) if !o.ok() => o.stderr.lines().next().unwrap_or("").trim().to_owned(),
357 Ok(_) => "the remote reported no default branch".to_owned(),
358 Err(e) => e.to_string(),
359 };
360 bail!(
361 "cannot tell which branch of `{remote}` is the base ({why}): set [merge] base \
362 (and remote) in magi.toml, or run `git remote set-head {remote} -a`. magi does \
363 not fall back to the checked-out branch, which may be detached or stale"
364 )
365}
366
367pub async fn is_clean(repo: &Path) -> Result<bool> {
369 Ok(git(repo, &["status", "--porcelain"]).await?.is_empty())
370}
371
372pub async fn status_porcelain(repo: &Path) -> Result<String> {
374 git(repo, &["status", "--porcelain"]).await
375}
376
377pub async fn worktree_add_branch(repo: &Path, path: &Path, branch: &str, base: &str) -> Result<()> {
379 if let Some(parent) = path.parent() {
380 tokio::fs::create_dir_all(parent).await.ok();
381 }
382 let path_s = path_arg(path);
383 git(repo, &["worktree", "add", "-b", branch, &path_s, base])
384 .await
385 .map(|_| ())
386}
387
388pub(crate) async fn worktree_add_existing(
390 repo: &Path,
391 path: &Path,
392 branch: &str,
393 force: bool,
394) -> Result<()> {
395 if let Some(parent) = path.parent() {
396 tokio::fs::create_dir_all(parent).await.ok();
397 }
398 let path_s = path_arg(path);
399 if force {
400 git(repo, &["worktree", "add", "--force", &path_s, branch]).await
401 } else {
402 git(repo, &["worktree", "add", &path_s, branch]).await
403 }
404 .map(|_| ())
405}
406
407pub async fn worktree_add_detached(repo: &Path, path: &Path, rev: &str) -> Result<()> {
409 if let Some(parent) = path.parent() {
410 tokio::fs::create_dir_all(parent).await.ok();
411 }
412 let path_s = path_arg(path);
413 git(repo, &["worktree", "add", "--detach", &path_s, rev])
414 .await
415 .map(|_| ())
416}
417
418pub async fn reset_detached(worktree: &Path, rev: &str) -> Result<()> {
420 reset_detached_keep_ignored(worktree, rev).await?;
421 clean_all(worktree).await
422}
423
424pub async fn reset_detached_keep_ignored(worktree: &Path, rev: &str) -> Result<()> {
427 git(worktree, &["checkout", "--detach", rev]).await?;
428 git(worktree, &["reset", "--hard", rev]).await.map(|_| ())
429}
430
431pub async fn worktree_holding(repo: &Path, branch: &str) -> Result<Option<PathBuf>> {
436 let listing = git(repo, &["worktree", "list", "--porcelain"]).await?;
437 Ok(parse_worktree_holder(&listing, branch))
438}
439
440fn parse_worktree_holder(listing: &str, branch: &str) -> Option<PathBuf> {
441 let want = format!("refs/heads/{branch}");
442 let mut path: Option<PathBuf> = None;
443 for line in listing.lines() {
444 if let Some(p) = line.strip_prefix("worktree ") {
445 path = Some(PathBuf::from(p));
446 } else if line.strip_prefix("branch ") == Some(want.as_str()) {
447 return path;
448 }
449 }
450 None
451}
452
453pub async fn worktree_remove(repo: &Path, path: &Path) -> Result<bool> {
457 let path_s = path_arg(path);
458 let out = git_raw(repo, &["worktree", "remove", "--force", &path_s]).await?;
459 if out.ok() {
460 return Ok(true);
461 }
462 if !path.exists() {
464 git_raw(repo, &["worktree", "prune"]).await?;
465 }
466 Ok(false)
467}
468
469pub async fn worktree_remove_clean(repo: &Path, path: &Path) -> Result<bool> {
473 let path_s = path_arg(path);
474 Ok(git_raw(repo, &["worktree", "remove", &path_s]).await?.ok())
475}
476
477pub async fn remove_worktree_from_linked(dir: &Path) {
486 let Ok(link) = std::fs::read_to_string(dir.join(".git")) else {
487 return;
488 };
489 let Some(admin) = link.strip_prefix("gitdir:").map(str::trim) else {
490 return;
491 };
492 let admin = Path::new(admin);
495 let Some(common) = admin.parent().and_then(Path::parent) else {
496 return;
497 };
498 let common_s = common.to_string_lossy();
499 let _ = git_raw(dir, &["--git-dir", &common_s, "worktree", "prune"]).await;
500}
501
502pub async fn worktree_prune(repo: &Path) -> Result<()> {
511 git(repo, &["worktree", "prune"]).await.map(|_| ())
512}
513
514pub async fn branch_delete(repo: &Path, branch: &str) -> Result<bool> {
516 Ok(git_raw(repo, &["branch", "-D", branch]).await?.ok())
517}
518
519pub async fn branch_exists(repo: &Path, branch: &str) -> Result<bool> {
521 let refname = format!("refs/heads/{branch}");
522 Ok(
523 git_raw(repo, &["show-ref", "--verify", "--quiet", &refname])
524 .await?
525 .ok(),
526 )
527}
528
529pub async fn remote_has_branch(repo: &Path, remote: &str, branch: &str) -> Result<bool> {
532 let refname = format!("refs/heads/{branch}");
533 let out = git_raw(repo, &["ls-remote", "--exit-code", remote, &refname]).await?;
534 match out.code {
535 Some(0) => Ok(true),
536 Some(2) => Ok(false),
537 code => bail!(
538 "git ls-remote {remote} failed ({}): {}",
539 crate::notices::exit_status(code),
540 out.stderr
541 ),
542 }
543}
544
545pub async fn diff(worktree: &Path, base: &str, head: &str) -> Result<String> {
547 let range = format!("{base}...{head}");
548 git(
549 worktree,
550 &["diff", "--no-color", "--no-ext-diff", "-M", &range],
551 )
552 .await
553}
554
555pub async fn diff_stat(worktree: &Path, base: &str, head: &str) -> Result<String> {
557 let range = format!("{base}...{head}");
558 git(worktree, &["diff", "--no-color", "--stat", &range]).await
559}
560
561pub async fn changed_lines(worktree: &Path, base: &str, head: &str) -> Option<usize> {
565 let out = git_raw(worktree, &["diff", "--numstat", base, head])
566 .await
567 .ok()?;
568 if !out.ok() {
569 return None;
570 }
571 let mut total = 0usize;
572 for line in out.stdout.lines().filter(|l| !l.trim().is_empty()) {
573 let mut cols = line.split('\t');
574 let added: usize = cols.next()?.parse().ok()?;
575 let removed: usize = cols.next()?.parse().ok()?;
576 total = total.saturating_add(added).saturating_add(removed);
577 }
578 Some(total)
579}
580
581pub async fn restore_to(worktree: &Path, rev: &str) -> Result<()> {
585 git(worktree, &["reset", "--hard", "-q", rev]).await?;
586 git(worktree, &["clean", "-ffdq"]).await?;
589 git(
595 worktree,
596 &[
597 "submodule",
598 "--quiet",
599 "update",
600 "--recursive",
601 "--force",
602 "--checkout",
603 ],
604 )
605 .await?;
606 git(
607 worktree,
608 &[
609 "submodule",
610 "--quiet",
611 "foreach",
612 "--recursive",
613 "git clean -ffdq",
614 ],
615 )
616 .await?;
617 Ok(())
618}
619
620pub async fn changed_files(worktree: &Path, base: &str, head: &str) -> Result<Vec<String>> {
622 let range = format!("{base}...{head}");
623 let out = git(worktree, &["diff", "--name-only", &range]).await?;
624 Ok(out.lines().map(str::to_owned).collect())
625}
626
627pub async fn commit_log(worktree: &Path, base: &str, head: &str) -> Result<Vec<(String, String)>> {
631 let range = format!("{base}..{head}");
632 let out = git(
633 worktree,
634 &[
635 "log",
636 "--reverse",
637 "--no-color",
638 "--format=%s%x1f%b%x00",
639 &range,
640 ],
641 )
642 .await?;
643 Ok(out
644 .split('\0')
645 .filter_map(|rec| {
646 let rec = rec.trim_start_matches('\n');
647 if rec.trim().is_empty() {
648 return None;
649 }
650 let (subject, body) = rec.split_once('\x1f').unwrap_or((rec, ""));
651 Some((subject.trim().to_owned(), body.trim().to_owned()))
652 })
653 .collect())
654}
655
656pub async fn log_oneline(worktree: &Path, base: &str, head: &str) -> Result<String> {
658 let range = format!("{base}..{head}");
659 git(
660 worktree,
661 &["log", "--reverse", "--format=%s%n%b%n--", &range],
662 )
663 .await
664}
665
666pub async fn subjects(worktree: &Path, base: &str, head: &str) -> Result<Vec<String>> {
669 let range = format!("{base}..{head}");
670 let out = git(worktree, &["log", "--reverse", "--format=%s%x00", &range]).await?;
671 let mut parts: Vec<String> = out.split('\0').map(|s| s.trim().to_owned()).collect();
672 parts.pop();
674 Ok(parts)
675}
676
677pub async fn commits_ahead(worktree: &Path, base: &str, head: &str) -> Result<usize> {
679 let range = format!("{base}..{head}");
680 let out = git(worktree, &["rev-list", "--count", &range]).await?;
681 Ok(out.trim().parse().unwrap_or(0))
682}
683
684pub async fn commit_all(worktree: &Path, message: &str) -> Result<bool> {
691 if git(worktree, &["status", "--porcelain"]).await?.is_empty() {
692 return Ok(false);
693 }
694 git(worktree, &["add", "-A"]).await?;
695 if !crate::worktree_setup::withheld_paths(worktree)
697 .await
698 .is_empty()
699 {
700 crate::worktree_setup::unstage_products(worktree).await?;
701 if git_raw(worktree, &["diff", "--cached", "--quiet"])
702 .await?
703 .ok()
704 {
705 return Ok(false);
706 }
707 }
708 let out = git_raw(
709 worktree,
710 &[
711 "-c",
712 "user.name=magi candidate",
713 "-c",
714 "user.email=magi@localhost",
715 "commit",
716 "--no-verify",
717 "-m",
718 message,
719 ],
720 )
721 .await?;
722 if !out.ok() {
723 bail!("rescue commit failed: {}", out.stderr);
724 }
725 Ok(true)
726}
727
728#[derive(Debug, Clone, PartialEq, Eq)]
731pub struct Stray {
732 pub path: String,
734 pub manager: String,
736 pub kept_by: String,
739}
740
741#[derive(Debug, Default)]
743pub struct Rescue {
744 pub committed: bool,
746 pub withheld: Vec<Stray>,
748}
749
750fn lock_kind(name: &str) -> Option<(&'static str, &'static str)> {
752 Some(match name {
753 "package-lock.json" | "npm-shrinkwrap.json" => ("node", "npm"),
754 "yarn.lock" => ("node", "yarn"),
755 "pnpm-lock.yaml" => ("node", "pnpm"),
756 "bun.lock" | "bun.lockb" => ("node", "bun"),
757 "poetry.lock" => ("python", "poetry"),
758 "uv.lock" => ("python", "uv"),
759 "Pipfile.lock" => ("python", "pipenv"),
760 "pdm.lock" => ("python", "pdm"),
761 "Cargo.lock" => ("rust", "cargo"),
762 _ => return None,
763 })
764}
765
766fn split_dir(path: &str) -> (&str, &str) {
767 path.rsplit_once('/').unwrap_or(("", path))
768}
769
770pub fn stray_lockfiles(untracked: &[String], tracked: &[String]) -> Vec<Stray> {
778 let mut out = Vec::new();
779 for path in untracked {
780 let (dir, name) = split_dir(path);
781 let Some((eco, manager)) = lock_kind(name) else {
782 continue;
783 };
784 let beside = |other: &String| split_dir(other).0 == dir;
785 let kept_by = if manager == "cargo" {
786 let has_manifest = tracked
787 .iter()
788 .chain(untracked)
789 .any(|p| beside(p) && split_dir(p).1 == "Cargo.toml");
790 if has_manifest {
791 continue;
792 }
793 "no Cargo.toml in the directory".to_owned()
794 } else {
795 let Some(other) = tracked.iter().find(|p| {
796 beside(p)
797 && lock_kind(split_dir(p).1).is_some_and(|(e, m)| e == eco && m != manager)
798 }) else {
799 continue;
800 };
801 other.clone()
802 };
803 out.push(Stray {
804 path: path.clone(),
805 manager: manager.to_owned(),
806 kept_by,
807 });
808 }
809 out
810}
811
812async fn nul_list(worktree: &Path, args: &[&str]) -> Result<Vec<String>> {
813 let out = git(worktree, args).await?;
814 Ok(out
815 .split('\0')
816 .filter(|s| !s.is_empty())
817 .map(str::to_owned)
818 .collect())
819}
820
821pub async fn snapshot_uncommitted(worktree: &Path, destination: &Path) -> Result<()> {
825 if destination.exists() {
826 if destination.join("complete").exists() {
827 return Ok(());
828 }
829 bail!("earlier recovery snapshot is incomplete; retain original worktree");
830 }
831 std::fs::create_dir_all(destination)?;
832 for (name, args) in [
833 ("status.txt", vec!["status", "--porcelain=v1"]),
834 ("staged.patch", vec!["diff", "--binary", "--cached"]),
835 ("unstaged.patch", vec!["diff", "--binary"]),
836 ] {
837 let out = Command::new("git")
840 .args(&args)
841 .current_dir(worktree)
842 .quiet()
843 .stdin(Stdio::null())
844 .output()
845 .await?;
846 if !out.status.success() {
847 bail!(
848 "recovery snapshot failed: {}",
849 String::from_utf8_lossy(&out.stderr)
850 );
851 }
852 std::fs::write(destination.join(name), out.stdout)?;
853 }
854 let paths = nul_list(
855 worktree,
856 &["ls-files", "-z", "--others", "--exclude-standard"],
857 )
858 .await?;
859 for name in paths {
860 let relative = Path::new(&name);
861 if relative
862 .components()
863 .any(|c| !matches!(c, std::path::Component::Normal(_)))
864 {
865 bail!("unsafe recovery path");
866 }
867 let source = worktree.join(relative);
868 let target = destination.join("untracked").join(relative);
869 std::fs::create_dir_all(target.parent().context("untracked recovery parent")?)?;
870 if std::fs::symlink_metadata(&source)?.file_type().is_symlink() {
871 bail!("untracked symlink requires manual recovery: {name}");
873 }
874 std::fs::copy(source, target)?;
875 }
876 std::fs::write(destination.join("complete"), "snapshot captured\n")?;
877 Ok(())
878}
879
880pub async fn rescue_commit(worktree: &Path, message: &str) -> Result<Rescue> {
886 if git(worktree, &["status", "--porcelain"]).await?.is_empty() {
887 return Ok(Rescue::default());
888 }
889 let untracked = nul_list(
890 worktree,
891 &["ls-files", "-z", "--others", "--exclude-standard"],
892 )
893 .await?;
894 let tracked = nul_list(worktree, &["ls-files", "-z"]).await?;
895 let withheld = stray_lockfiles(&untracked, &tracked);
896
897 git(worktree, &["add", "-A"]).await?;
898 if !withheld.is_empty() {
899 let mut args = vec!["reset", "-q", "--"];
900 args.extend(withheld.iter().map(|s| s.path.as_str()));
901 git(worktree, &args).await?;
902 }
903 crate::worktree_setup::unstage_products(worktree).await?;
904 if git_raw(worktree, &["diff", "--cached", "--quiet"])
905 .await?
906 .ok()
907 {
908 return Ok(Rescue {
909 committed: false,
910 withheld,
911 });
912 }
913 let out = git_raw(
914 worktree,
915 &[
916 "-c",
917 "user.name=magi candidate",
918 "-c",
919 "user.email=magi@localhost",
920 "commit",
921 "--no-verify",
922 "-m",
923 message,
924 ],
925 )
926 .await?;
927 if !out.ok() {
928 bail!("rescue commit failed: {}", out.stderr);
929 }
930 Ok(Rescue {
931 committed: true,
932 withheld,
933 })
934}
935
936pub async fn enable_worktree_config(repo: &Path) -> Result<bool> {
941 let out = git_raw(repo, &["config", "--get", "extensions.worktreeConfig"]).await?;
942 if out.ok() && out.stdout.trim() == "true" {
943 return Ok(false);
944 }
945 git(repo, &["config", "extensions.worktreeConfig", "true"]).await?;
946 Ok(true)
947}
948
949pub async fn disable_worktree_config(repo: &Path) -> Result<()> {
951 git_raw(repo, &["config", "--unset", "extensions.worktreeConfig"]).await?;
952 Ok(())
953}
954
955struct WorktreeConfigRef {
958 count: usize,
960 we_enabled: bool,
966}
967
968static WORKTREE_CONFIG: std::sync::LazyLock<
975 std::sync::Mutex<
976 std::collections::HashMap<PathBuf, std::sync::Arc<tokio::sync::Mutex<WorktreeConfigRef>>>,
977 >,
978> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
979
980fn worktree_config_slot(repo: &Path) -> std::sync::Arc<tokio::sync::Mutex<WorktreeConfigRef>> {
982 let mut map = WORKTREE_CONFIG
983 .lock()
984 .unwrap_or_else(std::sync::PoisonError::into_inner);
985 map.entry(repo.to_path_buf())
986 .or_insert_with(|| {
987 std::sync::Arc::new(tokio::sync::Mutex::new(WorktreeConfigRef {
988 count: 0,
989 we_enabled: false,
990 }))
991 })
992 .clone()
993}
994
995pub async fn acquire_worktree_config(repo: &Path) -> Result<()> {
1012 let slot = worktree_config_slot(repo);
1013 let mut entry = slot.lock().await;
1014 entry.count += 1;
1015 if entry.count == 1 {
1016 entry.we_enabled = enable_worktree_config(repo).await?;
1017 }
1018 Ok(())
1019}
1020
1021pub async fn release_worktree_config(repo: &Path) -> Result<()> {
1027 let slot = worktree_config_slot(repo);
1028 let mut entry = slot.lock().await;
1029 entry.count = entry.count.saturating_sub(1);
1030 if entry.count == 0 && entry.we_enabled {
1031 disable_worktree_config(repo).await?;
1032 entry.we_enabled = false;
1033 }
1034 Ok(())
1035}
1036
1037pub async fn set_worktree_hooks_path(worktree: &Path, hooks_dir: &Path) -> Result<()> {
1043 let dir = hooks_dir.to_string_lossy().replace('\\', "/");
1044 git(worktree, &["config", "--worktree", "core.hooksPath", &dir])
1045 .await
1046 .map(|_| ())
1047}
1048
1049pub async fn local_exclude(worktree: &Path, pattern: &str) -> Result<()> {
1051 let git_dir = git(worktree, &["rev-parse", "--git-path", "info/exclude"]).await?;
1052 let path = worktree.join(git_dir);
1053 if let Some(parent) = path.parent() {
1054 tokio::fs::create_dir_all(parent).await.ok();
1055 }
1056 let mut body = tokio::fs::read_to_string(&path).await.unwrap_or_default();
1057 if body.lines().any(|l| l.trim() == pattern) {
1058 return Ok(());
1059 }
1060 if !body.is_empty() && !body.ends_with('\n') {
1061 body.push('\n');
1062 }
1063 body.push_str(pattern);
1064 body.push('\n');
1065 tokio::fs::write(&path, body)
1066 .await
1067 .with_context(|| format!("write {}", path.display()))?;
1068 Ok(())
1069}
1070
1071pub async fn merge_no_ff(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
1077 git_raw(
1078 repo,
1079 &["merge", "--no-ff", "--no-edit", "-m", message, branch],
1080 )
1081 .await
1082}
1083
1084pub async fn merge_squash(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
1095 let staged = git_raw(repo, &["merge", "--squash", branch]).await?;
1096 if !staged.ok() {
1097 return Ok(staged);
1098 }
1099 git_raw(repo, &["commit", "-m", message]).await
1100}
1101
1102pub async fn merge_ff_only(repo: &Path, branch: &str) -> Result<GitOut> {
1112 git_raw(repo, &["merge", "--ff-only", branch]).await
1113}
1114
1115pub async fn push(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
1117 git_raw(repo, &["push", "-u", remote, branch]).await
1118}
1119
1120pub async fn push_as(
1123 repo: &Path,
1124 remote: &str,
1125 local: &str,
1126 head: &str,
1127 expected: &str,
1128) -> Result<GitOut> {
1129 let lease = format!("--force-with-lease=refs/heads/{head}:{expected}");
1130 let refspec = format!("refs/heads/{local}:refs/heads/{head}");
1131 git_raw(repo, &["push", &lease, remote, &refspec]).await
1132}
1133
1134pub async fn remote_head(repo: &Path, remote: &str, branch: &str) -> Result<Option<String>> {
1136 let reference = format!("refs/heads/{branch}");
1137 let out = git(repo, &["ls-remote", "--refs", remote, &reference]).await?;
1138 Ok(out.split_whitespace().next().map(str::to_owned))
1139}
1140
1141pub async fn push_rewritten(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
1149 git_raw(repo, &["push", "--force-with-lease", remote, branch]).await
1150}
1151
1152pub async fn push_pinned(
1161 repo: &Path,
1162 remote: &str,
1163 branch: &str,
1164 expected: &str,
1165) -> Result<GitOut> {
1166 let lease = format!("--force-with-lease=refs/heads/{branch}:{expected}");
1167 let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1168 git_raw(repo, &["push", &lease, remote, &refspec]).await
1169}
1170
1171pub async fn cherry(repo: &Path, upstream: &str, head: &str) -> Result<(Vec<String>, Vec<String>)> {
1174 let out = git(repo, &["cherry", upstream, head]).await?;
1175 let (mut unmatched, mut matched) = (Vec::new(), Vec::new());
1176 for line in out.lines() {
1177 if let Some(sha) = line.strip_prefix("+ ") {
1178 unmatched.push(sha.trim().to_owned());
1179 } else if let Some(sha) = line.strip_prefix("- ") {
1180 matched.push(sha.trim().to_owned());
1181 }
1182 }
1183 Ok((unmatched, matched))
1184}
1185
1186#[derive(Debug)]
1188pub struct RebaseRecord {
1189 pub picks: Vec<String>,
1191 pub heads: Vec<String>,
1193}
1194
1195const REBASE_EXEC: &str = "git rev-parse HEAD >> \"$(git rev-parse --git-path magi-rebase-heads)\"";
1196
1197async fn rebase_file(scratch: &Path, name: &str) -> Result<PathBuf> {
1198 let path = git(scratch, &["rev-parse", "--git-path", name]).await?;
1199 let path = Path::new(path.trim());
1200 Ok(if path.is_absolute() {
1201 path.to_path_buf()
1202 } else {
1203 scratch.join(path)
1204 })
1205}
1206
1207async fn full_commit(scratch: &Path, sha: &str) -> Result<String> {
1208 anyhow::ensure!(
1209 !sha.is_empty() && sha.bytes().all(|b| b.is_ascii_hexdigit()),
1210 "invalid rebase commit id: {sha}"
1211 );
1212 rev_parse(scratch, &format!("{sha}^{{commit}}")).await
1213}
1214
1215async fn save_rebase_picks(scratch: &Path) -> Result<()> {
1218 let mut picks = Vec::new();
1219 for name in ["rebase-merge/done", "rebase-merge/git-rebase-todo"] {
1220 let text = std::fs::read_to_string(rebase_file(scratch, name).await?)?;
1221 for line in text.lines().map(str::trim) {
1222 if line.is_empty() || line.starts_with('#') {
1223 continue;
1224 }
1225 let mut words = line.split_whitespace();
1226 match words.next() {
1227 Some("pick" | "p") => {
1228 picks.push(
1229 full_commit(scratch, words.next().context("pick without commit")?).await?,
1230 );
1231 }
1232 Some("exec" | "x")
1233 if line
1234 .split_once(' ')
1235 .is_some_and(|(_, cmd)| cmd == REBASE_EXEC) => {}
1236 _ => bail!("unexpected rebase instruction: {line}"),
1237 }
1238 }
1239 }
1240 let path = rebase_file(scratch, "magi-rebase-picks").await?;
1241 let tmp = path.with_extension("tmp");
1242 std::fs::write(&tmp, picks.join("\n") + "\n")?;
1243 std::fs::rename(tmp, path)?;
1244 Ok(())
1245}
1246
1247pub async fn rebase_record(scratch: &Path) -> Result<RebaseRecord> {
1249 let mut lists = Vec::new();
1250 for name in ["magi-rebase-picks", "magi-rebase-heads"] {
1251 let text = std::fs::read_to_string(rebase_file(scratch, name).await?)
1252 .with_context(|| format!("read {name}"))?;
1253 let mut commits = Vec::new();
1254 for sha in text.lines() {
1255 let full = full_commit(scratch, sha).await?;
1256 anyhow::ensure!(full == sha, "non-full commit id in {name}");
1257 commits.push(full);
1258 }
1259 lists.push(commits);
1260 }
1261 let heads = lists.pop().unwrap();
1262 let picks = lists.pop().unwrap();
1263 anyhow::ensure!(
1264 !picks.is_empty() && picks.len() == heads.len(),
1265 "rebase pick/HEAD count mismatch"
1266 );
1267 Ok(RebaseRecord { picks, heads })
1268}
1269
1270pub fn rebase_said(text: &str) -> String {
1272 text.trim()
1273 .split(['\r', '\n'])
1274 .filter(|line| !line.trim_start().starts_with("Executing:"))
1275 .collect::<Vec<_>>()
1276 .join("\n")
1277}
1278
1279#[derive(Debug, Clone, PartialEq, Eq)]
1281pub enum RebaseStart {
1282 Applied,
1285 Conflicted(String),
1288 Failed(String),
1291}
1292
1293pub async fn rebase_start(
1308 repo: &Path,
1309 scratch: &Path,
1310 branch: &str,
1311 onto: &str,
1312) -> Result<RebaseStart> {
1313 rebase_prepare(repo, scratch, branch).await?;
1314 rebase_execute(repo, scratch, onto).await
1315}
1316
1317#[derive(Debug)]
1319pub struct RebasePreparationError(pub String);
1320
1321impl std::fmt::Display for RebasePreparationError {
1322 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1323 f.write_str(&self.0)
1324 }
1325}
1326
1327impl std::error::Error for RebasePreparationError {}
1328
1329pub(crate) async fn rebase_prepare(repo: &Path, scratch: &Path, branch: &str) -> Result<()> {
1332 if rebase_in_progress(scratch).await {
1333 return Ok(());
1334 }
1335 let result = async {
1336 worktree_remove(repo, scratch).await.ok();
1337 let path = path_arg(scratch);
1338 let args = ["worktree", "add", "--force", &path, branch];
1339 let out = git_raw(repo, &args).await?;
1340 ensure!(
1341 out.ok(),
1342 "git {} (exit {:?}): {}",
1343 args.join(" "),
1344 out.code,
1345 if out.stderr.trim().is_empty() {
1346 &out.stdout
1347 } else {
1348 &out.stderr
1349 }
1350 );
1351 std::fs::write(rebase_file(scratch, "magi-rebase-heads").await?, "")?;
1352 Ok::<_, anyhow::Error>(())
1353 }
1354 .await;
1355 result.map_err(|e| {
1356 RebasePreparationError(format!(
1357 "prepare rebase scratch {}: {e:#}",
1358 scratch.display()
1359 ))
1360 .into()
1361 })
1362}
1363
1364pub(crate) async fn rebase_execute(repo: &Path, scratch: &Path, onto: &str) -> Result<RebaseStart> {
1366 let out = git_raw(
1367 scratch,
1368 &["rebase", "--empty=drop", "--exec", REBASE_EXEC, onto],
1369 )
1370 .await?;
1371 if out.ok() {
1372 worktree_remove(repo, scratch).await.ok();
1373 return Ok(RebaseStart::Applied);
1374 }
1375 let why = rebase_said(&if out.stderr.trim().is_empty() {
1376 out.stdout.trim().to_owned()
1377 } else {
1378 out.stderr.trim().to_owned()
1379 });
1380 if rebase_in_progress(scratch).await {
1381 if let Err(error) = save_rebase_picks(scratch).await {
1382 rebase_abort(repo, scratch).await;
1383 return Ok(RebaseStart::Failed(format!(
1384 "cannot record rebase picks: {error:#}"
1385 )));
1386 }
1387 return Ok(RebaseStart::Conflicted(why));
1388 }
1389 worktree_remove(repo, scratch).await.ok();
1390 Ok(RebaseStart::Failed(why))
1391}
1392
1393pub async fn rebase_in_progress(worktree: &Path) -> bool {
1395 for name in ["rebase-merge", "rebase-apply"] {
1396 let Ok(p) = git(worktree, &["rev-parse", "--git-path", name]).await else {
1397 continue;
1398 };
1399 let p = Path::new(p.trim());
1400 let full = if p.is_absolute() {
1401 p.to_path_buf()
1402 } else {
1403 worktree.join(p)
1404 };
1405 if full.exists() {
1406 return true;
1407 }
1408 }
1409 false
1410}
1411
1412pub async fn unmerged_paths(worktree: &Path) -> Result<Vec<String>> {
1414 let out = git(worktree, &["diff", "--name-only", "--diff-filter=U", "-z"]).await?;
1415 Ok(out
1416 .split('\0')
1417 .filter(|l| !l.is_empty())
1418 .map(str::to_owned)
1419 .collect())
1420}
1421
1422pub async fn rebase_abort(repo: &Path, scratch: &Path) {
1425 git_raw(scratch, &["rebase", "--abort"]).await.ok();
1426 worktree_remove(repo, scratch).await.ok();
1427}
1428
1429pub async fn rebase_branch_in_temp(
1437 repo: &Path,
1438 scratch: &Path,
1439 branch: &str,
1440 onto: &str,
1441) -> Result<Option<String>> {
1442 match rebase_start(repo, scratch, branch, onto).await? {
1443 RebaseStart::Applied => Ok(None),
1444 RebaseStart::Failed(why) => Ok(Some(why)),
1445 RebaseStart::Conflicted(why) => {
1446 rebase_abort(repo, scratch).await;
1447 Ok(Some(why))
1448 }
1449 }
1450}
1451
1452pub async fn sync_to_head(worktree: &Path) -> Result<()> {
1465 reset_hard_head(worktree).await?;
1466 clean_all(worktree).await
1467}
1468
1469pub async fn reset_hard_head(worktree: &Path) -> Result<()> {
1471 git(worktree, &["reset", "--hard", "HEAD"])
1472 .await
1473 .map(|_| ())
1474}
1475
1476pub async fn clean_all(worktree: &Path) -> Result<()> {
1478 git(worktree, &["clean", "-fdx"]).await.map(|_| ())
1479}
1480
1481pub async fn fetch(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
1500 let refspec = format!("+refs/heads/{branch}:refs/remotes/{remote}/{branch}");
1501 git_raw(repo, &["fetch", "--quiet", remote, &refspec]).await
1502}
1503
1504pub async fn merge_base(repo: &Path, a: &str, b: &str) -> Result<String> {
1506 Ok(git(repo, &["merge-base", a, b]).await?.trim().to_owned())
1507}
1508
1509pub async fn is_ancestor(repo: &Path, ancestor: &str, of: &str) -> bool {
1511 git_raw(repo, &["merge-base", "--is-ancestor", ancestor, of])
1512 .await
1513 .is_ok_and(|o| o.ok())
1514}
1515
1516pub async fn ancestry(repo: &Path, ancestor: &str, of: &str) -> Result<bool> {
1521 let out = git_raw(repo, &["merge-base", "--is-ancestor", ancestor, of]).await?;
1522 match out.code {
1523 Some(0) => Ok(true),
1524 Some(1) => Ok(false),
1525 _ => bail!(
1526 "git merge-base --is-ancestor {ancestor} {of} failed ({}): {}",
1527 crate::notices::exit_status(out.code),
1528 out.stderr
1529 ),
1530 }
1531}
1532
1533pub async fn commit_of(repo: &Path, rev: &str) -> Option<String> {
1535 let spec = format!("{rev}^{{commit}}");
1536 let out = git_raw(repo, &["rev-parse", "--verify", "--quiet", &spec])
1537 .await
1538 .ok()?;
1539 (out.ok() && !out.stdout.is_empty()).then_some(out.stdout)
1540}
1541
1542pub async fn branches_containing(repo: &Path, commit: &str) -> Result<Vec<String>> {
1544 let out = git(
1545 repo,
1546 &[
1547 "branch",
1548 "-a",
1549 "--contains",
1550 commit,
1551 "--format=%(refname:short)",
1552 ],
1553 )
1554 .await?;
1555 Ok(out
1556 .lines()
1557 .map(str::trim)
1558 .filter(|l| !l.is_empty() && !l.ends_with("/HEAD") && !l.contains("HEAD detached"))
1559 .map(str::to_owned)
1560 .collect())
1561}
1562
1563pub async fn cherry_pick(worktree: &Path, commit: &str) -> Result<()> {
1567 let out = git_raw(
1568 worktree,
1569 &[
1570 "-c",
1571 "user.name=magi candidate",
1572 "-c",
1573 "user.email=magi@localhost",
1574 "cherry-pick",
1575 "-x",
1576 commit,
1577 ],
1578 )
1579 .await?;
1580 if out.ok() {
1581 return Ok(());
1582 }
1583 let _ = git_raw(worktree, &["cherry-pick", "--abort"]).await;
1584 bail!(
1585 "cherry-pick of {commit} failed: {}",
1586 if out.stderr.is_empty() {
1587 out.stdout
1588 } else {
1589 out.stderr
1590 }
1591 )
1592}
1593
1594pub async fn tree_of(repo: &Path, rev: &str) -> Result<String> {
1596 git(repo, &["rev-parse", &format!("{rev}^{{tree}}")]).await
1597}
1598
1599pub async fn rev_exists(repo: &Path, rev: &str) -> bool {
1601 git_raw(repo, &["rev-parse", "--verify", "--quiet", rev])
1602 .await
1603 .is_ok_and(|o| o.ok())
1604}
1605
1606#[cfg(test)]
1607mod tests {
1608 #[tokio::test]
1609 async fn checkout_discovery_ignores_inherited_git_target() {
1610 const FIXTURE: &str = "MAGI_TEST_CHECKOUT_DISCOVERY_ROOT";
1611 if let Some(root) = std::env::var_os(FIXTURE) {
1612 let root = std::path::PathBuf::from(root);
1613 let first = root.join("first");
1614 let second = root.join("second");
1615 let plain = root.join("plain");
1616 assert_eq!(
1617 super::toplevel(&second)
1618 .await
1619 .unwrap()
1620 .canonicalize()
1621 .unwrap(),
1622 second.canonicalize().unwrap()
1623 );
1624 assert!(super::toplevel(&plain).await.is_err());
1625 assert!(!super::same_checkout(&first, &second).unwrap());
1626 assert!(super::same_checkout(&first, &plain).is_err());
1627 assert!(super::same_checkout(&first, &first.join("src")).unwrap());
1628 return;
1629 }
1630 let fixture = tempfile::tempdir().unwrap();
1631 let root = fixture.path();
1632 for name in ["first", "second"] {
1633 let checkout = root.join(name);
1634 std::fs::create_dir_all(checkout.join("src")).unwrap();
1635 super::git(&checkout, &["init", "-q"]).await.unwrap();
1636 }
1637 std::fs::create_dir(root.join("plain")).unwrap();
1638 let output = std::process::Command::new(std::env::current_exe().unwrap())
1639 .args([
1640 "--exact",
1641 "git::tests::checkout_discovery_ignores_inherited_git_target",
1642 ])
1643 .env(FIXTURE, root)
1644 .env("GIT_DIR", root.join("first/.git"))
1645 .env("GIT_WORK_TREE", root.join("first"))
1646 .env("GIT_CONFIG_COUNT", "1")
1647 .env("GIT_CONFIG_KEY_0", "core.worktree")
1648 .env("GIT_CONFIG_VALUE_0", root.join("first"))
1649 .output()
1650 .unwrap();
1651 let stdout = String::from_utf8_lossy(&output.stdout);
1652 assert!(
1653 output.status.success() && stdout.contains("1 passed"),
1654 "{stdout}"
1655 );
1656 }
1657
1658 #[test]
1659 fn git_cli_path_spelling_handles_windows_canonical_prefixes() {
1660 for (native, expected) in [
1661 (r"\\?\C:\temp\work tree", "C:/temp/work tree"),
1662 (
1663 r"\\?\UNC\server\share\work tree",
1664 "//server/share/work tree",
1665 ),
1666 (r"C:\temp\work tree", "C:/temp/work tree"),
1667 ("C:/temp/work tree", "C:/temp/work tree"),
1668 ] {
1669 assert_eq!(super::windows_cli_path(native), expected);
1670 }
1671 }
1672
1673 #[test]
1674 fn git_cli_path_spelling_does_not_alias_extended_only_names() {
1675 for path in [
1676 r"\\?\C:\temp.\copy",
1677 r"\\?\C:\temp \copy",
1678 r"\\?\C:\NUL.txt\copy",
1679 r"\\?\C:\COM1\copy",
1680 ] {
1681 assert!(super::windows_cli_path(path).starts_with("//?/"));
1682 }
1683 }
1684
1685 #[cfg(unix)]
1686 #[test]
1687 fn git_cli_path_spelling_preserves_native_paths_on_unix() {
1688 assert_eq!(
1689 super::path_arg(std::path::Path::new(r"/tmp/back\slash")),
1690 r"/tmp/back\slash"
1691 );
1692 }
1693
1694 #[test]
1695 fn git_cli_canonical_output_accepts_platform_spelling_and_rejects_aliases() {
1696 let temp = tempfile::tempdir().unwrap();
1697 let canonical = temp.path().canonicalize().unwrap();
1698 let printed = super::path_arg(&canonical);
1699 assert_eq!(super::canonical_output_path(&printed).unwrap(), canonical);
1700 let noncanonical = format!("{printed}/child/..");
1703 std::fs::create_dir(canonical.join("child")).unwrap();
1704 assert!(super::canonical_output_path(&noncanonical).is_err());
1705 #[cfg(unix)]
1706 {
1707 let alias = canonical.join("alias");
1708 std::os::unix::fs::symlink(canonical.join("child"), &alias).unwrap();
1709 assert!(super::canonical_output_path(alias.to_str().unwrap()).is_err());
1710 }
1711 }
1712
1713 use super::*;
1714
1715 #[test]
1716 fn worktree_holder_is_read_from_the_porcelain_listing() {
1717 let listing = "worktree /repo\nHEAD aaa\nbranch refs/heads/main\n\n\
1718 worktree /wt/cand-A\nHEAD bbb\nbranch refs/heads/magi/f82f/A\n\n\
1719 worktree /wt/detached\nHEAD ccc\ndetached\n";
1720 assert_eq!(
1721 parse_worktree_holder(listing, "magi/f82f/A"),
1722 Some(PathBuf::from("/wt/cand-A"))
1723 );
1724 assert_eq!(parse_worktree_holder(listing, "magi/f82f"), None);
1725 assert_eq!(parse_worktree_holder(listing, "other"), None);
1726 }
1727
1728 async fn scratch() -> (tempfile::TempDir, PathBuf) {
1729 let dir = tempfile::tempdir().unwrap();
1730 let repo = dir.path().join("repo");
1731 tokio::fs::create_dir_all(&repo).await.unwrap();
1732 git(&repo, &["init", "-b", "main"]).await.unwrap();
1733 git(&repo, &["config", "user.name", "test"]).await.unwrap();
1734 git(&repo, &["config", "user.email", "test@example.com"])
1735 .await
1736 .unwrap();
1737 tokio::fs::write(repo.join("a.txt"), "one\n").await.unwrap();
1738 git(&repo, &["add", "-A"]).await.unwrap();
1739 git(&repo, &["commit", "-m", "init"]).await.unwrap();
1740 (dir, repo)
1741 }
1742
1743 #[tokio::test]
1744 async fn restore_to_removes_nested_repositories_inside_submodules() {
1745 let (_parent_dir, repo) = scratch().await;
1746 let (_source_dir, source) = scratch().await;
1747 sh(
1748 &repo,
1749 &[
1750 "-c",
1751 "protocol.file.allow=always",
1752 "submodule",
1753 "add",
1754 &source.to_string_lossy(),
1755 "sub",
1756 ],
1757 );
1758 sh(&repo, &["commit", "-am", "add submodule"]);
1759 let pre = rev_parse(&repo, "HEAD").await.unwrap();
1760 let sub = repo.join("sub");
1761 sh(&sub, &["init", "nested"]);
1762 tokio::fs::write(sub.join("nested/rejected.txt"), "rejected\n")
1763 .await
1764 .unwrap();
1765
1766 restore_to(&repo, &pre).await.unwrap();
1767
1768 assert!(!sub.join("nested").exists());
1769 assert_eq!(rev_parse(&repo, "HEAD").await.unwrap(), pre);
1770 assert_eq!(
1771 rev_parse(&sub, "HEAD").await.unwrap(),
1772 rev_parse(&source, "HEAD").await.unwrap()
1773 );
1774 assert!(
1775 git(&repo, &["status", "--porcelain"])
1776 .await
1777 .unwrap()
1778 .is_empty()
1779 );
1780 }
1781
1782 #[tokio::test]
1783 async fn a_branch_rebases_onto_a_moved_base_and_says_when_it_cannot() {
1784 let (_g, repo) = scratch().await;
1785
1786 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1788 tokio::fs::write(repo.join("b.txt"), "side\n")
1789 .await
1790 .unwrap();
1791 git(&repo, &["add", "-A"]).await.unwrap();
1792 git(&repo, &["commit", "-m", "side work"]).await.unwrap();
1793
1794 git(&repo, &["checkout", "main"]).await.unwrap();
1797 tokio::fs::write(repo.join("c.txt"), "main\n")
1798 .await
1799 .unwrap();
1800 git(&repo, &["add", "-A"]).await.unwrap();
1801 git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
1802
1803 let scratch_tree = repo.parent().unwrap().join("rebase-scratch");
1804 let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
1805 .await
1806 .unwrap();
1807 assert!(clean.is_none(), "a disjoint change rebases: {clean:?}");
1808 assert_eq!(
1809 commits_ahead(&repo, "main", "side").await.unwrap(),
1810 1,
1811 "one commit, replayed onto the new base"
1812 );
1813 assert!(
1814 !scratch_tree.exists(),
1815 "the throwaway worktree is not left behind"
1816 );
1817
1818 git(&repo, &["checkout", "-b", "clash"]).await.unwrap();
1820 tokio::fs::write(repo.join("a.txt"), "clash\n")
1821 .await
1822 .unwrap();
1823 git(&repo, &["add", "-A"]).await.unwrap();
1824 git(&repo, &["commit", "-m", "clash"]).await.unwrap();
1825 git(&repo, &["checkout", "main"]).await.unwrap();
1826 tokio::fs::write(repo.join("a.txt"), "main edit\n")
1827 .await
1828 .unwrap();
1829 git(&repo, &["add", "-A"]).await.unwrap();
1830 git(&repo, &["commit", "-m", "main edit"]).await.unwrap();
1831
1832 let before = rev_parse(&repo, "clash").await.unwrap();
1833 let why = rebase_branch_in_temp(&repo, &scratch_tree, "clash", "main")
1834 .await
1835 .unwrap()
1836 .expect("a same-line clash cannot be rebased silently");
1837 assert!(
1838 why.to_lowercase().contains("conflict"),
1839 "the reason is what git said, which is what a person needs: {why}"
1840 );
1841 assert_eq!(
1842 rev_parse(&repo, "clash").await.unwrap(),
1843 before,
1844 "a failed rebase leaves the branch exactly where it was"
1845 );
1846 assert!(!scratch_tree.exists(), "and cleans up after itself");
1847 }
1848
1849 #[tokio::test]
1850 async fn merge_squash_folds_the_branch_into_one_commit_under_the_given_message() {
1851 let (_g, repo) = scratch().await;
1852 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1853 for name in ["b.txt", "c.txt"] {
1854 tokio::fs::write(repo.join(name), "side\n").await.unwrap();
1855 git(&repo, &["add", "-A"]).await.unwrap();
1856 git(
1857 &repo,
1858 &["commit", "-m", "magi: candidate A (uncommitted work)"],
1859 )
1860 .await
1861 .unwrap();
1862 }
1863 git(&repo, &["checkout", "main"]).await.unwrap();
1864 let before = rev_parse(&repo, "main").await.unwrap();
1865
1866 let out = merge_squash(&repo, "side", "an explicit subject")
1867 .await
1868 .unwrap();
1869 assert!(out.ok(), "{}", out.stderr);
1870 assert_eq!(
1871 commits_ahead(&repo, &before, "main").await.unwrap(),
1872 1,
1873 "squash adds exactly one commit onto the tip, not one per candidate commit"
1874 );
1875 let subject = git(&repo, &["log", "-1", "--format=%s"]).await.unwrap();
1876 assert_eq!(
1877 subject, "an explicit subject",
1878 "the candidate's own placeholder subject must not survive: {subject}"
1879 );
1880 }
1881
1882 #[tokio::test]
1883 async fn merge_ff_only_fast_forwards_a_branch_already_rebased_onto_the_tip() {
1884 let (_g, repo) = scratch().await;
1885 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1886 tokio::fs::write(repo.join("b.txt"), "side\n")
1887 .await
1888 .unwrap();
1889 git(&repo, &["add", "-A"]).await.unwrap();
1890 git(&repo, &["commit", "-m", "side work"]).await.unwrap();
1891 git(&repo, &["checkout", "main"]).await.unwrap();
1892
1893 let before = rev_parse(&repo, "side").await.unwrap();
1894 let out = merge_ff_only(&repo, "side").await.unwrap();
1895 assert!(out.ok(), "{}", out.stderr);
1896 assert_eq!(
1897 rev_parse(&repo, "main").await.unwrap(),
1898 before,
1899 "a fast-forward moves the base tip to the branch, no merge commit"
1900 );
1901 }
1902
1903 #[tokio::test]
1904 async fn merge_ff_only_refuses_to_write_a_merge_commit() {
1905 let (_g, repo) = scratch().await;
1906 git(&repo, &["checkout", "-b", "side"]).await.unwrap();
1907 tokio::fs::write(repo.join("b.txt"), "side\n")
1908 .await
1909 .unwrap();
1910 git(&repo, &["add", "-A"]).await.unwrap();
1911 git(&repo, &["commit", "-m", "side work"]).await.unwrap();
1912
1913 git(&repo, &["checkout", "main"]).await.unwrap();
1915 tokio::fs::write(repo.join("c.txt"), "main\n")
1916 .await
1917 .unwrap();
1918 git(&repo, &["add", "-A"]).await.unwrap();
1919 git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
1920
1921 let before = rev_parse(&repo, "main").await.unwrap();
1922 let out = merge_ff_only(&repo, "side").await.unwrap();
1923 assert!(!out.ok(), "a divergent branch cannot fast-forward");
1924 assert_eq!(
1925 rev_parse(&repo, "main").await.unwrap(),
1926 before,
1927 "a refused fast-forward must not touch main"
1928 );
1929 }
1930
1931 #[tokio::test]
1932 async fn a_sibling_worktree_stays_stale_after_a_rebase_until_synced() {
1933 let (guard, repo) = scratch().await;
1934
1935 git(&repo, &["branch", "side"]).await.unwrap();
1939 let side_wt = guard.path().join("side-wt");
1940 git(
1941 &repo,
1942 &["worktree", "add", &side_wt.to_string_lossy(), "side"],
1943 )
1944 .await
1945 .unwrap();
1946 tokio::fs::write(side_wt.join("b.txt"), "candidate\n")
1947 .await
1948 .unwrap();
1949 git(&side_wt, &["add", "-A"]).await.unwrap();
1950 git(&side_wt, &["commit", "-m", "side work"]).await.unwrap();
1951
1952 git(&repo, &["checkout", "main"]).await.unwrap();
1954 tokio::fs::write(repo.join("c.txt"), "main\n")
1955 .await
1956 .unwrap();
1957 git(&repo, &["add", "-A"]).await.unwrap();
1958 git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
1959
1960 let scratch_tree = guard.path().join("rebase-scratch");
1962 let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
1963 .await
1964 .unwrap();
1965 assert!(clean.is_none());
1966
1967 assert_eq!(
1971 rev_parse(&side_wt, "HEAD").await.unwrap(),
1972 rev_parse(&repo, "side").await.unwrap(),
1973 "HEAD follows the moved ref"
1974 );
1975 assert!(
1976 !side_wt.join("c.txt").exists(),
1977 "stale until synced: main's new file has not reached this worktree's disk"
1978 );
1979
1980 sync_to_head(&side_wt).await.unwrap();
1981 assert!(side_wt.join("c.txt").is_file(), "synced now");
1982 assert!(
1983 side_wt.join("b.txt").is_file(),
1984 "the worktree's own committed work survives the sync"
1985 );
1986 assert!(is_clean(&side_wt).await.unwrap());
1987 }
1988
1989 #[tokio::test]
1990 async fn clean_repo_reports_clean_then_dirty() {
1991 let (_g, repo) = scratch().await;
1992 assert!(is_clean(&repo).await.unwrap());
1993 tokio::fs::write(repo.join("a.txt"), "two\n").await.unwrap();
1994 assert!(!is_clean(&repo).await.unwrap());
1995 }
1996
1997 async fn track(repo: &Path, name: &str, body: &str) {
1998 let p = repo.join(name);
1999 if let Some(d) = p.parent() {
2000 tokio::fs::create_dir_all(d).await.unwrap();
2001 }
2002 tokio::fs::write(&p, body).await.unwrap();
2003 git(repo, &["add", name]).await.unwrap();
2004 git(
2005 repo,
2006 &[
2007 "-c",
2008 "user.name=t",
2009 "-c",
2010 "user.email=t@localhost",
2011 "commit",
2012 "-q",
2013 "-m",
2014 "seed",
2015 ],
2016 )
2017 .await
2018 .unwrap();
2019 }
2020
2021 #[tokio::test]
2022 async fn rescue_withholds_a_foreign_lockfile() {
2023 let (_g, repo) = scratch().await;
2024 track(&repo, "web/bun.lock", "a\n").await;
2025 tokio::fs::write(repo.join("web/pnpm-lock.yaml"), "x\n")
2026 .await
2027 .unwrap();
2028 tokio::fs::write(repo.join("web/app.ts"), "real\n")
2029 .await
2030 .unwrap();
2031
2032 let r = rescue_commit(&repo, "rescue").await.unwrap();
2033 assert!(r.committed);
2034 assert_eq!(
2035 r.withheld,
2036 [Stray {
2037 path: "web/pnpm-lock.yaml".to_owned(),
2038 manager: "pnpm".to_owned(),
2039 kept_by: "web/bun.lock".to_owned(),
2040 }]
2041 );
2042 let files = git(&repo, &["show", "--name-only", "--format=", "HEAD"])
2043 .await
2044 .unwrap();
2045 assert!(files.contains("web/app.ts"), "{files}");
2046 assert!(!files.contains("pnpm-lock"), "{files}");
2047 assert!(repo.join("web/pnpm-lock.yaml").is_file(), "not deleted");
2048 }
2049
2050 #[tokio::test]
2051 async fn rescue_with_only_a_stray_commits_nothing() {
2052 let (_g, repo) = scratch().await;
2053 track(&repo, "bun.lock", "a\n").await;
2054 tokio::fs::write(repo.join("yarn.lock"), "x\n")
2055 .await
2056 .unwrap();
2057 let r = rescue_commit(&repo, "rescue").await.unwrap();
2058 assert!(!r.committed);
2059 assert_eq!(r.withheld.len(), 1);
2060 }
2061
2062 #[tokio::test]
2063 async fn rescue_keeps_a_same_manager_lockfile_update() {
2064 let (_g, repo) = scratch().await;
2065 track(&repo, "bun.lock", "a\n").await;
2066 tokio::fs::write(repo.join("bun.lock"), "b\n")
2067 .await
2068 .unwrap();
2069 let r = rescue_commit(&repo, "rescue").await.unwrap();
2070 assert!(r.committed);
2071 assert!(r.withheld.is_empty());
2072 let files = git(&repo, &["show", "--name-only", "--format=", "HEAD"])
2073 .await
2074 .unwrap();
2075 assert_eq!(files, "bun.lock");
2076 }
2077
2078 #[tokio::test]
2079 async fn rescue_keeps_the_first_lockfile_in_a_bare_directory() {
2080 let (_g, repo) = scratch().await;
2081 track(&repo, "other/bun.lock", "a\n").await;
2082 tokio::fs::create_dir_all(repo.join("web")).await.unwrap();
2083 tokio::fs::write(repo.join("web/package-lock.json"), "{}\n")
2084 .await
2085 .unwrap();
2086 let r = rescue_commit(&repo, "rescue").await.unwrap();
2087 assert!(r.committed);
2088 assert!(r.withheld.is_empty());
2089 }
2090
2091 #[test]
2092 fn a_cargo_lock_is_foreign_only_without_a_cargo_toml() {
2093 let s = |v: &[&str]| v.iter().map(|x| (*x).to_owned()).collect::<Vec<_>>();
2094 assert_eq!(stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&[])).len(), 1);
2095 assert!(stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&["a/Cargo.toml"])).is_empty());
2096 assert!(stray_lockfiles(&s(&["a/Cargo.lock", "a/Cargo.toml"]), &s(&[])).is_empty());
2097 assert_eq!(
2099 stray_lockfiles(&s(&["a/Cargo.lock"]), &s(&["Cargo.toml"])).len(),
2100 1
2101 );
2102 }
2103
2104 #[tokio::test]
2105 async fn clean_removal_preserves_edits_while_scratch_removal_discards_them() {
2106 let (guard, repo) = scratch().await;
2107 let wt = guard.path().join("scratch-wt");
2108 worktree_add_detached(&repo, &wt, "HEAD").await.unwrap();
2109 tokio::fs::write(wt.join("built.txt"), "build output")
2110 .await
2111 .unwrap();
2112 assert!(!worktree_remove_clean(&repo, &wt).await.unwrap());
2113 assert!(wt.join("built.txt").exists());
2114 let listing = git(&repo, &["worktree", "list", "--porcelain"])
2115 .await
2116 .unwrap();
2117 let registered = listing
2118 .lines()
2119 .filter_map(|line| line.strip_prefix("worktree "))
2120 .map(PathBuf::from)
2121 .find(|path| path.canonicalize().unwrap() == wt.canonicalize().unwrap())
2122 .expect("the refused removal must retain the worktree registration");
2123 assert!(worktree_remove(&repo, &wt).await.unwrap());
2124 assert!(!wt.exists());
2125 let listing = git(&repo, &["worktree", "list", "--porcelain"])
2126 .await
2127 .unwrap();
2128 assert!(!listing.lines().any(|line| {
2129 line.strip_prefix("worktree ")
2130 .is_some_and(|path| Path::new(path) == registered)
2131 }));
2132 }
2133
2134 #[tokio::test]
2135 async fn worktree_lifecycle_and_diff() {
2136 let (guard, repo) = scratch().await;
2137 let base = rev_parse(&repo, "HEAD").await.unwrap();
2138 let wt = guard.path().join("wt-a");
2139 worktree_add_branch(&repo, &wt, "magi/test/a", &base)
2140 .await
2141 .unwrap();
2142 tokio::fs::write(wt.join("b.txt"), "candidate\n")
2143 .await
2144 .unwrap();
2145
2146 assert!(commit_all(&wt, "candidate work").await.unwrap());
2147 assert!(!commit_all(&wt, "nothing left").await.unwrap());
2148
2149 assert_eq!(commits_ahead(&wt, &base, "HEAD").await.unwrap(), 1);
2150 let patch = diff(&wt, &base, "HEAD").await.unwrap();
2151 assert!(patch.contains("b.txt"), "patch was: {patch}");
2152 assert_eq!(
2153 changed_files(&wt, &base, "HEAD").await.unwrap(),
2154 ["b.txt".to_owned()]
2155 );
2156
2157 let author = git(&wt, &["log", "-1", "--format=%an <%ae>"])
2159 .await
2160 .unwrap();
2161 assert_eq!(author, "magi candidate <magi@localhost>");
2162
2163 assert!(worktree_remove(&repo, &wt).await.unwrap());
2164 assert!(branch_exists(&repo, "magi/test/a").await.unwrap());
2165 assert!(branch_delete(&repo, "magi/test/a").await.unwrap());
2166 assert!(!branch_exists(&repo, "magi/test/a").await.unwrap());
2167 }
2168
2169 #[tokio::test]
2170 async fn worktree_scoped_hooks_path_does_not_leak_to_primary() {
2171 let (guard, repo) = scratch().await;
2172 let base = rev_parse(&repo, "HEAD").await.unwrap();
2173 let wt = guard.path().join("wt-h");
2174 worktree_add_branch(&repo, &wt, "magi/test/h", &base)
2175 .await
2176 .unwrap();
2177 let hooks = guard.path().join("hooks");
2178 tokio::fs::create_dir_all(&hooks).await.unwrap();
2179
2180 assert!(enable_worktree_config(&repo).await.unwrap());
2181 set_worktree_hooks_path(&wt, &hooks).await.unwrap();
2182
2183 let in_wt = git(&wt, &["config", "--get", "core.hooksPath"])
2184 .await
2185 .unwrap();
2186 assert!(!in_wt.is_empty());
2187 let in_primary = git_raw(&repo, &["config", "--get", "core.hooksPath"])
2188 .await
2189 .unwrap();
2190 assert!(
2191 !in_primary.ok(),
2192 "primary worktree must keep its own hooks: {in_primary:?}"
2193 );
2194
2195 disable_worktree_config(&repo).await.unwrap();
2196 }
2197
2198 #[tokio::test]
2199 async fn worktree_config_stays_on_while_a_sibling_run_still_holds_it() {
2200 let (_g, repo) = scratch().await;
2201
2202 acquire_worktree_config(&repo).await.unwrap();
2205 acquire_worktree_config(&repo).await.unwrap();
2206
2207 let on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
2208 .await
2209 .unwrap();
2210 assert_eq!(on, "true");
2211
2212 release_worktree_config(&repo).await.unwrap();
2216 let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
2217 .await
2218 .unwrap();
2219 assert_eq!(
2220 still_on, "true",
2221 "a sibling run's release must not disable the setting for the one still working"
2222 );
2223
2224 release_worktree_config(&repo).await.unwrap();
2226 let after = git_raw(&repo, &["config", "--get", "extensions.worktreeConfig"])
2227 .await
2228 .unwrap();
2229 assert!(
2230 !after.ok(),
2231 "the last release must turn the setting back off: {after:?}"
2232 );
2233 }
2234
2235 #[tokio::test]
2236 async fn worktree_config_already_on_before_magi_touched_it_is_left_alone() {
2237 let (_g, repo) = scratch().await;
2238 git(&repo, &["config", "extensions.worktreeConfig", "true"])
2239 .await
2240 .unwrap();
2241
2242 acquire_worktree_config(&repo).await.unwrap();
2247 release_worktree_config(&repo).await.unwrap();
2248
2249 let still_on = git(&repo, &["config", "--get", "extensions.worktreeConfig"])
2250 .await
2251 .unwrap();
2252 assert_eq!(still_on, "true");
2253 }
2254
2255 #[tokio::test]
2256 async fn local_exclude_is_idempotent() {
2257 let (_g, repo) = scratch().await;
2258 local_exclude(&repo, "/.magi/").await.unwrap();
2259 local_exclude(&repo, "/.magi/").await.unwrap();
2260 let path = repo.join(".git/info/exclude");
2261 let body = tokio::fs::read_to_string(&path).await.unwrap();
2262 assert_eq!(body.matches("/.magi/").count(), 1);
2263 }
2264
2265 fn sh(cwd: &Path, args: &[&str]) {
2266 let out = std::process::Command::new("git")
2267 .quiet()
2268 .args(args)
2269 .current_dir(cwd)
2270 .output()
2271 .unwrap();
2272 assert!(
2273 out.status.success(),
2274 "git {args:?}: {}",
2275 String::from_utf8_lossy(&out.stderr)
2276 );
2277 }
2278
2279 async fn with_remote() -> (tempfile::TempDir, PathBuf) {
2282 let (g, repo) = scratch().await;
2283 let bare = g.path().join("bare.git");
2284 sh(g.path(), &["init", "--bare", "-b", "trunk", "bare.git"]);
2285 sh(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
2286 sh(&repo, &["push", "origin", "HEAD:refs/heads/trunk"]);
2287 sh(&repo, &["fetch", "origin"]);
2288 (g, repo)
2289 }
2290
2291 #[test]
2292 fn remote_head_branch_strips_only_the_matching_remote() {
2293 assert_eq!(
2294 remote_head_branch("origin", "refs/remotes/origin/main\n").as_deref(),
2295 Some("main")
2296 );
2297 assert_eq!(remote_head_branch("up", "refs/remotes/origin/main"), None);
2298 assert_eq!(remote_head_branch("origin", "refs/remotes/origin/"), None);
2299 }
2300
2301 #[tokio::test]
2302 async fn merge_base_branch_reads_origin_head_when_present() {
2303 let (_g, repo) = with_remote().await;
2304 sh(&repo, &["remote", "set-head", "origin", "trunk"]);
2305 assert_eq!(
2306 merge_base_branch(&repo, "origin", None).await.unwrap(),
2307 "trunk"
2308 );
2309 }
2310
2311 #[tokio::test]
2312 async fn merge_base_branch_recovers_a_missing_origin_head() {
2313 let (_g, repo) = with_remote().await;
2314 sh(&repo, &["remote", "set-head", "origin", "-d"]);
2316 let head = git_raw(
2317 &repo,
2318 &["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"],
2319 )
2320 .await
2321 .unwrap();
2322 assert!(!head.ok(), "precondition: no origin/HEAD");
2323 assert_eq!(
2324 merge_base_branch(&repo, "origin", None).await.unwrap(),
2325 "trunk"
2326 );
2327 }
2328
2329 #[tokio::test]
2330 async fn merge_base_branch_errors_without_a_remote_and_never_uses_head() {
2331 let (_g, repo) = scratch().await;
2332 let err = merge_base_branch(&repo, "origin", None).await.unwrap_err();
2333 assert!(format!("{err:#}").contains("[merge] base"), "{err:#}");
2334 }
2335
2336 #[tokio::test]
2337 async fn merge_base_branch_prefers_the_explicit_base() {
2338 let (_g, repo) = with_remote().await;
2339 assert_eq!(
2340 merge_base_branch(&repo, "origin", Some("release"))
2341 .await
2342 .unwrap(),
2343 "release"
2344 );
2345 }
2346
2347 #[tokio::test]
2348 async fn merge_base_branch_names_an_unfetched_default_branch() {
2349 let (g, repo) = scratch().await;
2352 let bare = g.path().join("bare.git");
2353 sh(g.path(), &["init", "--bare", "-b", "trunk", "bare.git"]);
2354 sh(
2355 &repo,
2356 &["push", &bare.to_string_lossy(), "HEAD:refs/heads/trunk"],
2357 );
2358 sh(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
2359 assert!(!rev_exists(&repo, "refs/remotes/origin/trunk").await);
2360 assert_eq!(
2361 merge_base_branch(&repo, "origin", None).await.unwrap(),
2362 "trunk"
2363 );
2364 }
2365
2366 #[test]
2367 fn symref_branch_reads_ls_remote_output() {
2368 assert_eq!(
2369 symref_branch("ref: refs/heads/main\tHEAD\nabc\tHEAD\n").as_deref(),
2370 Some("main")
2371 );
2372 assert_eq!(symref_branch("abc\tHEAD\n"), None);
2373 }
2374}