From 39ab3cde1a94999e9a83f0eced89fff5161ce87a Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 16 Nov 2026 17:07:30 +0100 Subject: [PATCH] feat(migrate): support repos with linked worktrees Nested ones move with the checkout, outside ones stay; link files are rewritten, backed up and restored on rollback. Locked, prunable and mid-operation linked worktrees are refused. Co-Authored-By: Claude Sonnet 5.5 --- crates/grove-core/src/migrate.rs | 339 ++++++++++++++++++++++++++--- crates/grove-core/tests/migrate.rs | 210 +++++++++++++++++- 2 files changed, 502 insertions(+), 47 deletions(-) diff --git a/crates/grove-core/src/migrate.rs b/crates/grove-core/src/migrate.rs index ce4ab0f..2c819d6 100644 --- a/crates/grove-core/src/migrate.rs +++ b/crates/grove-core/src/migrate.rs @@ -3,6 +3,11 @@ //! Safety: a full tar backup and a backup ref are taken first; the observable state //! (`status --ignored`, stashes, refs) is compared before and after; any failure after //! the first modification triggers a rollback to the original layout. +//! +//! Linked worktrees (`git worktree add`) are supported: the ones nested inside the repo move +//! together with the main checkout, the ones outside stay where they are, and the two link files +//! of each (`/.git` and `.bare/worktrees//gitdir`) are rewritten to the new locations. +//! Locked, missing/prunable and mid-operation linked worktrees are refused. use crate::git::{Git, GitError}; use crate::layout::dir_name; @@ -73,6 +78,41 @@ pub struct Report { pub branch: String, pub backup_tar: PathBuf, pub backup_ref: String, + /// Linked worktrees that existed before the migration (they were kept usable). + pub linked: Vec, + /// Extra tar backups, one per linked worktree outside the repo directory. + pub linked_backups: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LinkedReport { + /// Location before the migration. + pub old_path: PathBuf, + /// Location now (differs from `old_path` only for worktrees nested inside the repo). + pub path: PathBuf, + /// `None` for a detached HEAD. + pub branch: Option, +} + +/// A linked worktree found by the pre-flight, with what is needed to relink and roll back. +#[derive(Debug, Clone)] +struct Linked { + old_path: PathBuf, + branch: Option, + /// Directory name under `.git/worktrees/`. + id: String, + /// Original contents of `/.git` and `.git/worktrees//gitdir`. + orig_gitfile: String, + orig_gitdir: String, +} + +impl Linked { + fn new_path(&self, root: &Path, dir: &str) -> PathBuf { + match self.old_path.strip_prefix(root) { + Ok(rel) => root.join(dir).join(rel), + Err(_) => self.old_path.clone(), + } + } } /// Steps after which a failure can be injected (tests only). @@ -83,6 +123,7 @@ pub enum Step { GitMoved, WorktreeAdded, Filled, + Relinked, IndexMoved, Verified, } @@ -95,6 +136,10 @@ struct Progress { wt_meta: Option, filled: bool, index_moved: bool, + /// Link files of linked worktrees may have been rewritten. + relinking: bool, + /// Ids under `.git/worktrees/` before the migration; any other one is ours. + orig_ids: Vec, /// Original `core.worktree`, restored on rollback. orig_core_worktree: Option, } @@ -104,19 +149,33 @@ struct Observed { status: String, stash: String, refs: String, + /// Per linked worktree (same order as the pre-flight list): HEAD, branch, status. + linked: Vec, } -fn observe(git: &Git) -> Result { +fn observe(git: &Git, linked: &[PathBuf]) -> Result { let refs = git.run(&["for-each-ref", "--format=%(refname) %(objectname)"])?; let refs = refs .lines() .filter(|l| !l.starts_with("refs/sync-backup/")) .collect::>() .join("\n"); + let mut lk = Vec::new(); + for path in linked { + let g = Git::new(path); + lk.push(format!( + "{}\n{}\n{}", + g.run(&["rev-parse", "HEAD"])?, + g.probe(&["symbolic-ref", "-q", "HEAD"])? + .unwrap_or_default(), + g.run(&["status", "--porcelain", "--ignored"])? + )); + } Ok(Observed { status: git.run(&["status", "--porcelain", "--ignored"])?, stash: git.run(&["stash", "list", "--format=%H"])?, refs, + linked: lk, }) } @@ -149,7 +208,7 @@ fn refuse(m: impl Into) -> Result { Err(MigrateError::Refused(m.into())) } -fn preflight(root: &Path) -> Result { +fn preflight(root: &Path) -> Result<(String, Vec), MigrateError> { let dotgit = root.join(".git"); if root.join(BARE).exists() { return refuse("already migrated (.bare exists)"); @@ -176,19 +235,10 @@ fn preflight(root: &Path) -> Result { { return refuse("repository has no commits yet"); } - for f in [ - "rebase-merge", - "rebase-apply", - "MERGE_HEAD", - "CHERRY_PICK_HEAD", - "REVERT_HEAD", - "BISECT_LOG", - ] { - if dotgit.join(f).exists() { - return refuse(format!( - "operation in progress ({f}): finish or abort it first" - )); - } + if let Some(f) = operation_in_progress(&dotgit) { + return refuse(format!( + "operation in progress ({f}): finish or abort it first" + )); } if matches!( git.probe(&["config", "--get", "core.sparseCheckout"])? @@ -204,15 +254,108 @@ fn preflight(root: &Path) -> Result { if root.join(".gitmodules").exists() || dotgit.join("modules").exists() { return refuse("submodules are not supported yet"); } - if git - .run(&["worktree", "list", "--porcelain"])? - .matches("worktree ") - .count() - > 1 - { - return refuse("repository already has linked worktrees; not supported yet"); + let linked = linked_worktrees(root, &git)?; + Ok((branch, linked)) +} + +const OPERATION_FILES: [&str; 6] = [ + "rebase-merge", + "rebase-apply", + "MERGE_HEAD", + "CHERRY_PICK_HEAD", + "REVERT_HEAD", + "BISECT_LOG", +]; + +/// First sign of an unfinished operation in a git dir (`.git` or `.git/worktrees/`). +fn operation_in_progress(gitdir: &Path) -> Option<&'static str> { + OPERATION_FILES + .into_iter() + .find(|f| gitdir.join(f).exists()) +} + +/// Linked worktrees of the plain repo at `root`, or a refusal if one cannot be moved safely. +fn linked_worktrees(root: &Path, git: &Git) -> Result, MigrateError> { + let out = git.run(&["worktree", "list", "--porcelain"])?; + let mut linked = Vec::new(); + // The first block is the main worktree. + for block in out.split("\n\n").skip(1).filter(|b| !b.trim().is_empty()) { + let mut path = None; + let mut branch = None; + let (mut locked, mut prunable) = (false, false); + for line in block.lines() { + if let Some(p) = line.strip_prefix("worktree ") { + path = Some(PathBuf::from(p)); + } else if let Some(b) = line.strip_prefix("branch refs/heads/") { + branch = Some(b.to_string()); + } else if line == "locked" || line.starts_with("locked ") { + locked = true; + } else if line == "prunable" || line.starts_with("prunable ") { + prunable = true; + } + } + let Some(path) = path else { continue }; + let shown = path.display(); + if locked { + return refuse(format!( + "linked worktree {shown} is locked: unlock it first (git worktree unlock)" + )); + } + let Ok(old_path) = path.canonicalize() else { + return refuse(format!( + "linked worktree {shown} is missing on disk: restore it or run `git worktree prune`" + )); + }; + if prunable { + return refuse(format!( + "linked worktree {shown} is prunable (broken link): fix it or run `git worktree prune`" + )); + } + if root.starts_with(&old_path) { + return refuse(format!( + "linked worktree {shown} contains the repository; not supported" + )); + } + let gitfile = old_path.join(".git"); + let orig_gitfile = fs::read_to_string(&gitfile).map_err(|e| { + MigrateError::Refused(format!("cannot read {}: {e}", gitfile.display())) + })?; + let meta = orig_gitfile + .trim() + .strip_prefix("gitdir: ") + .map(PathBuf::from) + .filter(|m| m.is_absolute()) + .ok_or_else(|| { + MigrateError::Refused(format!( + "linked worktree {shown}: unsupported .git file (relative links?)" + )) + })?; + let meta = meta.canonicalize()?; + let id = match (meta.parent(), meta.file_name()) { + (Some(p), Some(id)) if p == root.join(".git").join("worktrees") => { + id.to_string_lossy().into_owned() + } + _ => { + return refuse(format!( + "linked worktree {shown} does not belong to this repository's .git" + )); + } + }; + if let Some(f) = operation_in_progress(&meta) { + return refuse(format!( + "operation in progress ({f}) in linked worktree {shown}: finish or abort it first" + )); + } + let orig_gitdir = fs::read_to_string(meta.join("gitdir"))?; + linked.push(Linked { + old_path, + branch, + id, + orig_gitfile, + orig_gitdir, + }); } - Ok(branch) + Ok(linked) } fn backup( @@ -221,7 +364,8 @@ fn backup( machine: &str, backup_dir: &Path, stamp: &str, -) -> Result<(PathBuf, String), MigrateError> { + linked: &[Linked], +) -> Result<(PathBuf, String, Vec), MigrateError> { // Check before creating anything so a refusal never leaves stray directories behind. if std::path::absolute(backup_dir)?.starts_with(root) { return refuse("backup directory must be outside the repository"); @@ -231,6 +375,11 @@ fn backup( if backup_dir.starts_with(root) { return refuse("backup directory must be outside the repository"); } + for l in linked.iter().filter(|l| !l.old_path.starts_with(root)) { + if backup_dir.starts_with(&l.old_path) { + return refuse("backup directory must be outside the linked worktrees"); + } + } let name = root .file_name() .map(|n| n.to_string_lossy().into_owned()) @@ -253,9 +402,43 @@ fn backup( String::from_utf8_lossy(&out.stderr) )); } + // Linked worktrees outside the repo dir are not in the tar above: back each one up too. + let mut extra = Vec::new(); + for (i, l) in linked.iter().enumerate() { + if l.old_path.starts_with(root) { + continue; + } + let (Some(wp), Some(wn)) = (l.old_path.parent(), l.old_path.file_name()) else { + continue; + }; + let t = backup_dir.join(format!( + "{name}-{stamp}-linked{i}-{}.tar", + wn.to_string_lossy() + )); + let out = Command::new("tar") + .arg("-cf") + .arg(&t) + .arg("-C") + .arg(wp) + .arg(wn) + .output()?; + if !out.status.success() { + let _ = fs::remove_file(&t); + let _ = fs::remove_file(&tar); + for e in &extra { + let _ = fs::remove_file(e); + } + return refuse(format!( + "tar backup of linked worktree {} failed: {}", + l.old_path.display(), + String::from_utf8_lossy(&out.stderr) + )); + } + extra.push(t); + } let backup_ref = format!("refs/sync-backup/{machine}/{stamp}/add"); git.run(&["update-ref", &backup_ref, "HEAD"])?; - Ok((tar, backup_ref)) + Ok((tar, backup_ref, extra)) } fn migrate_inner( @@ -266,23 +449,37 @@ fn migrate_inner( inject: Option, ) -> Result { let root = repo.canonicalize()?; - let branch = preflight(&root)?; + let (branch, linked) = preflight(&root)?; let git = Git::new(&root); - let before = observe(&git)?; - let (backup_tar, backup_ref) = backup(&root, &git, machine, backup_dir, stamp)?; + let old_paths: Vec = linked.iter().map(|l| l.old_path.clone()).collect(); + let before = observe(&git, &old_paths)?; + let (backup_tar, backup_ref, linked_backups) = + backup(&root, &git, machine, backup_dir, stamp, &linked)?; let dir = dir_name(&branch, &[BARE, STAGE]); - let mut p = Progress::default(); - match run_steps(&root, &branch, &dir, &before, &mut p, inject) { + let mut p = Progress { + orig_ids: list_ids(&root.join(".git")), + ..Progress::default() + }; + match run_steps(&root, &branch, &dir, &linked, &before, &mut p, inject) { Ok(worktree) => Ok(Report { bare_dir: root.join(BARE), worktree, branch, backup_tar, backup_ref, + linked: linked + .iter() + .map(|l| LinkedReport { + old_path: l.old_path.clone(), + path: l.new_path(&root, &dir), + branch: l.branch.clone(), + }) + .collect(), + linked_backups, }), Err(cause) => { - let rb = rollback(&root, &p); + let rb = rollback(&root, &p, &linked); let (cause, rolled_back) = match rb { Ok(()) => (cause, true), Err(e) => (format!("{cause}; rollback error: {e}"), false), @@ -308,6 +505,30 @@ fn move_entries(from: &Path, to: &Path, skip: &[&str]) -> io::Result<()> { Ok(()) } +fn list_ids(gitdir: &Path) -> Vec { + fs::read_dir(gitdir.join("worktrees")) + .into_iter() + .flatten() + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect() +} + +/// Point every linked worktree's link files at the new locations. +fn relink(root: &Path, dir: &str, linked: &[Linked]) -> io::Result<()> { + let meta_root = root.join(BARE).join("worktrees"); + for l in linked { + let new = l.new_path(root, dir); + let meta = meta_root.join(&l.id); + fs::write(new.join(".git"), format!("gitdir: {}\n", meta.display()))?; + fs::write( + meta.join("gitdir"), + format!("{}\n", new.join(".git").display()), + )?; + } + Ok(()) +} + fn hook(inject: Option, at: Step) -> Result<(), String> { if inject == Some(at) { Err(format!("injected failure after {at:?}")) @@ -320,6 +541,7 @@ fn run_steps( root: &Path, branch: &str, dir: &str, + linked: &[Linked], before: &Observed, p: &mut Progress, inject: Option, @@ -376,6 +598,11 @@ fn run_steps( move_entries(&stage, &wt, &[]).map_err(s)?; hook(inject, Step::Filled)?; + // 4b. Repair the links of the linked worktrees (nested ones moved with the files). + p.relinking = true; + relink(root, dir, linked).map_err(s)?; + hook(inject, Step::Relinked)?; + // 5. Carry over the index so staged changes survive. let old_index = root.join(BARE).join("index"); if old_index.exists() { @@ -385,12 +612,35 @@ fn run_steps( hook(inject, Step::IndexMoved)?; // 6. Verify nothing observable changed. - let after = observe(&Git::new(&wt)).map_err(s)?; + let new_paths: Vec = linked.iter().map(|l| l.new_path(root, dir)).collect(); + let listing = Git::new(&wt) + .run(&["worktree", "list", "--porcelain"]) + .map_err(s)?; + for np in &new_paths { + if !listing + .lines() + .any(|l| l == format!("worktree {}", np.display())) + { + return Err(format!( + "verification failed: linked worktree {} is not registered", + np.display() + )); + } + } + if listing + .lines() + .any(|l| l == "prunable" || l.starts_with("prunable ")) + { + return Err("verification failed: a linked worktree link is broken".into()); + } + let after = observe(&Git::new(&wt), &new_paths).map_err(s)?; if &after != before { let what = if after.status != before.status { "status" } else if after.stash != before.stash { "stashes" + } else if after.linked != before.linked { + "linked worktrees" } else { "refs" }; @@ -404,7 +654,7 @@ fn run_steps( Ok(wt) } -fn rollback(root: &Path, p: &Progress) -> Result<(), String> { +fn rollback(root: &Path, p: &Progress, linked: &[Linked]) -> Result<(), String> { let stage = root.join(STAGE); let bare = root.join(BARE); if p.index_moved @@ -439,8 +689,13 @@ fn rollback(root: &Path, p: &Progress) -> Result<(), String> { } if p.git_moved { let g = Git::new(root); - // Drop metadata of a half-created worktree (e.g. `worktree add` failed midway). - let _ = g.probe(&["--git-dir", BARE, "worktree", "prune"]); + // Drop metadata of a half-created worktree (e.g. `worktree add` failed midway). Never + // `worktree prune` here: linked worktrees are temporarily at stale paths. + for id in list_ids(&bare) { + if !p.orig_ids.contains(&id) { + fs::remove_dir_all(bare.join("worktrees").join(id)).map_err(s)?; + } + } let _ = fs::remove_dir(bare.join("worktrees")); g.run(&["--git-dir", BARE, "config", "core.bare", "false"]) .map_err(s)?; @@ -454,5 +709,19 @@ fn rollback(root: &Path, p: &Progress) -> Result<(), String> { move_entries(&stage, root, &[]).map_err(s)?; fs::remove_dir(&stage).map_err(s)?; } + if p.relinking { + // Everything is back in place: restore the link files of the linked worktrees. + for l in linked { + fs::write(l.old_path.join(".git"), &l.orig_gitfile).map_err(s)?; + fs::write( + root.join(".git") + .join("worktrees") + .join(&l.id) + .join("gitdir"), + &l.orig_gitdir, + ) + .map_err(s)?; + } + } Ok(()) } diff --git a/crates/grove-core/tests/migrate.rs b/crates/grove-core/tests/migrate.rs index 4134b97..f5d2dc5 100644 --- a/crates/grove-core/tests/migrate.rs +++ b/crates/grove-core/tests/migrate.rs @@ -170,19 +170,39 @@ fn refuses_unsafe_situations_without_touching_anything() { fs::write(subm.join(".gitmodules"), "").unwrap(); assert!(refused(migrate(&subm, "m", &bk, "1")).contains("submodule")); - let multi = base.join("multi"); - let g = init(&multi); + let locked = base.join("locked"); + let g = init(&locked); commit(&g, "a", "1"); - g.run(&[ - "worktree", - "add", - "-q", - "-b", - "x", - base.join("extra").to_str().unwrap(), - ]) - .unwrap(); - assert!(refused(migrate(&multi, "m", &bk, "1")).contains("linked worktrees")); + let lw = base.join("locked-wt"); + g.run(&["worktree", "add", "-q", "-b", "x", lw.to_str().unwrap()]) + .unwrap(); + g.run(&["worktree", "lock", lw.to_str().unwrap()]).unwrap(); + assert!(refused(migrate(&locked, "m", &bk, "1")).contains("locked")); + assert!(locked.join(".git").is_dir(), "refusal touches nothing"); + + let prunable = base.join("prunable"); + let g = init(&prunable); + commit(&g, "a", "1"); + let pw = base.join("prunable-wt"); + g.run(&["worktree", "add", "-q", "-b", "x", pw.to_str().unwrap()]) + .unwrap(); + fs::remove_dir_all(&pw).unwrap(); + assert!(refused(migrate(&prunable, "m", &bk, "1")).contains("missing")); + + let busy = base.join("busy"); + let g = init(&busy); + commit(&g, "a", "1"); + let bw = base.join("busy-wt"); + g.run(&["worktree", "add", "-q", "-b", "x", bw.to_str().unwrap()]) + .unwrap(); + let meta = fs::read_to_string(bw.join(".git")).unwrap(); + let meta = meta.trim().strip_prefix("gitdir: ").unwrap(); + fs::write(std::path::Path::new(meta).join("MERGE_HEAD"), "x").unwrap(); + let m = refused(migrate(&busy, "m", &bk, "1")); + assert!( + m.contains("in progress") && m.contains("linked worktree"), + "{m}" + ); let done = base.join("done"); let g = init(&done); @@ -209,3 +229,169 @@ fn refuses_unsafe_situations_without_touching_anything() { fs::create_dir(inside.join("sub")).unwrap(); assert!(refused(migrate(&inside.join("sub"), "m", &bk, "1")).contains("plain clone")); } + +/// Observable state of a worktree: HEAD, branch and `status --ignored`. +fn wt_state(dir: &std::path::Path) -> String { + let g = Git::new(dir); + format!( + "{}|{}|{}", + g.run(&["rev-parse", "HEAD"]).unwrap(), + g.probe(&["symbolic-ref", "-q", "HEAD"]) + .unwrap() + .unwrap_or_default(), + g.run(&["status", "--porcelain", "--ignored"]).unwrap() + ) +} + +/// A repo with a detached worktree nested in it and a dirty branch worktree next to it. +fn repo_with_linked( + base: &std::path::Path, +) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) { + let repo = base.join("proj"); + let g = messy_repo(&repo); + let nested = repo.join(".claude/worktrees/wt1"); + fs::create_dir_all(nested.parent().unwrap()).unwrap(); + g.run(&[ + "worktree", + "add", + "-q", + "--detach", + nested.to_str().unwrap(), + ]) + .unwrap(); + fs::write(nested.join("src/a.txt"), "nested edit\n").unwrap(); + fs::write(nested.join("nested-untracked.txt"), "n\n").unwrap(); + fs::write(nested.join("nested.env"), "ignored\n").unwrap(); + let outside = base.join("proj-feature"); + g.run(&[ + "worktree", + "add", + "-q", + "-b", + "feat/out", + outside.to_str().unwrap(), + ]) + .unwrap(); + fs::write(outside.join("b.txt"), "outside edit\n").unwrap(); + fs::write(outside.join("new-staged.txt"), "s\n").unwrap(); + Git::new(&outside).run(&["add", "new-staged.txt"]).unwrap(); + fs::write(outside.join("out-untracked.txt"), "u\n").unwrap(); + fs::write(outside.join("out.env"), "ignored\n").unwrap(); + (repo, nested, outside) +} + +fn same_links(wt: &std::path::Path, bare: &std::path::Path) { + let pointer = fs::read_to_string(wt.join(".git")).unwrap(); + let meta = std::path::PathBuf::from(pointer.trim().strip_prefix("gitdir: ").unwrap()); + assert!(meta.starts_with(bare.join("worktrees")), "{pointer}"); + let back = fs::read_to_string(meta.join("gitdir")).unwrap(); + assert_eq!(back.trim(), wt.join(".git").to_str().unwrap()); +} + +#[test] +fn migrates_with_nested_detached_and_outside_branch_worktrees() { + let base = tmpdir("linked"); + let (repo, nested, outside) = repo_with_linked(&base); + let (nested_before, outside_before) = (wt_state(&nested), wt_state(&outside)); + let main_before = wt_state(&repo); + assert!(nested_before.contains("nested-untracked.txt")); + + let r = migrate(&repo, "m", &base.join("bk"), "1").unwrap(); + + let root = repo.canonicalize().unwrap(); + let new_nested = root.join("main/.claude/worktrees/wt1"); + assert_eq!(names(&root), vec![".bare", "main"]); + assert_eq!(r.linked.len(), 2); + let find = |p: &std::path::Path| r.linked.iter().find(|l| l.path == p).unwrap(); + assert_eq!(find(&new_nested).branch, None); + assert_eq!( + find(&new_nested).old_path, + root.join(".claude/worktrees/wt1") + ); + let out_canon = outside.canonicalize().unwrap(); + assert_eq!(find(&out_canon).branch.as_deref(), Some("feat/out")); + assert_eq!(find(&out_canon).old_path, out_canon); + assert_eq!( + r.linked_backups.len(), + 1, + "outside worktree gets its own tar" + ); + assert!(r.linked_backups[0].metadata().unwrap().len() > 0); + + // Same observable state in all three worktrees, and links point both ways. + assert_eq!(wt_state(&r.worktree), main_before); + assert_eq!(wt_state(&new_nested), nested_before); + assert_eq!(wt_state(&outside), outside_before); + same_links(&new_nested, &r.bare_dir); + same_links(&outside.canonicalize().unwrap(), &r.bare_dir); + assert!(!root.join(".claude").exists()); + assert_eq!( + fs::read_to_string(outside.join("b.txt")).unwrap(), + "outside edit\n" + ); + assert!(outside.join("out.env").exists()); + assert!(new_nested.join("nested.env").exists()); + + let list = Git::new(&r.worktree) + .run(&["worktree", "list", "--porcelain"]) + .unwrap(); + assert!(list.contains(&format!("worktree {}", new_nested.display()))); + assert!(list.contains(&format!( + "worktree {}", + outside.canonicalize().unwrap().display() + ))); + assert!(!list.contains("prunable"), "{list}"); + + // They are still usable: commit on the outside branch, status in the nested one. + let og = Git::new(&outside); + og.run(&["commit", "-qam", "more"]).unwrap(); + assert!(Git::new(&new_nested).run(&["status"]).is_ok()); +} + +#[test] +fn rollback_restores_linked_worktrees_at_every_step() { + for step in [ + Step::Staged, + Step::GitMoved, + Step::WorktreeAdded, + Step::Filled, + Step::Relinked, + Step::IndexMoved, + Step::Verified, + ] { + let base = tmpdir("rblinked"); + let (repo, nested, outside) = repo_with_linked(&base); + let before = (wt_state(&repo), wt_state(&nested), wt_state(&outside)); + let files = ( + fs::read_to_string(nested.join(".git")).unwrap(), + fs::read_to_string(outside.join(".git")).unwrap(), + ); + let names_before = names(&repo); + + let err = migrate_failing_after(&repo, "m", &base.join("bk"), "1", step).unwrap_err(); + let MigrateError::Failed { rolled_back, .. } = err else { + panic!("{step:?}: expected Failed") + }; + assert!(rolled_back, "{step:?}"); + + assert_eq!(names(&repo), names_before, "{step:?}"); + assert_eq!( + (wt_state(&repo), wt_state(&nested), wt_state(&outside)), + before, + "{step:?}" + ); + assert_eq!(fs::read_to_string(nested.join(".git")).unwrap(), files.0); + assert_eq!(fs::read_to_string(outside.join(".git")).unwrap(), files.1); + let g = Git::new(&repo); + let list = g.run(&["worktree", "list", "--porcelain"]).unwrap(); + assert_eq!(list.matches("worktree ").count(), 3, "{step:?}: {list}"); + assert!(!list.contains("prunable"), "{step:?}: {list}"); + assert_eq!( + fs::read_dir(repo.join(".git/worktrees")).unwrap().count(), + 2, + "{step:?}: only the original worktree metadata remains" + ); + // And a retry succeeds afterwards. + migrate(&repo, "m", &base.join("bk"), "2").unwrap(); + } +}