Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: extract shared execute_removal for worktree removal (#1700)
Maximilian Roos848902434307
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex d4a3f35e2..386911342 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -23,15 +23,14 @@ use skim::prelude::*;use skim::reader::CommandCollector;use worktrunk::git::{Repository, current_or_recover};-use super::branch_deletion::delete_branch_if_safe;use super::handle_switch::{approve_switch_hooks, run_pre_switch_hooks, spawn_switch_background_hooks, switch_extra_vars,};use super::list::collect;use super::repository_ext::{RemoveTarget, RepositoryCliExt};use super::worktree::{- BranchDeletionMode, RemoveResult, SwitchBranchInfo, SwitchResult, execute_switch,- offer_bare_repo_worktree_path_fix, path_mismatch, plan_switch,+ BranchDeletionMode, RemoveResult, SwitchBranchInfo, SwitchResult, execute_removal,+ execute_switch, offer_bare_repo_worktree_path_fix, path_mismatch, plan_switch,};use crate::output::handle_switch_output;@@ -68,7 +67,7 @@ impl PickerCollector {/// Execute worktree removal silently: stop fsmonitor, remove worktree, delete branch.////// No output, no hooks, no cd directives — we're inside skim's TUI.- fn execute_removal(result: &RemoveResult) -> anyhow::Result<()> {+ fn do_removal(result: &RemoveResult) -> anyhow::Result<()> {let RemoveResult::RemovedWorktree {main_path,worktree_path,@@ -83,18 +82,15 @@ impl PickerCollector {};let repo = Repository::at(main_path)?;- let _ = repo- .worktree_at(worktree_path)- .run_command(&["fsmonitor--daemon", "stop"]);- repo.remove_worktree(worktree_path, *force_worktree)?;-- if let Some(branch) = branch_name- && !deletion_mode.should_keep()- {- let target = target_branch.as_deref().unwrap_or("HEAD");- let _ = delete_branch_if_safe(&repo, branch, target, deletion_mode.is_force());- }-+ // Branch deletion result intentionally ignored — best-effort in TUI context.+ execute_removal(+ &repo,+ worktree_path,+ branch_name.as_deref(),+ *deletion_mode,+ target_branch.as_deref(),+ *force_worktree,+ )?;Ok(())}}@@ -135,7 +131,7 @@ impl CommandCollector for PickerCollector {.repo.prepare_worktree_removal(target, BranchDeletionMode::SafeDelete, false, config).and_then(|result| {- Self::execute_removal(&result)?;+ Self::do_removal(&result)?;Ok(result)});match removal {@@ -750,7 +746,7 @@ pub mod tests {removed_commit: None,};- PickerCollector::execute_removal(&result).unwrap();+ PickerCollector::do_removal(&result).unwrap();assert!(!wt_path.exists(), "worktree should be removed");let output = Cmd::new("git")@@ -768,6 +764,6 @@ pub mod tests {deletion_mode: BranchDeletionMode::SafeDelete,pruned: false,};- PickerCollector::execute_removal(&result).unwrap();+ PickerCollector::do_removal(&result).unwrap();}}diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rsindex 4582aa598..71c8ac398 100644--- a/src/commands/worktree/mod.rs+++ b/src/commands/worktree/mod.rs@@ -84,6 +84,11 @@ mod resolve;mod switch;mod types;+use std::path::Path;++use super::branch_deletion::{BranchDeletionResult, delete_branch_if_safe};+use worktrunk::git::Repository;+// Re-export public types and functionspub use push::{handle_no_ff_merge, handle_push};pub(crate) use resolve::paths_match;@@ -96,3 +101,51 @@ pub use types::{BranchDeletionMode, MergeOperations, OperationMode, RemoveResult, SwitchBranchInfo, SwitchPlan,SwitchResult,};++/// Execute core worktree removal: stop fsmonitor, remove worktree, delete branch.+///+/// Performs the three git operations that constitute worktree removal:+/// 1. Stop fsmonitor daemon (best effort — prevents zombie daemons)+/// 2. Remove the git worktree+/// 3. Delete the branch if safe (conditional on `deletion_mode` and `branch_name`)+///+/// The outer `Result` covers worktree removal failures. The inner+/// `Option<Result<BranchDeletionResult>>` is the raw `delete_branch_if_safe` result,+/// preserved so callers can handle branch deletion failures independently:+/// - The picker ignores it (best-effort in TUI context)+/// - The output handler processes it for user-facing display+///+/// Returns `Ok(None)` when branch deletion was not attempted (no branch name,+/// or `deletion_mode.should_keep()`).+pub fn execute_removal(+ repo: &Repository,+ worktree_path: &Path,+ branch_name: Option<&str>,+ deletion_mode: BranchDeletionMode,+ target_branch: Option<&str>,+ force_worktree: bool,+) -> anyhow::Result<Option<anyhow::Result<BranchDeletionResult>>> {+ // Stop fsmonitor daemon (best effort — prevents zombie daemons when using+ // builtin fsmonitor). Must happen while the worktree path still exists.+ let _ = repo+ .worktree_at(worktree_path)+ .run_command(&["fsmonitor--daemon", "stop"]);++ // Remove the worktree+ repo.remove_worktree(worktree_path, force_worktree)?;++ // Delete branch if safe+ if let Some(branch) = branch_name+ && !deletion_mode.should_keep()+ {+ let target = target_branch.unwrap_or("HEAD");+ Ok(Some(delete_branch_if_safe(+ repo,+ branch,+ target,+ deletion_mode.is_force(),+ )))+ } else {+ Ok(None)+ }+}diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 20649dee0..0b0dc6854 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -19,7 +19,9 @@ use crate::commands::process::{HookLog, InternalOp, build_remove_command, build_remove_command_staged, generate_removing_path,spawn_detached,};-use crate::commands::worktree::{BranchDeletionMode, RemoveResult, SwitchBranchInfo, SwitchResult};+use crate::commands::worktree::{+ BranchDeletionMode, RemoveResult, SwitchBranchInfo, SwitchResult, execute_removal,+};use worktrunk::config::UserConfig;use worktrunk::git::GitError;use worktrunk::git::IntegrationReason;@@ -902,30 +904,28 @@ impl RemovalDisplayInfo {}/// Build display info from actual deletion result (foreground mode).- fn from_actual(- repo: &Repository,+ fn from_branch_result(+ branch_deletion: Option<anyhow::Result<BranchDeletionResult>>,branch_name: &str,- 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();- let (outcome, integration_target, show_unmerged_hint) = if !deletion_mode.should_keep() {- let check_target = target_branch.unwrap_or("HEAD");- let result =- delete_branch_if_safe(repo, branch_name, check_target, deletion_mode.is_force());- let (deletion, needs_hint) = handle_branch_deletion_result(result, branch_name, true)?;- // Only use integration_target for display if we had a real target (not "HEAD" fallback)- let display_target = target_branch.map(|_| deletion.integration_target);- (deletion.outcome, display_target, needs_hint)- } else {- (+ let (outcome, integration_target, show_unmerged_hint) = match branch_deletion {+ Some(result) => {+ let (deletion, needs_hint) =+ handle_branch_deletion_result(result, branch_name, true)?;+ // Only use integration_target for display if we had a real target (not "HEAD" fallback)+ let display_target = target_branch.map(|_| deletion.integration_target);+ (deletion.outcome, display_target, needs_hint)+ }+ None => (BranchDeletionOutcome::NotDeleted,target_branch.map(String::from),false,- )+ ),};Ok(Self {@@ -1131,18 +1131,20 @@ fn handle_removed_worktree_output(ctx: RemovedWorktreeOutputContext<'_>) -> anyhformat_path_for_display(worktree_path))));- let _ = repo- .worktree_at(worktree_path)- .run_command(&["fsmonitor--daemon", "stop"]);- 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(),- remaining_entries: list_remaining_entries(worktree_path),- error: err.to_string(),- }- .into());- }+ execute_removal(+ &repo,+ worktree_path,+ None,+ deletion_mode,+ target_branch,+ force_worktree,+ )+ .map_err(|err| GitError::WorktreeRemovalFailed {+ branch: path_dir_name(worktree_path).to_string(),+ path: worktree_path.to_path_buf(),+ remaining_entries: list_remaining_entries(worktree_path),+ error: err.to_string(),+ })?;eprintln!("{}",success_message(cformat!(@@ -1207,26 +1209,24 @@ fn handle_removed_worktree_output(ctx: RemovedWorktreeOutputContext<'_>) -> anyh);}- // Stop fsmonitor daemon first (best effort - ignore errors)- // This prevents zombie daemons from accumulating when using builtin fsmonitor- let _ = repo- .worktree_at(worktree_path)- .run_command(&["fsmonitor--daemon", "stop"]);-- 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(),- remaining_entries: list_remaining_entries(worktree_path),- error: err.to_string(),- }- .into());- }-- let display_info = RemovalDisplayInfo::from_actual(+ let branch_result = execute_removal(&repo,- branch_name,+ worktree_path,+ Some(branch_name),deletion_mode,+ target_branch,+ force_worktree,+ )+ .map_err(|err| GitError::WorktreeRemovalFailed {+ branch: branch_name.into(),+ path: worktree_path.to_path_buf(),+ remaining_entries: list_remaining_entries(worktree_path),+ error: err.to_string(),+ })?;++ let display_info = RemovalDisplayInfo::from_branch_result(+ branch_result,+ branch_name,pre_computed_integration,target_branch,force_worktree,