Merge branch 'feat/migrate-linked-worktrees' into feat/daemon-scope

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-11-16 17:22:15 +01:00
commit 8bcdcd5771
7 files changed
+705 -52

No files matched your search

+328 -38
View File
@@ -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 (`<wt>/.git` and `.bare/worktrees/<id>/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<LinkedReport>,
/// Extra tar backups, one per linked worktree outside the repo directory.
pub linked_backups: Vec<PathBuf>,
}
#[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<String>,
}
/// 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<String>,
/// Directory name under `.git/worktrees/`.
id: String,
/// Original contents of `<wt>/.git` and `.git/worktrees/<id>/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<PathBuf>,
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<String>,
/// Original `core.worktree`, restored on rollback.
orig_core_worktree: Option<String>,
}
@@ -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<String>,
}
fn observe(git: &Git) -> Result<Observed, GitError> {
fn observe(git: &Git, linked: &[PathBuf]) -> Result<Observed, GitError> {
let refs = git.run(&["for-each-ref", "--format=%(refname) %(objectname)"])?;
let refs = refs
.lines()
.filter(|l| !l.starts_with("refs/sync-backup/"))
.collect::<Vec<_>>()
.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,14 +208,14 @@ fn refuse<T>(m: impl Into<String>) -> Result<T, MigrateError> {
Err(MigrateError::Refused(m.into()))
}
fn preflight(root: &Path) -> Result<String, MigrateError> {
fn preflight(root: &Path) -> Result<(String, Vec<Linked>), MigrateError> {
let dotgit = root.join(".git");
if root.join(BARE).exists() {
return refuse("already migrated (.bare exists)");
}
if root.join(STAGE).exists() {
return refuse(format!(
"{STAGE} exists: a previous migration was interrupted. Your files are in {STAGE} and the git dir in .bare; restore from the backup tar or move them back by hand"
"{STAGE} exists: a previous migration was interrupted. Your files are in {STAGE} and the git dir in .bare; restore from the backup tar or move them back by hand. Linked worktrees may also need their .git link files restored from the backup tars or `git worktree repair`"
));
}
if !dotgit.is_dir() {
@@ -176,19 +235,10 @@ fn preflight(root: &Path) -> Result<String, MigrateError> {
{
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"])?
@@ -201,18 +251,132 @@ fn preflight(root: &Path) -> Result<String, MigrateError> {
) {
return refuse("sparse checkout / per-worktree config is not supported yet");
}
if root.join(".gitmodules").exists() || dotgit.join("modules").exists() {
if root.join(".gitmodules").exists()
|| dotgit.join("modules").exists()
|| list_ids(&dotgit)
.iter()
.any(|id| dotgit.join("worktrees").join(id).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");
for key in ["worktree.useRelativePaths", "extensions.relativeWorktrees"] {
if matches!(
git.probe(&["config", "--type=bool", "--get", key])?
.as_deref(),
Some("true")
) {
return refuse(format!(
"{key} (relative worktree links) is not supported yet"
));
}
}
Ok(branch)
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/<id>`).
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<Vec<Linked>, 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"
));
}
if old_path.join(".gitmodules").exists() {
return refuse(format!(
"linked worktree {shown} has submodules; not supported yet"
));
}
let orig_gitdir = fs::read_to_string(meta.join("gitdir"))?;
linked.push(Linked {
old_path,
branch,
id,
orig_gitfile,
orig_gitdir,
});
}
Ok(linked)
}
fn backup(
@@ -221,7 +385,8 @@ fn backup(
machine: &str,
backup_dir: &Path,
stamp: &str,
) -> Result<(PathBuf, String), MigrateError> {
linked: &[Linked],
) -> Result<(PathBuf, String, Vec<PathBuf>), 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 +396,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 +423,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 +470,37 @@ fn migrate_inner(
inject: Option<Step>,
) -> Result<Report, MigrateError> {
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<PathBuf> = 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 +526,30 @@ fn move_entries(from: &Path, to: &Path, skip: &[&str]) -> io::Result<()> {
Ok(())
}
fn list_ids(gitdir: &Path) -> Vec<String> {
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<Step>, at: Step) -> Result<(), String> {
if inject == Some(at) {
Err(format!("injected failure after {at:?}"))
@@ -320,6 +562,7 @@ fn run_steps(
root: &Path,
branch: &str,
dir: &str,
linked: &[Linked],
before: &Observed,
p: &mut Progress,
inject: Option<Step>,
@@ -366,7 +609,7 @@ fn run_steps(
let meta = pointer
.trim()
.strip_prefix("gitdir: ")
.map(PathBuf::from)
.map(|m| wt.join(m))
.ok_or("unexpected .git file in new worktree")?;
p.wt_meta = Some(meta.clone());
hook(inject, Step::WorktreeAdded)?;
@@ -376,6 +619,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 +633,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<PathBuf> = 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 +675,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 +710,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 +730,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(())
}
+6
View File
@@ -376,11 +376,17 @@ pub fn archive_gone(root: &Path, machine: &str, stamp: &str) -> Result<Vec<Archi
.map(|(b, _)| b)
.collect();
let wts = crate::inspect::worktrees(&bare)?;
let canonical_root = root.canonicalize().ok();
let mut out = Vec::new();
for branch in gone {
let Some(wt) = wts.iter().find(|w| w.branch.as_deref() == Some(branch)) else {
continue;
};
// Only worktrees of the layout (`<root>/<dir>`) are ours to remove; a linked worktree
// elsewhere (e.g. a sibling directory) is the user's.
if wt.path.parent() != canonical_root.as_deref() {
continue;
}
// Ignored files (.env, build output...) count as local work too.
if !Git::new(&wt.path)
.run(&["status", "--porcelain", "--ignored"])?
+225 -12
View File
@@ -170,19 +170,66 @@ 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 subw = base.join("subw");
let g = init(&subw);
commit(&g, "a", "1");
let sw = base.join("subw-wt");
g.run(&["worktree", "add", "-q", "-b", "x", sw.to_str().unwrap()])
.unwrap();
fs::write(sw.join(".gitmodules"), "").unwrap();
assert!(refused(migrate(&subw, "m", &bk, "1")).contains("submodules"));
let subm2 = base.join("subm2");
let g = init(&subm2);
commit(&g, "a", "1");
let sw2 = base.join("subm2-wt");
g.run(&["worktree", "add", "-q", "-b", "x", sw2.to_str().unwrap()])
.unwrap();
let meta = fs::read_to_string(sw2.join(".git")).unwrap();
let meta = meta.trim().strip_prefix("gitdir: ").unwrap();
fs::create_dir_all(std::path::Path::new(meta).join("modules/m")).unwrap();
assert!(refused(migrate(&subm2, "m", &bk, "1")).contains("submodules"));
let rel = base.join("rel");
let g = init(&rel);
commit(&g, "a", "1");
g.run(&["config", "worktree.useRelativePaths", "true"])
.unwrap();
assert!(refused(migrate(&rel, "m", &bk, "1")).contains("relative"));
assert!(rel.join(".git").is_dir());
let done = base.join("done");
let g = init(&done);
@@ -209,3 +256,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();
}
}
+84
View File
@@ -210,3 +210,87 @@ fn withheld_snapshots_are_neither_taken_nor_pushed_but_fast_forward_still_works(
));
assert!(d.join("b.txt").exists());
}
#[test]
fn migrated_repo_with_linked_worktrees_syncs_only_what_it_can() {
use grove_core::migrate::migrate;
let base = tmpdir("synclinked");
let remote = base.join("r.git");
Git::new(&base)
.run(&[
"init",
"-q",
"--bare",
"-b",
"main",
remote.to_str().unwrap(),
])
.unwrap();
let seed = init(&base.join("seed"));
seed.run(&["remote", "add", "origin", remote.to_str().unwrap()])
.unwrap();
commit(&seed, "a.txt", "1\n");
seed.run(&["push", "-q", "-u", "origin", "main"]).unwrap();
seed.run(&["push", "-q", "origin", "main:feat/out"])
.unwrap();
let (ga, da) = clone(&base, &remote, "A");
let nested = da.join(".claude/worktrees/wt1");
ga.run(&[
"worktree",
"add",
"-q",
"--detach",
nested.to_str().unwrap(),
])
.unwrap();
let outside = base.join("A-feature");
ga.run(&[
"worktree",
"add",
"-q",
"--track",
"-b",
"feat/out",
outside.to_str().unwrap(),
"origin/feat/out",
])
.unwrap();
migrate(&da, "A", &base.join("bk"), "1").unwrap();
let nested = da.join("main/.claude/worktrees/wt1");
fs::write(nested.join("a.txt"), "detached edit\n").unwrap();
fs::write(outside.join("a.txt"), "outside edit\n").unwrap();
let rep = sync_repo(&da, &opts("A", "t1")).unwrap();
let find = |p: &Path| {
rep.worktrees
.iter()
.find(|w| w.path == p.canonicalize().unwrap())
.unwrap_or_else(|| panic!("{} not reported: {:?}", p.display(), rep.worktrees))
};
// Detached: reported, never snapshotted.
let d = find(&nested);
assert_eq!((d.branch.clone(), d.snapshot), (None, None));
assert!(d.errors.is_empty(), "{:?}", d.errors);
assert_eq!(d.state, State::Dirty);
// Branch worktree elsewhere: synced under its own branch ref.
let o = find(&outside);
assert_eq!(o.snapshot, Some("created"));
assert!(o.errors.is_empty(), "{:?}", o.errors);
let bare = Git::new(da.join(".bare"));
assert!(bare.run(&["rev-parse", "refs/sync/A/feat/out"]).is_ok());
assert!(
bare.probe(&["rev-parse", "-q", "--verify", "refs/sync/A/HEAD"])
.unwrap()
.is_none()
);
// Gone upstream + clean: a worktree outside the layout is never archived or removed.
Git::new(&outside)
.run(&["checkout", "-q", "--", "."])
.unwrap();
seed.run(&["push", "-q", "origin", "--delete", "feat/out"])
.unwrap();
let rep = sync_repo(&da, &opts("A", "t2")).unwrap();
assert!(rep.archived.is_empty(), "{:?}", rep.archived);
assert!(outside.join("a.txt").exists());
}