Skip to content

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

fix(remove): make --force flag work with dirty worktrees (#658) (#662)

Maximilian Roos9775cbd940f4
diff --git a/.claude/rules/cli-output-formatting.md b/.claude/rules/cli-output-formatting.md
index f34b4734e..5946e047b 100644
--- a/.claude/rules/cli-output-formatting.md
+++ b/.claude/rules/cli-output-formatting.md
@@ -140,6 +140,20 @@ behavior:
"Removing feature worktree in background; retaining branch"
```
+**Flag locality:** Place flag indicators adjacent to the concept they modify.
+Flags should appear immediately after the noun/action they affect, not at the
+end of the message:
+
+```rust
+// GOOD - (--force) is adjacent to "worktree" which it modifies
+"Removing feature worktree (--force) & branch in background (same commit as main, _)"
+// BAD - (--force) at end, disconnected from the worktree removal it enables
+"Removing feature worktree & branch in background (same commit as main, _) (--force)"
+```
+
+This principle ensures readers can immediately understand what each annotation
+modifies.
+
**Parallel structure:** Related messages should follow the same pattern:
```rust
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 10f9785c0..212b2152b 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -161,8 +161,10 @@ impl RepositoryCliExt for Repository {
return Err(GitError::CannotRemoveMainWorktree.into());
}
- // Ensure the working tree is clean
- target_wt.ensure_clean("remove worktree", branch_name.as_deref())?;
+ // Check working tree cleanliness (unless --force, which passes through to git)
+ if !force_worktree {
+ target_wt.ensure_clean("remove worktree", branch_name.as_deref())?;
+ }
// Compute main_path and changed_directory based on whether we're removing current
let (main_path, changed_directory) = if is_current {
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 43fdea336..13f632b6f 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -579,6 +579,8 @@ struct RemovalDisplayInfo {
branch_was_integrated: bool,
/// Whether to show the "unmerged, run -D" hint (foreground only, based on actual deletion)
show_unmerged_hint: bool,
+ /// Whether --force was used (for display purposes)
+ force_worktree: bool,
}
impl RemovalDisplayInfo {
@@ -590,6 +592,7 @@ impl RemovalDisplayInfo {
deletion_mode: BranchDeletionMode,
pre_computed_integration: Option<IntegrationReason>,
target_branch: Option<&str>,
+ force_worktree: bool,
) -> Self {
let (outcome, effective_target) = if deletion_mode.should_keep() {
(
@@ -614,6 +617,7 @@ impl RemovalDisplayInfo {
effective_target,
branch_was_integrated: pre_computed_integration.is_some(),
show_unmerged_hint: false, // Background mode never shows this hint
+ force_worktree,
}
}
@@ -624,6 +628,7 @@ impl RemovalDisplayInfo {
deletion_mode: BranchDeletionMode,
pre_computed_integration: Option<IntegrationReason>,
target_branch: Option<&str>,
+ force_worktree: bool,
) -> anyhow::Result<Self> {
let branch_was_integrated = pre_computed_integration.is_some();
@@ -648,6 +653,7 @@ impl RemovalDisplayInfo {
effective_target,
branch_was_integrated,
show_unmerged_hint,
+ force_worktree,
})
}
@@ -670,16 +676,23 @@ impl RemovalDisplayInfo {
&self.outcome,
self.effective_target.as_deref(),
);
+ let force_text = if self.force_worktree {
+ " (--force)"
+ } else {
+ ""
+ };
if is_background {
let flag_text = &flag_note.text;
let flag_after = flag_note.after_cyan();
let msg = if self.branch_deleted() {
cformat!(
- "<cyan>◎ Removing <bold>{branch_name}</> worktree & branch in background{flag_text}</>{flag_after}"
+ "<cyan>◎ Removing <bold>{branch_name}</> worktree{force_text} & branch in background{flag_text}</>{flag_after}"
)
} else {
- cformat!("<cyan>◎ Removing <bold>{branch_name}</> worktree in background</>")
+ cformat!(
+ "<cyan>◎ Removing <bold>{branch_name}</> worktree{force_text} in background</>"
+ )
};
Ok(super::print(FormattedMessage::new(msg))?)
} else {
@@ -687,10 +700,10 @@ impl RemovalDisplayInfo {
let flag_text = &flag_note.text;
let flag_after = flag_note.after_green();
cformat!(
- "<green>✓ Removed <bold>{branch_name}</> worktree & branch{flag_text}</>{flag_after}"
+ "<green>✓ Removed <bold>{branch_name}</> worktree{force_text} & branch{flag_text}</>{flag_after}"
)
} else {
- cformat!("<green>✓ Removed <bold>{branch_name}</> worktree</>")
+ cformat!("<green>✓ Removed <bold>{branch_name}</> worktree{force_text}</>")
};
Ok(super::print(FormattedMessage::new(msg))?)
}
@@ -832,6 +845,7 @@ fn handle_removed_worktree_output(
deletion_mode,
pre_computed_integration,
target_branch,
+ force_worktree,
);
display_info.print_message(branch_name, true)?;
@@ -892,6 +906,7 @@ fn handle_removed_worktree_output(
deletion_mode,
pre_computed_integration,
target_branch,
+ force_worktree,
)?;
display_info.print_message(branch_name, false)?;
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 0dcec7976..b458b5671 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -322,6 +322,115 @@ fn test_remove_by_name_dirty_target(mut repo: TestRepo) {
assert_cmd_snapshot!(make_snapshot_cmd(&repo, "remove", &["feature-dirty"], None));
}
+/// --force allows removal of dirty worktrees (issue #658)
+/// This test: untracked files, branch at same commit as main
+#[rstest]
+fn test_remove_force_with_untracked_files(mut repo: TestRepo) {
+ let worktree_path = repo.add_worktree("feature-untracked");
+
+ // Create an untracked file (like devbox.lock, .env, build artifacts)
+ std::fs::write(worktree_path.join("devbox.lock"), "untracked content").unwrap();
+
+ // Verify git sees it as untracked only
+ let status = repo
+ .git_command()
+ .args(["status", "--porcelain"])
+ .current_dir(&worktree_path)
+ .output()
+ .unwrap();
+ let status_output = String::from_utf8_lossy(&status.stdout);
+ assert!(
+ status_output.contains("?? devbox.lock"),
+ "File should be untracked"
+ );
+
+ // Remove with --force should succeed
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "remove",
+ &["--force", "feature-untracked"],
+ None
+ ));
+}
+
+/// --force allows removal of dirty worktrees (issue #658)
+/// This test: modified tracked file, branch ahead of main (unmerged)
+#[rstest]
+fn test_remove_force_with_modified_files(mut repo: TestRepo) {
+ let worktree_path = repo.add_worktree("feature-modified");
+
+ // Add a file to the worktree and commit it first
+ std::fs::write(worktree_path.join("tracked.txt"), "original content").unwrap();
+ repo.git_command()
+ .args(["add", "tracked.txt"])
+ .current_dir(&worktree_path)
+ .output()
+ .unwrap();
+ repo.git_command()
+ .args(["commit", "-m", "Add tracked file"])
+ .current_dir(&worktree_path)
+ .output()
+ .unwrap();
+
+ // Now modify the tracked file
+ std::fs::write(worktree_path.join("tracked.txt"), "modified content").unwrap();
+
+ // --force passes through to git, which allows this
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "remove",
+ &["--force", "feature-modified"],
+ None
+ ));
+}
+
+/// --force allows removal of dirty worktrees (issue #658)
+/// This test: staged (uncommitted) file, branch at same commit as main
+#[rstest]
+fn test_remove_force_with_staged_files(mut repo: TestRepo) {
+ let worktree_path = repo.add_worktree("feature-staged");
+
+ // Create and stage a new file (but don't commit)
+ std::fs::write(worktree_path.join("staged.txt"), "staged content").unwrap();
+ repo.git_command()
+ .args(["add", "staged.txt"])
+ .current_dir(&worktree_path)
+ .output()
+ .unwrap();
+
+ // --force passes through to git, which allows this
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "remove",
+ &["--force", "feature-staged"],
+ None
+ ));
+}
+
+/// --force + -D: dirty worktree AND unmerged branch
+#[rstest]
+fn test_remove_force_with_force_delete(mut repo: TestRepo) {
+ let worktree_path = repo.add_worktree("feature-dirty-unmerged");
+
+ // Make a commit so the branch is ahead of main (unmerged)
+ repo.git_command()
+ .args(["commit", "--allow-empty", "-m", "feature commit"])
+ .current_dir(&worktree_path)
+ .output()
+ .unwrap();
+
+ // Add untracked file to make the worktree dirty
+ std::fs::write(worktree_path.join("untracked.txt"), "dirty").unwrap();
+
+ // --force (dirty worktree) + -D (force delete unmerged branch)
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "remove",
+ &["--force", "-D", "feature-dirty-unmerged"],
+ None
+ ));
+}
+
#[rstest]
fn test_remove_multiple_worktrees(mut repo: TestRepo) {
// Create three worktrees
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_force_with_force_delete.snap b/tests/snapshots/integration__integration_tests__remove__remove_force_with_force_delete.snap
new file mode 100644
index 000000000..81db046a6
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_force_with_force_delete.snap
@@ -0,0 +1,38 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - "--force"
+ - "-D"
+ - feature-dirty-unmerged
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ 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
+ MOCK_CONFIG_DIR: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp22EH0v/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Removing feature-dirty-unmerged worktree (--force) & branch in background (--force-delete)
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_force_with_modified_files.snap b/tests/snapshots/integration__integration_tests__remove__remove_force_with_modified_files.snap
new file mode 100644
index 000000000..3c30b06f4
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_force_with_modified_files.snap
@@ -0,0 +1,38 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - "--force"
+ - feature-modified
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ 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
+ MOCK_CONFIG_DIR: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpZBmXa4/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Removing feature-modified worktree (--force) in background
+↳ Branch unmerged; to delete, run wt remove feature-modified -D
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_force_with_staged_files.snap b/tests/snapshots/integration__integration_tests__remove__remove_force_with_staged_files.snap
new file mode 100644
index 000000000..2a7a31d4b
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_force_with_staged_files.snap
@@ -0,0 +1,37 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - "--force"
+ - feature-staged
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ 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
+ MOCK_CONFIG_DIR: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpikz508/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Removing feature-staged worktree (--force) & branch in background (same commit as main, _)
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_force_with_untracked_files.snap b/tests/snapshots/integration__integration_tests__remove__remove_force_with_untracked_files.snap
new file mode 100644
index 000000000..bd5e51c55
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_force_with_untracked_files.snap
@@ -0,0 +1,37 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - "--force"
+ - feature-untracked
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ 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
+ MOCK_CONFIG_DIR: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmppcKJg1/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Removing feature-untracked worktree (--force) & branch in background (same commit as main, _)