Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(remove): name trash staging dirs by worktree registration (#4361)

Maximilian Roosf844d09cea7f
diff --git a/src/git/remove.rs b/src/git/remove.rs
index bcac99300..83c7036ea 100644
--- a/src/git/remove.rs
+++ b/src/git/remove.rs
@@ -462,7 +462,7 @@ pub fn stage_worktree_removal(
force_worktree: bool,
) -> anyhow::Result<Option<PathBuf>> {
let worktree = repo.worktree_at(worktree_path);
- worktree.ensure_holds_this_worktree()?;
+ let git_dir = worktree.ensure_holds_this_worktree()?;
// Lock is the user's explicit "don't remove this". `--force` does not
// override it, matching `git worktree remove` and `prepare_worktree_removal`.
@@ -487,7 +487,7 @@ pub fn stage_worktree_removal(
stop_fsmonitor_daemon(&repo.worktree_at(worktree_path));
- Ok(rename_into_trash(repo, worktree_path))
+ Ok(rename_into_trash(repo, worktree_path, &git_dir))
}
/// Rename a worktree into `<git-common-dir>/wt/trash/` and prune git metadata.
@@ -501,12 +501,17 @@ pub fn stage_worktree_removal(
/// sweeping the repository, so a sibling worktree whose directory happens to
/// be absent right now keeps its registration. A locked worktree never reaches
/// here — [`stage_worktree_removal`] rejects one before the rename.
-fn rename_into_trash(repo: &Repository, worktree_path: &Path) -> Option<PathBuf> {
+fn rename_into_trash(repo: &Repository, worktree_path: &Path, git_dir: &Path) -> Option<PathBuf> {
let trash_dir = repo.wt_trash_dir();
let _ = std::fs::create_dir_all(&trash_dir);
- let staged_path = generate_removing_path(&trash_dir, worktree_path);
+ let staged_path = generate_removing_path(&trash_dir, git_dir);
- if std::fs::rename(worktree_path, &staged_path).is_ok() {
+ if std::fs::rename(worktree_path, &staged_path)
+ .inspect_err(|e| {
+ tracing::debug!(error = %e, "Failed to stage worktree into trash, falling back: {e}");
+ })
+ .is_ok()
+ {
// The rename moved the directory out from under `worktree_path`,
// leaving its registration stale for the prune to delete.
if let Err(e) = repo.prune_worktree_entry(worktree_path) {
@@ -676,10 +681,16 @@ fn cas_delete_branch_outcome(
/// worktrees on different mount points will get EXDEV and fall back to the
/// `git worktree remove` path.
///
-/// Format: `<trash-dir>/<name>-<timestamp>`
-pub(crate) fn generate_removing_path(trash_dir: &Path, worktree_path: &Path) -> PathBuf {
+/// Format: `<trash-dir>/<name>-<timestamp>`, where `<name>` is the final
+/// component of the worktree's `git_dir`: its registration id under
+/// `<common>/worktrees/`, which git keeps unique among a repository's
+/// worktrees. The directory's basename is not unique — Codex places every
+/// worktree at `<id>/<repo>` — and two removals sharing a staging path in the
+/// same second would make the second rename fail onto the synchronous
+/// fallback.
+pub(crate) fn generate_removing_path(trash_dir: &Path, git_dir: &Path) -> PathBuf {
let timestamp = epoch_now();
- let name = worktree_path
+ let name = git_dir
.file_name()
.map(|n| n.to_string_lossy())
.unwrap_or_default();
@@ -1056,11 +1067,11 @@ mod tests {
#[test]
fn test_generate_removing_path() {
let trash_dir = PathBuf::from("/some/path/.git/wt/trash");
- let path = PathBuf::from("/foo/bar/feature-branch");
- let removing_path = generate_removing_path(&trash_dir, &path);
- // Format: <trash>/<name>-<timestamp>
+ let git_dir = PathBuf::from("/some/path/.git/worktrees/repo1");
+ let removing_path = generate_removing_path(&trash_dir, &git_dir);
+ // Format: <trash>/<registration>-<timestamp>
let name = removing_path.file_name().unwrap().to_string_lossy();
- assert!(name.starts_with("feature-branch-"));
+ assert!(name.starts_with("repo1-"));
assert!(removing_path.starts_with(&trash_dir));
}
diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rs
index 1708b4add..49b0ed766 100644
--- a/src/git/repository/working_tree.rs
+++ b/src/git/repository/working_tree.rs
@@ -890,14 +890,18 @@ impl<'a> WorkingTree<'a> {
/// two cover different halves of "the directory no longer holds this
/// worktree": prunable is the half git notices, this is the half it does
/// not.
- pub fn ensure_holds_this_worktree(&self) -> anyhow::Result<()> {
+ ///
+ /// Returns the git dir that answers for this worktree: the common dir for
+ /// the main worktree, its registration under `<common>/worktrees/`
+ /// otherwise.
+ pub fn ensure_holds_this_worktree(&self) -> anyhow::Result<PathBuf> {
let common_dir = self.repo.git_common_dir();
// A git dir that can't be resolved at all is the strongest form of "not
// this worktree": nothing there answers for it. Treating that as a
// refusal keeps the failure closed.
let git_dir = Repository::git_dir_at(&self.path);
if git_dir.as_deref() == Some(common_dir) {
- return Ok(());
+ return Ok(common_dir.to_path_buf());
}
// Where the occupant's own registration says it lives. `None` when there
@@ -905,15 +909,15 @@ impl<'a> WorkingTree<'a> {
// different repository, or its registration here has lost its `gitdir`
// file.
let registrations = common_dir.join("worktrees");
- let occupant_registered_at = git_dir
- .filter(|git_dir| git_dir.parent() == Some(registrations.as_path()))
- .as_deref()
- .and_then(registration_worktree_path);
- if occupant_registered_at
- .as_deref()
- .is_some_and(|recorded| crate::path::paths_match(recorded, &self.path))
+ let registration =
+ git_dir.filter(|git_dir| git_dir.parent() == Some(registrations.as_path()));
+ let occupant_registered_at = registration.as_deref().and_then(registration_worktree_path);
+ if let Some(registration) = registration
+ && occupant_registered_at
+ .as_deref()
+ .is_some_and(|recorded| crate::path::paths_match(recorded, &self.path))
{
- return Ok(());
+ return Ok(registration);
}
Err(GitError::WorktreePathNotOurs {
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index edd094963..d0b591cf9 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -79,6 +79,43 @@ fn test_prune_removes_merged(mut repo: TestRepo) {
assert!(!worktree_path.exists(), "Worktree should be fully removed");
}
+/// Worktrees sharing a directory basename (Codex's `<id>/<repo>` layout) each
+/// stage into trash. The suite pins `epoch_now()`, so with basename-derived
+/// staging names the second rename would collide and fall back to a
+/// synchronous `git worktree remove`, which spawns no detached cleanup.
+#[rstest]
+fn test_prune_stages_worktrees_sharing_a_basename(mut repo: TestRepo) {
+ repo.commit("initial");
+ let parent = repo.root_path().parent().unwrap().to_path_buf();
+ let worktrees = [
+ ("one", parent.join("aaaa/repo")),
+ ("two", parent.join("bbbb/repo")),
+ ];
+ for (branch, path) in &worktrees {
+ repo.add_worktree_at_path(branch, path);
+ }
+
+ let output = repo
+ .wt_command()
+ .args(["step", "prune", "--yes", "--min-age=0s"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let logs = crate::common::resolve_git_common_dir(repo.root_path()).join("wt/logs");
+ for (branch, path) in &worktrees {
+ assert!(!path.exists(), "{branch} must be removed");
+ assert!(
+ logs.join(branch).join("internal/remove.log").exists(),
+ "{branch} must be staged into trash with a detached cleanup"
+ );
+ }
+}
+
/// Prune skips worktrees with unique commits (not merged)
#[rstest]
fn test_prune_skips_unmerged(mut repo: TestRepo) {