Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Expose worktree removal API from the library crate (#2227)
Worktrunk Bot0b2504ab263e
diff --git a/src/commands/branch_deletion.rs b/src/commands/branch_deletion.rsdeleted file mode 100644index 9682dc32c..000000000--- a/src/commands/branch_deletion.rs+++ /dev/null@@ -1,86 +0,0 @@-//! Branch deletion logic for worktree operations.-//!-//! This module handles the decision-making around whether a branch can be safely-//! deleted after its worktree is removed. It checks if the branch's content has-//! been integrated into the target branch.--use worktrunk::git::{IntegrationReason, Repository};--/// Outcome of a branch deletion attempt.-pub enum BranchDeletionOutcome {- /// Branch was not deleted (not integrated and not forced)- NotDeleted,- /// Branch was force-deleted without integration check- ForceDeleted,- /// Branch was deleted because it was integrated- Integrated(IntegrationReason),-}--/// Result of a branch deletion attempt.-pub struct BranchDeletionResult {- pub outcome: BranchDeletionOutcome,- /// The target that was actually checked against (may be upstream if ahead of local)- pub integration_target: String,-}--/// Attempt to delete a branch if it's integrated or force_delete is set.-///-/// Returns `BranchDeletionResult` with:-/// - `outcome`: Whether/why deletion occurred-/// - `integration_target`: The ref checked against (may be upstream if ahead of local)-pub fn delete_branch_if_safe(- repo: &Repository,- branch_name: &str,- target: &str,- force_delete: bool,-) -> anyhow::Result<BranchDeletionResult> {- // Force-delete: skip integration check entirely (matches compute_integration_reason- // behavior for the Worktree path). The user explicitly chose -D.- if force_delete {- repo.run_command(&["branch", "-D", branch_name])?;- return Ok(BranchDeletionResult {- outcome: BranchDeletionOutcome::ForceDeleted,- integration_target: target.to_string(),- });- }-- let (effective_target, reason) = repo.integration_reason(branch_name, target)?;-- let outcome = match reason {- Some(r) => {- repo.run_command(&["branch", "-D", branch_name])?;- BranchDeletionOutcome::Integrated(r)- }- None => BranchDeletionOutcome::NotDeleted,- };-- Ok(BranchDeletionResult {- outcome,- integration_target: effective_target,- })-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn test_branch_deletion_outcome_matching() {- // Ensure the match patterns work correctly- let outcomes = [- (BranchDeletionOutcome::NotDeleted, false),- (BranchDeletionOutcome::ForceDeleted, true),- (- BranchDeletionOutcome::Integrated(IntegrationReason::SameCommit),- true,- ),- ];- for (outcome, expected_deleted) in outcomes {- let deleted = matches!(- outcome,- BranchDeletionOutcome::ForceDeleted | BranchDeletionOutcome::Integrated(_)- );- assert_eq!(deleted, expected_deleted);- }- }-}diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 98b70517d..35d233df5 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -15,9 +15,9 @@ use super::repository_ext::{RepositoryCliExt, check_not_default_branch, compute_integration_reason, is_primary_worktree,};use super::worktree::{- BranchDeletionMode, MergeOperations, RemoveResult, handle_no_ff_merge, handle_push,- path_mismatch,+ MergeOperations, RemoveResult, handle_no_ff_merge, handle_push, path_mismatch,};+use worktrunk::git::BranchDeletionMode;/// Options for the merge command///diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex b0d0d1ee1..1a69b7db4 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -1,5 +1,4 @@mod alias;-pub(crate) mod branch_deletion;pub(crate) mod command_approval;pub(crate) mod command_executor;pub(crate) mod commit;diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 15b71397b..dd19b532a 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -23,7 +23,6 @@ use skim::prelude::*;use skim::reader::CommandCollector;use worktrunk::git::{Repository, current_or_recover};-use super::branch_deletion::delete_branch_if_safe;use super::command_executor::FailureStrategy;use super::handle_switch::{approve_switch_hooks, run_pre_switch_hooks, spawn_switch_background_hooks, switch_extra_vars,@@ -33,11 +32,14 @@ use super::list::collect;use super::repository_ext::{RemoveTarget, RepositoryCliExt};use super::worktree::hooks::PostRemoveContext;use super::worktree::{- BranchDeletionMode, RemoveResult, SwitchBranchInfo, SwitchResult, execute_removal,- execute_switch, offer_bare_repo_worktree_path_fix, path_mismatch, plan_switch,+ RemoveResult, SwitchBranchInfo, SwitchResult, execute_switch,+ offer_bare_repo_worktree_path_fix, path_mismatch, plan_switch,};use crate::commands::command_executor::CommandContext;use crate::output::handle_switch_output;+use worktrunk::git::{+ BranchDeletionMode, RemoveOptions, delete_branch_if_safe, remove_worktree_with_cleanup,+};use items::{HeaderSkimItem, PreviewCache, WorktreeSkimItem};use preview::{PreviewLayout, PreviewMode, PreviewState};@@ -121,13 +123,15 @@ impl PickerCollector {None, // no display path in TUI context)?;- let output = execute_removal(+ let output = remove_worktree_with_cleanup(&repo,worktree_path,- branch_name.as_deref(),- *deletion_mode,- target_branch.as_deref(),- *force_worktree,+ RemoveOptions {+ branch: branch_name.clone(),+ deletion_mode: *deletion_mode,+ target_branch: target_branch.clone(),+ force_worktree: *force_worktree,+ },)?;if let Some(staged) = output.staged_path {let _ = std::fs::remove_dir_all(&staged);@@ -748,8 +752,9 @@ fn resolve_identifier(pub mod tests {use super::preview::{PreviewLayout, PreviewMode, PreviewStateData};use super::{PickerAction, PickerCollector, resolve_identifier};- use crate::commands::worktree::{BranchDeletionMode, RemoveResult};+ use crate::commands::worktree::RemoveResult;use std::fs;+ use worktrunk::git::BranchDeletionMode;#[test]fn test_preview_state_data_roundtrip() {diff --git a/src/commands/process.rs b/src/commands/process.rsindex 1bb6b2506..dd8fcab82 100644--- a/src/commands/process.rs+++ b/src/commands/process.rs@@ -428,23 +428,6 @@ fn spawn_detached_exec_windows(Ok(())}-/// Generate a staging path for worktree removal.-///-/// Places the staging directory inside `.git/wt/trash/` so it is hidden from the-/// user's workspace. For the main worktree, `.git/` is on the same filesystem,-/// so `rename()` is an instant metadata operation. Linked worktrees on different-/// mount points will get EXDEV and fall back to legacy removal.-///-/// Format: `<wt/trash>/<name>-<timestamp>`-pub fn generate_removing_path(trash_dir: &Path, worktree_path: &Path) -> PathBuf {- let timestamp = epoch_now();- let name = worktree_path- .file_name()- .map(|n| n.to_string_lossy())- .unwrap_or_default();- trash_dir.join(format!("{}-{}", name, timestamp))-}-/// How old a `.git/wt/trash/` entry must be before [`sweep_stale_trash`] deletes it.pub const TRASH_STALE_THRESHOLD_SECS: u64 = 24 * 60 * 60;@@ -497,7 +480,7 @@ pub fn sweep_stale_trash(repo: &Repository) {////// Entries whose filename can't be parsed as `<name>-<timestamp>` are skipped —/// the sweep only touches directories worktrunk created via-/// [`generate_removing_path`].+/// [`worktrunk::git::remove::stage_worktree_removal`].fn collect_stale_trash_entries(trash_dir: &Path, now: u64, threshold_secs: u64) -> Vec<PathBuf> {let Ok(read_dir) = fs::read_dir(trash_dir) else {return Vec::new();@@ -516,10 +499,10 @@ fn collect_stale_trash_entries(trash_dir: &Path, now: u64, threshold_secs: u64)/// Extract the Unix timestamp suffix from a trash entry filename.///-/// Filenames produced by [`generate_removing_path`] have the form-/// `<name>-<timestamp>`, where timestamp is a bare unsigned integer in Unix-/// epoch seconds. The worktree name may contain hyphens, so splitting from the-/// right and parsing the tail is unambiguous.+/// Filenames produced by [`worktrunk::git::remove::stage_worktree_removal`]+/// have the form `<name>-<timestamp>`, where timestamp is a bare unsigned+/// integer in Unix epoch seconds. The worktree name may contain hyphens, so+/// splitting from the right and parsing the tail is unambiguous.fn parse_trash_entry_timestamp(name: &str) -> Option<u64> {let (_, suffix) = name.rsplit_once('-')?;suffix.parse::<u64>().ok()@@ -830,28 +813,6 @@ mod tests {assert_snapshot!(build_remove_command(&special_path, Some("feature/branch"), false, true), @"sleep 1 && { git -C '/tmp/test worktree' fsmonitor--daemon stop 2>/dev/null || true; } && git worktree remove '/tmp/test worktree' && git branch -D feature/branch");}- #[test]- fn test_generate_removing_path() {- let trash_dir = PathBuf::from("/tmp/repo/.git/wt/trash");- let path = PathBuf::from("/tmp/my-project.feature");- let removing_path = generate_removing_path(&trash_dir, &path);-- // Should be inside the trash directory- assert_eq!(removing_path.parent(), Some(trash_dir.as_path()));-- // Should have the expected prefix- let name = removing_path.file_name().unwrap().to_string_lossy();- assert!(name.starts_with("my-project.feature-"), "got: {}", name);-- // Should have a timestamp suffix (digits only after the prefix)- let timestamp_part = name.trim_start_matches("my-project.feature-");- assert!(- timestamp_part.chars().all(|c| c.is_ascii_digit()),- "timestamp part should be numeric: {}",- timestamp_part- );- }-#[test]fn test_build_remove_command_staged() {let staged_path = PathBuf::from("/tmp/repo/.git/wt/trash/my-project.feature-1234567890");diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex 54fe1b53f..975d59a02 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -2,12 +2,13 @@ use std::path::{Path, PathBuf};use std::process;use std::time::{SystemTime, UNIX_EPOCH};-use super::worktree::{BranchDeletionMode, RemoveResult, path_mismatch};+use super::worktree::{RemoveResult, path_mismatch};use anyhow::{Context, bail};use color_print::cformat;use worktrunk::config::UserConfig;use worktrunk::git::{- GitError, IntegrationReason, Repository, WorktreeInfo, parse_porcelain_z, parse_untracked_files,+ BranchDeletionMode, GitError, IntegrationReason, Repository, WorktreeInfo, parse_porcelain_z,+ parse_untracked_files,};use worktrunk::path::format_path_for_display;use worktrunk::styling::{eprintln, format_with_gutter, progress_message, warning_message};diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 05ad0c7bf..6a57911b1 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -42,8 +42,8 @@ use super::hooks::{HookCommandSpec, prepare_background_hooks, run_hook_with_filter, spawn_hook_pipeline,};use super::repository_ext::{RemoveTarget, RepositoryCliExt};-use super::worktree::BranchDeletionMode;use crate::output::handle_remove_output;+use worktrunk::git::BranchDeletionMode;/// Handle `wt step commit` command///diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rsindex 058cd26d0..9a77af2dd 100644--- a/src/commands/worktree/mod.rs+++ b/src/commands/worktree/mod.rs@@ -87,12 +87,6 @@ mod resolve;mod switch;mod types;-use std::path::{Path, PathBuf};--use super::branch_deletion::{BranchDeletionResult, delete_branch_if_safe};-use super::process::generate_removing_path;-use worktrunk::git::Repository;-// Re-export public types and functionspub use push::{handle_no_ff_merge, handle_push};pub(crate) use resolve::paths_match;@@ -102,97 +96,5 @@ pub use resolve::{};pub use switch::{execute_switch, plan_switch};pub use types::{- BranchDeletionMode, MergeOperations, OperationMode, RemoveResult, SwitchBranchInfo, SwitchPlan,- SwitchResult,+ MergeOperations, OperationMode, RemoveResult, SwitchBranchInfo, SwitchPlan, SwitchResult,};--/// Execute core worktree removal: stop fsmonitor, remove worktree, delete branch.-///-/// Uses the fast path (rename into `.git/wt/trash/` + prune) when possible,-/// falling back to `git worktree remove` on cross-filesystem setups.-/// On the fast path the directory disappears instantly; the caller is responsible-/// for cleaning up the staged trash entry (returned via `staged_path`).-///-/// Called from the synchronous (foreground) removal path and from the TUI picker.-/// The background removal path (`output::handlers::spawn_background_removal`)-/// uses `stage_worktree_removal` directly so it can defer the `rm -rf` to a-/// detached process. See `handle_remove_command` in `main.rs` for the full-/// `wt remove` command flow.-///-/// `branch_result` is the raw `delete_branch_if_safe` outcome, 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-///-/// `branch_result` is `None` when deletion was not attempted (no branch name,-/// or `deletion_mode.should_keep()`).-pub struct RemovalOutput {- pub branch_result: Option<anyhow::Result<BranchDeletionResult>>,- /// Path to the staged trash directory (fast path only). Caller should- /// `remove_dir_all` this — either synchronously or in the background.- pub staged_path: Option<PathBuf>,-}--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<RemovalOutput> {- // 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"]);-- // Fast path: rename into .git/wt/trash/ (instant on same filesystem),- // then prune git metadata. Falls back to `git worktree remove` if the- // rename fails (cross-filesystem, permissions, Windows file locking).- let staged_path = stage_worktree_removal(repo, worktree_path);- if staged_path.is_none() {- repo.remove_worktree(worktree_path, force_worktree)?;- }-- // Delete branch if safe- let branch_result = if let Some(branch) = branch_name- && !deletion_mode.should_keep()- {- let target = target_branch.unwrap_or("HEAD");- Some(delete_branch_if_safe(- repo,- branch,- target,- deletion_mode.is_force(),- ))- } else {- None- };-- Ok(RemovalOutput {- branch_result,- staged_path,- })-}--/// Rename a worktree into `.git/wt/trash/` and prune git metadata.-///-/// Returns `Some(staged_path)` on success, `None` if the rename failed.-/// Used internally by `execute_removal` and by the output handler's-/// `execute_instant_removal_or_fallback` (which builds shell command strings-/// and adds a placeholder directory — needs the raw staged path).-pub(crate) fn stage_worktree_removal(repo: &Repository, worktree_path: &Path) -> Option<PathBuf> {- let trash_dir = repo.wt_trash_dir();- let _ = std::fs::create_dir_all(&trash_dir);- let staged_path = generate_removing_path(&trash_dir, worktree_path);-- if std::fs::rename(worktree_path, &staged_path).is_ok() {- if let Err(e) = repo.prune_worktrees() {- log::debug!("Failed to prune worktrees after rename: {e}");- }- Some(staged_path)- } else {- None- }-}diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rsindex 33a333b7c..edbd92f92 100644--- a/src/commands/worktree/types.rs+++ b/src/commands/worktree/types.rs@@ -4,7 +4,7 @@use std::path::{Path, PathBuf};-use worktrunk::git::RefType;+use worktrunk::git::{BranchDeletionMode, RefType};/// Flags indicating which merge operations occurred#[derive(Debug, Clone, Copy)]@@ -137,45 +137,6 @@ impl SwitchPlan {}}-/// How the branch should be handled after worktree removal.-///-/// This enum replaces the previous boolean flag pair,-/// making the three valid states explicit and preventing invalid combinations.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum BranchDeletionMode {- /// Keep the branch regardless of merge status (--no-delete-branch flag).- Keep,- /// Delete the branch only if it's fully merged into the target branch (default).- SafeDelete,- /// Delete the branch even if it's not merged (-D flag).- ForceDelete,-}--impl BranchDeletionMode {- /// Create from CLI flags.- ///- /// `--no-delete-branch` takes precedence over `-D` (force delete).- pub fn from_flags(keep_branch: bool, force_delete: bool) -> Self {- if keep_branch {- Self::Keep- } else if force_delete {- Self::ForceDelete- } else {- Self::SafeDelete- }- }-- /// Whether the branch should be kept (not deleted).- pub fn should_keep(&self) -> bool {- matches!(self, Self::Keep)- }-- /// Whether to force delete even if not merged.- pub fn is_force(&self) -> bool {- matches!(self, Self::ForceDelete)- }-}-/// Result of a worktree remove operationpub enum RemoveResult {/// Removed worktree and changed directory (if needed)diff --git a/src/git/mod.rs b/src/git/mod.rsindex 320a91736..07752389c 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -8,6 +8,7 @@ mod error;mod parse;pub mod recover;pub mod remote_ref;+pub mod remove;mod repository;mod url;@@ -56,6 +57,10 @@ pub use error::{};pub use parse::{parse_porcelain_z, parse_untracked_files};pub use recover::{current_or_recover, cwd_removed_hint};+pub use remove::{+ BranchDeletionMode, BranchDeletionOutcome, BranchDeletionResult, RemovalOutput, RemoveOptions,+ delete_branch_if_safe, remove_worktree_with_cleanup, stage_worktree_removal,+};pub use repository::{Branch, Repository, ResolvedWorktree, WorkingTree, set_base_path};pub use url::GitRemoteUrl;pub use url::parse_owner_repo;diff --git a/src/git/remove.rs b/src/git/remove.rsnew file mode 100644index 000000000..bfffa2a03--- /dev/null+++ b/src/git/remove.rs@@ -0,0 +1,398 @@+//! Worktree removal with fast-path trash staging and safe branch deletion.+//!+//! This is the canonical removal flow used by `wt remove`, `wt merge --remove`,+//! and the TUI picker. External tooling (e.g. `worktrunk-sync`) can call it via+//! [`remove_worktree_with_cleanup`] to get the same semantics without+//! reimplementing the fsmonitor cleanup, trash-path staging, and+//! integration-check branch deletion.+//!+//! # What happens during removal+//!+//! 1. **fsmonitor daemon stopped** (best effort). `git fsmonitor--daemon stop`+//! runs against the target worktree before its path disappears, preventing+//! zombie daemons on platforms that use builtin fsmonitor.+//! 2. **Fast-path trash staging.** The worktree directory is renamed into+//! `<git-common-dir>/wt/trash/<name>-<timestamp>/`. Same-filesystem renames+//! are instant metadata operations, so the user's workspace clears+//! immediately. The caller is responsible for eventually removing the+//! staged path — either synchronously or via a background process.+//! 3. **Fallback removal.** If the rename fails (cross-filesystem, permission+//! denied, Windows file locks), the code falls back to `git worktree remove`+//! (optionally with `--force`), which deletes files directly.+//! 4. **Branch deletion** (optional). When a branch name is supplied, the+//! branch is deleted according to the requested [`BranchDeletionMode`]:+//! - [`Keep`](BranchDeletionMode::Keep): never delete.+//! - [`SafeDelete`](BranchDeletionMode::SafeDelete): delete only if+//! [`Repository::integration_reason`] reports the branch as integrated+//! into `target_branch` (or `HEAD` when unspecified).+//! - [`ForceDelete`](BranchDeletionMode::ForceDelete): run `branch -D`+//! without the integration check.+//!+//! # Example+//!+//! ```no_run+//! use std::path::Path;+//! use worktrunk::git::{+//! BranchDeletionMode, RemoveOptions, Repository, remove_worktree_with_cleanup,+//! };+//!+//! let repo = Repository::current()?;+//! let output = remove_worktree_with_cleanup(+//! &repo,+//! Path::new("/repos/myproject.feature"),+//! RemoveOptions {+//! branch: Some("feature".into()),+//! deletion_mode: BranchDeletionMode::SafeDelete,+//! target_branch: Some("main".into()),+//! force_worktree: false,+//! },+//! )?;+//!+//! // Caller cleans up the staged trash entry (sync or background).+//! if let Some(staged) = output.staged_path {+//! let _ = std::fs::remove_dir_all(staged);+//! }+//! # Ok::<(), anyhow::Error>(())+//! ```++use std::path::{Path, PathBuf};++use crate::git::{IntegrationReason, Repository};+use crate::utils::epoch_now;++/// How the branch should be handled after worktree removal.+///+/// Replaces a two-boolean flag pair (`keep`/`force`) to make the three valid+/// states explicit and prevent invalid combinations (e.g. keep+force).+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub enum BranchDeletionMode {+ /// Keep the branch regardless of merge status (`--no-delete-branch`).+ Keep,+ /// Delete only if integrated into the target branch (default).+ #[default]+ SafeDelete,+ /// Delete the branch even if not merged (`-D`).+ ForceDelete,+}++impl BranchDeletionMode {+ /// Construct from CLI-style flags.+ ///+ /// `keep_branch` takes precedence over `force_delete`.+ pub fn from_flags(keep_branch: bool, force_delete: bool) -> Self {+ if keep_branch {+ Self::Keep+ } else if force_delete {+ Self::ForceDelete+ } else {+ Self::SafeDelete+ }+ }++ /// Whether the branch should be kept (never deleted).+ pub fn should_keep(&self) -> bool {+ matches!(self, Self::Keep)+ }++ /// Whether to force-delete even if unmerged.+ pub fn is_force(&self) -> bool {+ matches!(self, Self::ForceDelete)+ }+}++/// Outcome of a branch-deletion attempt.+pub enum BranchDeletionOutcome {+ /// Branch was not deleted — it was not integrated, and deletion was not forced.+ NotDeleted,+ /// Branch was force-deleted without an integration check.+ ForceDeleted,+ /// Branch was deleted because it was integrated (the specific reason is attached).+ Integrated(IntegrationReason),+}++/// Result of [`delete_branch_if_safe`].+pub struct BranchDeletionResult {+ pub outcome: BranchDeletionOutcome,+ /// The ref actually checked against.+ ///+ /// May differ from the caller-supplied target when the local branch is+ /// behind its upstream — in that case `integration_reason` substitutes the+ /// upstream ref so users don't get false negatives.+ pub integration_target: String,+}++/// Options for [`remove_worktree_with_cleanup`].+///+/// Typical usage:+///+/// ```+/// use worktrunk::git::{BranchDeletionMode, RemoveOptions};+///+/// let options = RemoveOptions {+/// branch: Some("feature".into()),+/// deletion_mode: BranchDeletionMode::SafeDelete,+/// target_branch: Some("main".into()),+/// force_worktree: false,+/// };+///+/// // Or, to delete a worktree without touching the branch:+/// let options = RemoveOptions {+/// branch: Some("feature".into()),+/// deletion_mode: BranchDeletionMode::Keep,+/// ..Default::default()+/// };+/// ```+#[derive(Debug, Clone, Default)]+pub struct RemoveOptions {+ /// Branch name to delete alongside the worktree.+ ///+ /// `None` skips branch handling (useful for detached-HEAD worktrees).+ pub branch: Option<String>,+ /// How to handle the branch (default: [`BranchDeletionMode::SafeDelete`]).+ pub deletion_mode: BranchDeletionMode,+ /// Integration target for the safety check.+ ///+ /// Only consulted when `deletion_mode` is [`BranchDeletionMode::SafeDelete`].+ /// `None` falls back to `HEAD`.+ pub target_branch: Option<String>,+ /// Pass `--force` to the `git worktree remove` fallback.+ ///+ /// Does not affect the fast path — trash staging is unconditional and+ /// always preserves data (the renamed directory can be recovered from+ /// `<git-common-dir>/wt/trash/` until the caller deletes it).+ pub force_worktree: bool,+}++/// Result of [`remove_worktree_with_cleanup`].+///+/// `branch_result` is `None` when deletion was skipped (no branch supplied, or+/// `deletion_mode.should_keep()`). Otherwise it carries the raw result so+/// callers can decide how to surface branch-deletion failures — the+/// foreground removal path reports them to the user, the TUI picker ignores+/// them (best-effort), and external tools can do whatever fits.+///+/// `staged_path` is `Some` only on the fast path. Callers are responsible for+/// cleaning up the staged directory; `wt remove` does this with a detached+/// background `rm -rf` so the foreground command returns immediately.+pub struct RemovalOutput {+ pub branch_result: Option<anyhow::Result<BranchDeletionResult>>,+ /// Path to the staged trash directory on the fast path.+ ///+ /// `None` if the fast-path rename failed and the fallback `git worktree+ /// remove` was used.+ pub staged_path: Option<PathBuf>,+}++/// Remove a worktree with fsmonitor cleanup, fast-path trash staging, and+/// optional safe branch deletion.+///+/// See the [module-level docs](self) for the full flow.+///+/// # Errors+///+/// - Returns an error if the fast-path rename fails **and** the fallback+/// `git worktree remove` also fails.+/// - Branch-deletion errors are captured in+/// [`RemovalOutput::branch_result`] rather than returned — worktree removal+/// is considered the primary operation, and callers can decide how to+/// handle a residual branch-deletion failure.+pub fn remove_worktree_with_cleanup(+ repo: &Repository,+ worktree_path: &Path,+ options: RemoveOptions,+) -> anyhow::Result<RemovalOutput> {+ // 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"]);++ // Fast path: rename into .git/wt/trash/ (instant on same filesystem),+ // then prune git metadata. Falls back to `git worktree remove` if the+ // rename fails (cross-filesystem, permissions, Windows file locking).+ let staged_path = stage_worktree_removal(repo, worktree_path);+ if staged_path.is_none() {+ repo.remove_worktree(worktree_path, options.force_worktree)?;+ }++ // Delete branch if safe+ let branch_result = if let Some(branch) = options.branch.as_deref()+ && !options.deletion_mode.should_keep()+ {+ let target = options.target_branch.as_deref().unwrap_or("HEAD");+ Some(delete_branch_if_safe(+ repo,+ branch,+ target,+ options.deletion_mode.is_force(),+ ))+ } else {+ None+ };++ Ok(RemovalOutput {+ branch_result,+ staged_path,+ })+}++/// Rename a worktree into `<git-common-dir>/wt/trash/` and prune git metadata.+///+/// Returns `Some(staged_path)` on success, `None` if the rename failed (e.g.+/// cross-filesystem, permissions, Windows file locking). Callers that see+/// `None` should fall back to a direct `git worktree remove`.+///+/// This is a lower-level building block exposed for callers that want to+/// stage the directory up-front and defer the `rm -rf` to a detached+/// background process (the pattern `wt remove` uses internally).+pub fn stage_worktree_removal(repo: &Repository, worktree_path: &Path) -> Option<PathBuf> {+ let trash_dir = repo.wt_trash_dir();+ let _ = std::fs::create_dir_all(&trash_dir);+ let staged_path = generate_removing_path(&trash_dir, worktree_path);++ if std::fs::rename(worktree_path, &staged_path).is_ok() {+ if let Err(e) = repo.prune_worktrees() {+ log::debug!("Failed to prune worktrees after rename: {e}");+ }+ Some(staged_path)+ } else {+ None+ }+}++/// Delete a branch if its content is integrated into the target, or if+/// `force_delete` is set.+///+/// The integration check is the same logic `wt list` uses for its status+/// column — see [`IntegrationReason`] for the full set of recognised cases+/// (same-commit, ancestor, squash-merged, etc.).+///+/// Returns a [`BranchDeletionResult`] rather than raising an error for the+/// "not integrated" case — that's a normal outcome and the caller decides how+/// to surface it. Only `git branch -D` failures propagate as `Err`.+pub fn delete_branch_if_safe(+ repo: &Repository,+ branch_name: &str,+ target: &str,+ force_delete: bool,+) -> anyhow::Result<BranchDeletionResult> {+ // Force-delete: skip integration check entirely (matches compute_integration_reason+ // behavior for the Worktree path). The user explicitly chose -D.+ if force_delete {+ repo.run_command(&["branch", "-D", branch_name])?;+ return Ok(BranchDeletionResult {+ outcome: BranchDeletionOutcome::ForceDeleted,+ integration_target: target.to_string(),+ });+ }++ let (effective_target, reason) = repo.integration_reason(branch_name, target)?;++ let outcome = match reason {+ Some(r) => {+ repo.run_command(&["branch", "-D", branch_name])?;+ BranchDeletionOutcome::Integrated(r)+ }+ None => BranchDeletionOutcome::NotDeleted,+ };++ Ok(BranchDeletionResult {+ outcome,+ integration_target: effective_target,+ })+}++/// Generate a staging path for worktree removal.+///+/// Places the staging directory inside `<git-common-dir>/wt/trash/` so it is+/// hidden from the user's workspace. For the main worktree, `.git/` is on the+/// same filesystem, so `rename()` is an instant metadata operation. Linked+/// worktrees on different mount points will get EXDEV and fall back to the+/// `git worktree remove` path.+///+/// Format: `<trash-dir>/<name>-<timestamp>`+pub(crate) fn generate_removing_path(trash_dir: &Path, worktree_path: &Path) -> PathBuf {+ let timestamp = epoch_now();+ let name = worktree_path+ .file_name()+ .map(|n| n.to_string_lossy())+ .unwrap_or_default();+ trash_dir.join(format!("{}-{}", name, timestamp))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_branch_deletion_outcome_matching() {+ // Ensure the match patterns work correctly+ let outcomes = [+ (BranchDeletionOutcome::NotDeleted, false),+ (BranchDeletionOutcome::ForceDeleted, true),+ (+ BranchDeletionOutcome::Integrated(IntegrationReason::SameCommit),+ true,+ ),+ ];+ for (outcome, expected_deleted) in outcomes {+ let deleted = matches!(+ outcome,+ BranchDeletionOutcome::ForceDeleted | BranchDeletionOutcome::Integrated(_)+ );+ assert_eq!(deleted, expected_deleted);+ }+ }++ #[test]+ fn test_branch_deletion_mode_from_flags() {+ assert_eq!(+ BranchDeletionMode::from_flags(false, false),+ BranchDeletionMode::SafeDelete+ );+ assert_eq!(+ BranchDeletionMode::from_flags(false, true),+ BranchDeletionMode::ForceDelete+ );+ assert_eq!(+ BranchDeletionMode::from_flags(true, false),+ BranchDeletionMode::Keep+ );+ // keep takes precedence over force+ assert_eq!(+ BranchDeletionMode::from_flags(true, true),+ BranchDeletionMode::Keep+ );+ }++ #[test]+ fn test_branch_deletion_mode_helpers() {+ assert!(BranchDeletionMode::Keep.should_keep());+ assert!(!BranchDeletionMode::SafeDelete.should_keep());+ assert!(!BranchDeletionMode::ForceDelete.should_keep());++ assert!(BranchDeletionMode::ForceDelete.is_force());+ assert!(!BranchDeletionMode::SafeDelete.is_force());+ assert!(!BranchDeletionMode::Keep.is_force());+ }++ #[test]+ fn test_remove_options_default() {+ let opts = RemoveOptions::default();+ assert!(opts.branch.is_none());+ assert_eq!(opts.deletion_mode, BranchDeletionMode::SafeDelete);+ assert!(opts.target_branch.is_none());+ assert!(!opts.force_worktree);+ }++ #[test]+ fn test_generate_removing_path() {+ let trash_dir = PathBuf::from("/some/path/.git/wt/trash");+ let path = PathBuf::from("/foo/bar/feature-branch");+ let removing_path = generate_removing_path(&trash_dir, &path);+ // Format: <trash>/<name>-<timestamp>+ let name = removing_path.file_name().unwrap().to_string_lossy();+ assert!(name.starts_with("feature-branch-"));+ assert!(removing_path.starts_with(&trash_dir));+ }+}diff --git a/src/main.rs b/src/main.rsindex bff348234..200a1f868 100644--- a/src/main.rs+++ b/src/main.rs@@ -44,7 +44,7 @@ pub(crate) use crate::cli::OutputFormat;#[cfg(unix)]use commands::handle_picker;use commands::repository_ext::RepositoryCliExt;-use commands::worktree::{BranchDeletionMode, handle_no_ff_merge, handle_push};+use commands::worktree::{handle_no_ff_merge, handle_push};use commands::{MergeOptions, OperationMode, RebaseResult, RemoveTarget, SquashResult, SwitchOptions,add_approvals, clear_approvals, handle_claude_install, handle_claude_install_statusline,@@ -59,6 +59,7 @@ use commands::{step_relocate,};use output::handle_remove_output;+use worktrunk::git::BranchDeletionMode;use cli::{ApprovalsCommand, CiStatusAction, Cli, Commands, ConfigCommand, ConfigPluginsClaudeCommand,diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 90edb9828..8d3e619b2 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -9,7 +9,6 @@ use color_print::cformat;use worktrunk::shell_exec::Cmd;use worktrunk::styling::{eprint, format_bash_with_gutter, stderr};-use crate::commands::branch_deletion::{BranchDeletionOutcome, BranchDeletionResult};use crate::commands::command_executor::CommandContext;use crate::commands::command_executor::FailureStrategy;use crate::commands::hooks::{@@ -19,15 +18,16 @@ use crate::commands::process::{HookLog, InternalOp, build_remove_command, build_remove_command_staged, spawn_detached,};use crate::commands::worktree::hooks::PostRemoveContext;-use crate::commands::worktree::{- BranchDeletionMode, RemoveResult, SwitchBranchInfo, SwitchResult, execute_removal,- stage_worktree_removal,-};+use crate::commands::worktree::{RemoveResult, SwitchBranchInfo, SwitchResult};use worktrunk::config::UserConfig;use worktrunk::git::GitError;use worktrunk::git::IntegrationReason;use worktrunk::git::Repository;use worktrunk::git::path_dir_name;+use worktrunk::git::{+ BranchDeletionMode, BranchDeletionOutcome, BranchDeletionResult, RemoveOptions,+ remove_worktree_with_cleanup, stage_worktree_removal,+};use worktrunk::path::format_path_for_display;use worktrunk::styling::{FormattedMessage, eprintln, error_message, format_with_gutter, hint_message, info_message,@@ -1212,13 +1212,15 @@ fn handle_detached_removed_worktree_output(format_path_for_display(ctx.worktree_path))));- let output = execute_removal(+ let output = remove_worktree_with_cleanup(repo,ctx.worktree_path,- None,- ctx.deletion_mode,- ctx.target_branch,- ctx.force_worktree,+ RemoveOptions {+ branch: None,+ deletion_mode: ctx.deletion_mode,+ target_branch: ctx.target_branch.map(String::from),+ force_worktree: ctx.force_worktree,+ },).map_err(|err| GitError::WorktreeRemovalFailed {branch: path_dir_name(ctx.worktree_path).to_string(),@@ -1279,13 +1281,15 @@ fn handle_named_removed_worktree_foreground();}- let output = execute_removal(+ let output = remove_worktree_with_cleanup(repo,ctx.worktree_path,- Some(branch_name),- ctx.deletion_mode,- ctx.target_branch,- ctx.force_worktree,+ RemoveOptions {+ branch: Some(branch_name.to_string()),+ deletion_mode: ctx.deletion_mode,+ target_branch: ctx.target_branch.map(String::from),+ force_worktree: ctx.force_worktree,+ },).map_err(|err| GitError::WorktreeRemovalFailed {branch: branch_name.into(),