Skip to content

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

fix(remove): don't point at a detached worktree removed in the same run (#4313)

Worktrunk Botd0594169d4e3
diff --git a/src/commands/remove.rs b/src/commands/remove.rs
index 7f047c8c4..c4a84d1b3 100644
--- a/src/commands/remove.rs
+++ b/src/commands/remove.rs
@@ -250,6 +250,29 @@ fn validate_remove_targets(
}
}
+ // `wt remove <branch> <its-detached-path>` removes that directory in this
+ // run, so it isn't left behind. Checked after the loop because the path
+ // argument can come before or after the branch.
+ let removed: Vec<&Path> = plans
+ .others
+ .iter()
+ .chain(&plans.current)
+ .filter_map(RemovalPlan::removed_worktree_path)
+ .collect();
+ for plan in &mut plans.branch_only {
+ if let RemovalPlan::BranchOnly {
+ detached_worktree, ..
+ } = plan
+ && detached_worktree.as_deref().is_some_and(|detached| {
+ removed
+ .iter()
+ .any(|path| worktrunk::path::paths_match(path, detached))
+ })
+ {
+ *detached_worktree = None;
+ }
+ }
+
plans
}
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 0fde7688a..f81e66ee0 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -4792,6 +4792,48 @@ fn test_remove_json_reports_detached_worktree(mut repo: TestRepo) {
);
}
+/// Naming the detached worktree by path alongside the branch — the removal the
+/// hint above suggests — removes that directory in the same run, so the
+/// branch-only removal must not report it as left behind.
+#[rstest]
+fn test_remove_branch_and_its_detached_worktree_together(mut repo: TestRepo) {
+ let worktree_path = repo.add_worktree("both-detached");
+ repo.detach_head_in_worktree("both-detached");
+
+ let output = repo
+ .wt_command()
+ .args([
+ "remove",
+ "both-detached",
+ worktree_path.to_str().unwrap(),
+ "--format=json",
+ "--yes",
+ "--foreground",
+ ])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ assert!(!worktree_path.exists(), "detached worktree must be removed");
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ !stderr.contains("a detached worktree is @"),
+ "must not point at a directory this run removed; stderr:\n{stderr}"
+ );
+ let json: serde_json::Value =
+ serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();
+ let branch_only = json
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|e| e["kind"] == "branch_only")
+ .unwrap_or_else(|| panic!("expected a branch_only entry: {json}"));
+ assert!(
+ branch_only["detached_worktree"].is_null(),
+ "json must not name a directory this run removed: {json}"
+ );
+}
+
#[cfg(not(target_os = "windows"))]
#[rstest]
fn test_remove_json_multi_with_branch_only(mut repo: TestRepo) {