Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Add --force flag to wt remove for worktrees with untracked files (#310)
Maximilian Roos7e5057b1efae
diff --git a/docs/content/remove.md b/docs/content/remove.mdindex 99cf7ee9c..9652fd4e6 100644--- a/docs/content/remove.md+++ b/docs/content/remove.md@@ -92,8 +92,11 @@ Usage: <b><span class=c>wt remove</span></b> <span class=c>[OPTIONS]</span> <spa<b><span class=c>--no-verify</span></b>Skip hooks- <b><span class=c>--force</span></b>- Skip approval prompts+ <b><span class=c>-f</span></b>, <b><span class=c>--force</span></b>+ Force removal++ Skip approval prompts, and remove worktrees even if they contain+ untracked files (like build artifacts).<b><span class=c>-h</span></b>, <b><span class=c>--help</span></b>Print help (see a summary with '-h')diff --git a/src/cli.rs b/src/cli.rsindex aa3bf77d2..d1ee32379 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -2330,8 +2330,11 @@ Removal runs in the background by default (returns immediately). Logs are writte#[arg(long = "no-verify", action = clap::ArgAction::SetFalse, default_value_t = true)]verify: bool,- /// Skip approval prompts- #[arg(long)]+ /// Force removal+ ///+ /// Skip approval prompts, and remove worktrees even if they contain+ /// untracked files (like build artifacts).+ #[arg(short = 'f', long)]force: bool,},diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 351790b27..7cb7c0665 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -246,6 +246,9 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {deletion_mode: BranchDeletionMode::SafeDelete,target_branch: Some(target_branch.clone()),integration_reason,+ // After a successful merge, force removal since any untracked files+ // (build artifacts) are no longer needed+ force_worktree: true,};// Run hooks during merge removal (pass through verify flag)// Approval was handled at the gate (MergeCommandCollector)diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex d857e577f..a13d6a343 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -27,6 +27,7 @@ pub trait RepositoryCliExt {&self,branch_name: &str,deletion_mode: BranchDeletionMode,+ force_worktree: bool,) -> anyhow::Result<RemoveResult>;/// Remove the current worktree (handles detached HEAD state).@@ -38,6 +39,7 @@ pub trait RepositoryCliExt {fn remove_current_worktree(&self,deletion_mode: BranchDeletionMode,+ force_worktree: bool,) -> anyhow::Result<RemoveResult>;/// Prepare the target worktree for push by auto-stashing non-overlapping changes when safe.@@ -86,6 +88,7 @@ impl RepositoryCliExt for Repository {&self,branch_name: &str,deletion_mode: BranchDeletionMode,+ force_worktree: bool,) -> anyhow::Result<RemoveResult> {let worktree_path = match self.worktree_for_branch(branch_name)? {Some(path) => path,@@ -165,12 +168,14 @@ impl RepositoryCliExt for Repository {deletion_mode,target_branch,integration_reason,+ force_worktree,})}fn remove_current_worktree(&self,deletion_mode: BranchDeletionMode,+ force_worktree: bool,) -> anyhow::Result<RemoveResult> {// Cannot remove the main working tree (only linked worktrees can be removed)if !self.is_in_worktree()? {@@ -220,6 +225,7 @@ impl RepositoryCliExt for Repository {deletion_mode,target_branch,integration_reason,+ force_worktree,})}diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex bbcdb5c8c..8ebcd9b0f 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -452,6 +452,8 @@ pub enum RemoveResult {/// in background mode (background git operations can hold locks that cause/// subsequent integration checks to fail).integration_reason: Option<worktrunk::git::IntegrationReason>,+ /// Force git worktree removal even with untracked files.+ force_worktree: bool,},/// Branch exists but has no worktree - attempt branch deletion onlyBranchOnly {@@ -742,6 +744,7 @@ pub fn handle_remove(worktree_name: &str,no_delete_branch: bool,force_delete: bool,+ force_worktree: bool,background: bool,) -> anyhow::Result<RemoveResult> {let repo = Repository::current();@@ -756,6 +759,7 @@ pub fn handle_remove(repo.remove_worktree_by_name(worktree_name,BranchDeletionMode::from_flags(no_delete_branch, force_delete),+ force_worktree,)}@@ -766,6 +770,7 @@ pub fn handle_remove(pub fn handle_remove_current(no_delete_branch: bool,force_delete: bool,+ force_worktree: bool,background: bool,) -> anyhow::Result<RemoveResult> {let repo = Repository::current();@@ -775,10 +780,10 @@ pub fn handle_remove_current(crate::output::print(progress_message("Removing current worktree..."))?;}- repo.remove_current_worktree(BranchDeletionMode::from_flags(- no_delete_branch,- force_delete,- ))+ repo.remove_current_worktree(+ BranchDeletionMode::from_flags(no_delete_branch, force_delete),+ force_worktree,+ )}/// Handle removing a worktree by path (for detached non-current worktrees).@@ -790,6 +795,7 @@ pub fn handle_remove_current(pub fn handle_remove_by_path(path: &std::path::Path,branch: Option<String>,+ force_worktree: bool,background: bool,) -> anyhow::Result<RemoveResult> {let repo = Repository::current();@@ -821,6 +827,7 @@ pub fn handle_remove_by_path(deletion_mode: BranchDeletionMode::Keep, // Can't delete branch for detached worktreetarget_branch: None,integration_reason: None, // Not applicable for detached worktrees+ force_worktree,})}@@ -1233,6 +1240,7 @@ mod tests {deletion_mode: BranchDeletionMode::SafeDelete,target_branch: Some("main".to_string()),integration_reason: Some(worktrunk::git::IntegrationReason::SameCommit),+ force_worktree: false,};match result {RemoveResult::RemovedWorktree {@@ -1243,6 +1251,7 @@ mod tests {deletion_mode,target_branch,integration_reason,+ force_worktree,} => {assert_eq!(main_path.to_str().unwrap(), "/main");assert_eq!(worktree_path.to_str().unwrap(), "/worktree");@@ -1252,6 +1261,7 @@ mod tests {assert!(!deletion_mode.is_force());assert_eq!(target_branch.as_deref(), Some("main"));assert!(integration_reason.is_some());+ assert!(!force_worktree);}_ => panic!("Expected RemovedWorktree variant"),}@@ -1286,15 +1296,18 @@ mod tests {deletion_mode: BranchDeletionMode::ForceDelete,target_branch: None,integration_reason: None, // Force delete skips integration check+ force_worktree: true,};match result {RemoveResult::RemovedWorktree {branch_name,deletion_mode,+ force_worktree,..} => {assert!(branch_name.is_none());assert!(deletion_mode.is_force());+ assert!(force_worktree);}_ => panic!("Expected RemovedWorktree variant"),}diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 72685a160..4779d8cb8 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -1425,13 +1425,22 @@ impl Repository {}/// Remove a worktree at the specified path.- pub fn remove_worktree(&self, path: &std::path::Path) -> anyhow::Result<()> {+ ///+ /// When `force` is true, passes `--force` to `git worktree remove`,+ /// allowing removal even when the worktree contains untracked files+ /// (like build artifacts such as `.vite/` or `node_modules/`).+ pub fn remove_worktree(&self, path: &std::path::Path, force: bool) -> anyhow::Result<()> {let path_str = path.to_str().ok_or_else(|| {anyhow::Error::from(GitError::Other {message: format!("Worktree path contains invalid UTF-8: {}", path.display()),})})?;- self.run_command(&["worktree", "remove", path_str])?;+ let mut args = vec!["worktree", "remove"];+ if force {+ args.push("--force");+ }+ args.push(path_str);+ self.run_command(&args)?;Ok(())}diff --git a/src/main.rs b/src/main.rsindex f9f85b286..a4a290a95 100644--- a/src/main.rs+++ b/src/main.rs@@ -1380,8 +1380,9 @@ fn main() {if worktrees.is_empty() {// No worktrees specified, remove current worktree// Uses path-based removal to handle detached HEAD state- let result = handle_remove_current(!delete_branch, force_delete, background)- .context("Failed to remove worktree")?;+ let result =+ handle_remove_current(!delete_branch, force_delete, force, background)+ .context("Failed to remove worktree")?;// Approval was handled at the gate// Post-switch hooks are spawned internally by handle_remove_outputhandle_remove_output(&result, background, verify)@@ -1430,6 +1431,7 @@ fn main() {branch_name,!delete_branch,force_delete,+ force,background,) {Ok(result) => {@@ -1442,7 +1444,7 @@ fn main() {}} else {// Non-current worktree is detached - remove by path (no branch to delete)- match handle_remove_by_path(path, None, background) {+ match handle_remove_by_path(path, None, force, background) {Ok(result) => {handle_remove_output(&result, background, verify)?;}@@ -1456,7 +1458,8 @@ fn main() {// Handle branch-only cases (no worktree)for branch in &branch_only {- match handle_remove(branch, !delete_branch, force_delete, background) {+ match handle_remove(branch, !delete_branch, force_delete, force, background)+ {Ok(result) => {handle_remove_output(&result, background, verify)?;}@@ -1470,7 +1473,8 @@ fn main() {// Remove current worktree last (if it was in the list)// Post-switch hooks are spawned internally by handle_remove_outputif let Some((_path, _branch)) = current {- match handle_remove_current(!delete_branch, force_delete, background) {+ match handle_remove_current(!delete_branch, force_delete, force, background)+ {Ok(result) => {handle_remove_output(&result, background, verify)?;}diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 0cbe33bc5..af3baa1c5 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -412,7 +412,14 @@ pub fn execute_user_command(command: &str) -> anyhow::Result<()> {/// `branch_to_delete` is the branch to delete after removing the worktree./// Pass `None` for detached HEAD or when branch should be retained./// This decision is computed upfront (checking if branch is merged) before spawning the background process.-fn build_remove_command(worktree_path: &std::path::Path, branch_to_delete: Option<&str>) -> String {+///+/// `force_worktree` adds `--force` to `git worktree remove`, allowing removal+/// even when the worktree contains untracked files (like build artifacts).+fn build_remove_command(+ worktree_path: &std::path::Path,+ branch_to_delete: Option<&str>,+ force_worktree: bool,+) -> String {use shell_escape::escape;let worktree_path_str = worktree_path.to_string_lossy();@@ -435,18 +442,20 @@ fn build_remove_command(worktree_path: &std::path::Path, branch_to_delete: Optioworktree_escaped);+ let force_flag = if force_worktree { " --force" } else { "" };+match branch_to_delete {Some(branch_name) => {let branch_escaped = escape(branch_name.into());format!(- "{} && {} && git worktree remove {} && git branch -D {}",- delay, stop_fsmonitor, worktree_escaped, branch_escaped+ "{} && {} && git worktree remove{} {} && git branch -D {}",+ delay, stop_fsmonitor, force_flag, worktree_escaped, branch_escaped)}None => {format!(- "{} && {} && git worktree remove {}",- delay, stop_fsmonitor, worktree_escaped+ "{} && {} && git worktree remove{} {}",+ delay, stop_fsmonitor, force_flag, worktree_escaped)}}@@ -469,6 +478,7 @@ pub fn handle_remove_output(deletion_mode,target_branch,integration_reason,+ force_worktree,} => handle_removed_worktree_output(main_path,worktree_path,@@ -477,6 +487,7 @@ pub fn handle_remove_output(*deletion_mode,target_branch.as_deref(),*integration_reason,+ *force_worktree,background,verify,),@@ -570,6 +581,7 @@ fn handle_removed_worktree_output(deletion_mode: BranchDeletionMode,target_branch: Option<&str>,pre_computed_integration: Option<IntegrationReason>,+ force_worktree: bool,background: bool,verify: bool,) -> anyhow::Result<()> {@@ -604,7 +616,7 @@ fn handle_removed_worktree_output(super::print(progress_message("Removing worktree in background (detached HEAD, no branch to delete)",))?;- let remove_command = build_remove_command(worktree_path, None);+ let remove_command = build_remove_command(worktree_path, None, force_worktree);spawn_detached(&repo,main_path,@@ -616,7 +628,7 @@ fn handle_removed_worktree_output(} else {let target_repo = worktrunk::git::Repository::at(worktree_path);let _ = target_repo.run_command(&["fsmonitor--daemon", "stop"]);- if let Err(err) = repo.remove_worktree(worktree_path) {+ if let Err(err) = repo.remove_worktree(worktree_path, force_worktree) {return Err(GitError::WorktreeRemovalFailed {branch: path_dir_name(worktree_path).to_string(),path: worktree_path.to_path_buf(),@@ -710,8 +722,11 @@ fn handle_removed_worktree_output(print_switch_message_if_changed(changed_directory, main_path)?;// Build command with the decision we already made- let remove_command =- build_remove_command(worktree_path, should_delete_branch.then_some(branch_name));+ let remove_command = build_remove_command(+ worktree_path,+ should_delete_branch.then_some(branch_name),+ force_worktree,+ );// Spawn the removal in background - runs from main_path (where we cd'd to)spawn_detached(@@ -735,7 +750,7 @@ fn handle_removed_worktree_output(let _ = target_repo.run_command(&["fsmonitor--daemon", "stop"]);// Track whether branch was actually deleted (will be computed based on deletion attempt)- if let Err(err) = repo.remove_worktree(worktree_path) {+ if let Err(err) = repo.remove_worktree(worktree_path, force_worktree) {return Err(GitError::WorktreeRemovalFailed {branch: branch_name.into(),path: worktree_path.to_path_buf(),@@ -1214,21 +1229,32 @@ mod tests {fn test_build_remove_command() {let path = PathBuf::from("/tmp/test-worktree");- // Without branch deletion- let cmd = build_remove_command(&path, None);+ // Without branch deletion, without force+ let cmd = build_remove_command(&path, None, false);assert!(cmd.contains("git worktree remove"));assert!(cmd.contains("/tmp/test-worktree"));assert!(!cmd.contains("branch -D"));+ assert!(!cmd.contains("--force"));- // With branch deletion- let cmd = build_remove_command(&path, Some("feature-branch"));+ // With branch deletion, without force+ let cmd = build_remove_command(&path, Some("feature-branch"), false);assert!(cmd.contains("git worktree remove"));assert!(cmd.contains("git branch -D"));assert!(cmd.contains("feature-branch"));+ assert!(!cmd.contains("--force"));++ // With force flag+ let cmd = build_remove_command(&path, None, true);+ assert!(cmd.contains("git worktree remove --force"));++ // With branch deletion and force+ let cmd = build_remove_command(&path, Some("feature-branch"), true);+ assert!(cmd.contains("git worktree remove --force"));+ assert!(cmd.contains("git branch -D"));// Shell escaping for special characterslet special_path = PathBuf::from("/tmp/test worktree");- let cmd = build_remove_command(&special_path, Some("feature/branch"));+ let cmd = build_remove_command(&special_path, Some("feature/branch"), false);assert!(cmd.contains("worktree remove"));}diff --git a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap b/tests/snapshots/integration__integration_tests__help__help_remove_long.snapindex e9162c465..dea7f34be 100644--- a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap@@ -39,8 +39,10 @@ Usage: [1m[36mwt remove[0m [36m[OPTIONS][0m [36m[WORKTREES]...[1m[36m--no-verifySkip hooks- [1m[36m--force- Skip approval prompts+ [1m[36m-f[0m, [1m[36m--force+ Force removal++ Skip approval prompts, and remove worktrees even if they contain untracked files (like build artifacts).[1m[36m-h[0m, [1m[36m--helpPrint help (see a summary with '-h')diff --git a/tests/snapshots/integration__integration_tests__help__help_remove_short.snap b/tests/snapshots/integration__integration_tests__help__help_remove_short.snapindex 92f863805..6505719db 100644--- a/tests/snapshots/integration__integration_tests__help__help_remove_short.snap+++ b/tests/snapshots/integration__integration_tests__help__help_remove_short.snap@@ -30,7 +30,7 @@ Usage: [1m[36mwt remove[0m [36m[OPTIONS][0m [36m[WORKTREES]...[1m[36m-D[0m, [1m[36m--force-delete[0m Delete unmerged branches[1m[36m--no-background[0m Run removal in foreground[1m[36m--no-verify[0m Skip hooks- [1m[36m--force[0m Skip approval prompts+ [1m[36m-f[0m, [1m[36m--force[0m Force removal[1m[36m-h[0m, [1m[36m--help[0m Print help (see more with '--help')[1m[32mGlobal Options: