Skip to content

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

Refactor remove command to continue on partial failures

Maximilian Roos0c3c0534204f
diff --git a/CLAUDE.md b/CLAUDE.md
index e58cd0ada..b3ea6b709 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -37,6 +37,7 @@ Use consistent terminology in documentation, help text, and code comments:
- **main worktree** — when referring to the primary worktree (the original git directory)
- **default branch** — when referring to the branch (main, master, etc.)
+- **target** — the destination branch for merge/rebase/push operations (e.g., "merge target", "rebase onto target"). Do NOT use "target" to refer to worktrees being operated on — use "worktree" or "worktrees" instead.
Avoid mixing: "main/default branch worktree" is confusing. Use "main worktree" for worktrees and "default branch" for branches.
diff --git a/src/main.rs b/src/main.rs
index cfcc34ab9..302f9451c 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1323,11 +1323,11 @@ fn main() {
let current_worktree = repo.worktree_root().ok();
// Partition worktrees into current, others, and branch-only.
- // Collect errors for invalid names so we can report all of them.
+ // Track all errors (resolution + removal) so we can report them and continue.
let mut others = Vec::new();
let mut branch_only = Vec::new();
let mut current: Option<(PathBuf, Option<String>)> = None;
- let mut errors: Vec<anyhow::Error> = Vec::new();
+ let mut all_errors: Vec<anyhow::Error> = Vec::new();
for worktree_name in &worktrees {
match resolve_worktree_arg(
@@ -1347,28 +1347,13 @@ fn main() {
branch_only.push(branch);
}
Err(e) => {
- errors.push(e);
+ // GitError variants already include emoji via error_message() in Display
+ output::print(e.to_string())?;
+ all_errors.push(e);
}
}
}
- // If any names failed to resolve, report those errors
- // (resolution errors are fatal - we can't proceed with unknown names)
- if !errors.is_empty() {
- for e in &errors {
- // GitError variants already include emoji via error_message() in Display
- output::print(e.to_string())?;
- }
- anyhow::bail!(
- "Failed to resolve {} of {} specified names",
- errors.len(),
- worktrees.len()
- );
- }
-
- // Track removal errors so we can report all of them
- let mut removal_errors: Vec<anyhow::Error> = Vec::new();
-
// Remove other worktrees first (approval was handled at the gate)
for (path, branch) in &others {
if let Some(branch_name) = branch {
@@ -1386,7 +1371,10 @@ fn main() {
verify,
)?;
}
- Err(e) => removal_errors.push(e),
+ Err(e) => {
+ output::print(e.to_string())?;
+ all_errors.push(e);
+ }
}
} else {
// Non-current worktree is detached - remove by path (no branch to delete)
@@ -1394,7 +1382,10 @@ fn main() {
Ok(result) => {
handle_remove_output(&result, None, background, verify)?;
}
- Err(e) => removal_errors.push(e),
+ Err(e) => {
+ output::print(e.to_string())?;
+ all_errors.push(e);
+ }
}
}
}
@@ -1405,7 +1396,10 @@ fn main() {
Ok(result) => {
handle_remove_output(&result, Some(branch), background, verify)?;
}
- Err(e) => removal_errors.push(e),
+ Err(e) => {
+ output::print(e.to_string())?;
+ all_errors.push(e);
+ }
}
}
@@ -1420,29 +1414,16 @@ fn main() {
verify,
)?;
}
- Err(e) => removal_errors.push(e),
+ Err(e) => {
+ output::print(e.to_string())?;
+ all_errors.push(e);
+ }
}
}
- // Report all removal errors
- if !removal_errors.is_empty() {
- for e in &removal_errors {
- // Errors already have their own formatting (emoji + color)
- output::print(e.to_string())?;
- }
- // Only show summary for multiple targets (single target error is self-explanatory)
- if worktrees.len() > 1 {
- anyhow::bail!(
- "Failed to remove {} of {} specified targets",
- removal_errors.len(),
- worktrees.len()
- );
- } else {
- // Single target - error already printed, just exit with failure
- // Terminate output before exiting (handles directive mode)
- let _ = output::terminate_output();
- process::exit(1);
- }
+ // Exit with failure if any errors occurred (errors already printed)
+ if !all_errors.is_empty() {
+ anyhow::bail!("");
}
Ok(())
@@ -1526,15 +1507,18 @@ fn main() {
// Anyhow error formatting:
// - With context: show context as header, root cause in gutter
// - Simple error: inline with emoji
+ // - Empty error: skip (errors already printed elsewhere)
let msg = e.to_string();
- let root_cause = e.root_cause().to_string();
- if msg != root_cause {
- // Has context: msg is context, root_cause is underlying error
- let _ = output::print(error_message(&msg));
- let _ = output::gutter(format_with_gutter(&root_cause, "", None));
- } else {
- // Simple error: inline with emoji
- let _ = output::print(cformat!("{ERROR_EMOJI} <red>{msg}</>"));
+ if !msg.is_empty() {
+ let root_cause = e.root_cause().to_string();
+ if msg != root_cause {
+ // Has context: msg is context, root_cause is underlying error
+ let _ = output::print(error_message(&msg));
+ let _ = output::gutter(format_with_gutter(&root_cause, "", None));
+ } else {
+ // Simple error: inline with emoji
+ let _ = output::print(cformat!("{ERROR_EMOJI} <red>{msg}</>"));
+ }
}
}
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 1f87294f6..4f93adc1a 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -230,6 +230,34 @@ fn test_remove_remote_only_branch(#[from(repo_with_remote)] repo: TestRepo) {
);
}
+#[rstest]
+fn test_remove_nonexistent_branch(repo: TestRepo) {
+ // Try to remove a branch that doesn't exist at all
+ snapshot_remove("remove_nonexistent_branch", &repo, &["nonexistent"], None);
+}
+
+#[rstest]
+fn test_remove_partial_success(mut repo: TestRepo) {
+ // Create one valid worktree
+ let _feature_path = repo.add_worktree("feature");
+
+ // Try to remove both the valid worktree and a nonexistent one
+ // The valid one should be removed; error for nonexistent; exit with failure
+ snapshot_remove(
+ "remove_partial_success",
+ &repo,
+ &["feature", "nonexistent"],
+ None,
+ );
+
+ // Verify the valid worktree was actually removed
+ let worktrees_dir = repo.root_path().parent().unwrap();
+ assert!(
+ !worktrees_dir.join("feature").exists(),
+ "feature worktree should have been removed despite partial failure"
+ );
+}
+
#[rstest]
fn test_remove_by_name_dirty_target(mut repo: TestRepo) {
let worktree_path = repo.add_worktree("feature-dirty");
diff --git a/tests/integration_tests/statusline.rs b/tests/integration_tests/statusline.rs
index a3bef4339..93dd42141 100644
--- a/tests/integration_tests/statusline.rs
+++ b/tests/integration_tests/statusline.rs
@@ -223,3 +223,68 @@ fn test_statusline_directive_mode(repo: TestRepo) {
"stderr should have statusline output in directive mode"
);
}
+
+// --- Branch Display Tests ---
+
+/// Test that statusline reflects the current branch after checkout.
+///
+/// Git updates worktree metadata (`branch` field in `git worktree list`) when
+/// you checkout a different branch. This test verifies that statusline correctly
+/// shows the new branch name after such a checkout.
+#[rstest]
+fn test_statusline_reflects_checked_out_branch(mut repo: TestRepo) {
+ // Create a feature worktree
+ let feature_path = repo.add_worktree("feature");
+
+ // Verify statusline shows "feature" initially
+ let output = run_statusline_from_dir(&repo, &[], None, &feature_path);
+ assert!(
+ output.contains("feature"),
+ "statusline should show 'feature' for feature worktree, got: {output}"
+ );
+
+ // Create and checkout a different branch "other" in the feature worktree
+ repo.git_command(&["branch", "other"]).output().unwrap();
+ let checkout_output = repo
+ .git_command(&["checkout", "other"])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+ assert!(
+ checkout_output.status.success(),
+ "checkout should succeed: {}",
+ String::from_utf8_lossy(&checkout_output.stderr)
+ );
+
+ // Verify statusline now shows "other"
+ let output = run_statusline_from_dir(&repo, &[], None, &feature_path);
+ assert!(
+ output.contains("other"),
+ "statusline should show 'other' after checkout, got: {output}"
+ );
+ assert!(
+ !output.contains("feature"),
+ "statusline should not show 'feature' after checkout, got: {output}"
+ );
+}
+
+/// Test that statusline handles detached HEAD correctly.
+#[rstest]
+fn test_statusline_detached_head(mut repo: TestRepo) {
+ // Create a feature worktree
+ let feature_path = repo.add_worktree("feature");
+
+ // Detach HEAD
+ repo.git_command(&["checkout", "--detach"])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+
+ // Verify statusline shows HEAD (not "feature")
+ let output = run_statusline_from_dir(&repo, &[], None, &feature_path);
+ // In detached state, we show "HEAD" as the branch name
+ assert!(
+ output.contains("HEAD") || !output.contains("feature"),
+ "statusline should not show 'feature' in detached HEAD, got: {output}"
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_multiple_nonexistent_force.snap b/tests/snapshots/integration__integration_tests__remove__remove_multiple_nonexistent_force.snap
index ef6da0557..b28c58332 100644
--- a/tests/snapshots/integration__integration_tests__remove__remove_multiple_nonexistent_force.snap
+++ b/tests/snapshots/integration__integration_tests__remove__remove_multiple_nonexistent_force.snap
@@ -17,6 +17,7 @@ info:
GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
GIT_CONFIG_SYSTEM: /dev/null
GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
LC_ALL: C
@@ -34,4 +35,3 @@ exit_code: 1
❌ No worktree found for branch foo
❌ No worktree found for branch bar
❌ No worktree found for branch baz
-❌ Failed to remove 3 of 3 specified targets
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_nonexistent_branch.snap b/tests/snapshots/integration__integration_tests__remove__remove_nonexistent_branch.snap
new file mode 100644
index 000000000..8dbec42b8
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_nonexistent_branch.snap
@@ -0,0 +1,32 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - nonexistent
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ PATH: "[PATH]"
+ SOURCE_DATE_EPOCH: "1735776000"
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+❌ No worktree found for branch nonexistent
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_partial_success.snap b/tests/snapshots/integration__integration_tests__remove__remove_partial_success.snap
new file mode 100644
index 000000000..3bf939d12
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_partial_success.snap
@@ -0,0 +1,34 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - feature
+ - nonexistent
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ PATH: "[PATH]"
+ SOURCE_DATE_EPOCH: "1735776000"
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+🔄 Removing feature worktree & branch in background (same commit as main)
+❌ No worktree found for branch nonexistent