Skip to content

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

Refactor branch deletion flags into BranchDeletionMode enum

Maximilian Roos9cdc261bc5de
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 416643d47..622e20889 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -10,7 +10,7 @@ use super::context::CommandEnv;
use super::hooks::{HookFailureStrategy, run_hook_with_filter};
use super::project_config::collect_commands_for_hooks;
use super::repository_ext::RepositoryCliExt;
-use super::worktree::{MergeOperations, RemoveResult, handle_push};
+use super::worktree::{BranchDeletionMode, MergeOperations, RemoveResult, handle_push};
/// Options for the merge command
pub struct MergeOptions<'a> {
@@ -237,8 +237,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
worktree_path: worktree_root,
changed_directory: true,
branch_name: Some(current_branch.clone()),
- no_delete_branch: false,
- force_delete: false,
+ deletion_mode: BranchDeletionMode::SafeDelete,
target_branch: Some(target_branch.clone()),
};
// Run hooks during merge removal (pass through verify flag)
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 6828b7a70..1e9b355e8 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -2,7 +2,7 @@ use std::path::{Path, PathBuf};
use std::process;
use std::time::{SystemTime, UNIX_EPOCH};
-use super::worktree::RemoveResult;
+use super::worktree::{BranchDeletionMode, RemoveResult};
use anyhow::Context;
use color_print::cformat;
use worktrunk::config::ProjectConfig;
@@ -26,8 +26,7 @@ pub trait RepositoryCliExt {
fn remove_worktree_by_name(
&self,
branch_name: &str,
- no_delete_branch: bool,
- force_delete: bool,
+ deletion_mode: BranchDeletionMode,
) -> anyhow::Result<RemoveResult>;
/// Remove the current worktree (handles detached HEAD state).
@@ -38,8 +37,7 @@ pub trait RepositoryCliExt {
/// 2. The reflog (if detached from a branch)
fn remove_current_worktree(
&self,
- no_delete_branch: bool,
- force_delete: bool,
+ deletion_mode: BranchDeletionMode,
) -> anyhow::Result<RemoveResult>;
/// Prepare the target worktree for push by auto-stashing non-overlapping changes when safe.
@@ -82,8 +80,7 @@ impl RepositoryCliExt for Repository {
fn remove_worktree_by_name(
&self,
branch_name: &str,
- no_delete_branch: bool,
- force_delete: bool,
+ deletion_mode: BranchDeletionMode,
) -> anyhow::Result<RemoveResult> {
let worktree_path = match self.worktree_for_branch(branch_name)? {
Some(path) => path,
@@ -93,8 +90,7 @@ impl RepositoryCliExt for Repository {
// Branch exists but no worktree - return BranchOnly to attempt branch deletion
return Ok(RemoveResult::BranchOnly {
branch_name: branch_name.to_string(),
- no_delete_branch,
- force_delete,
+ deletion_mode,
});
}
// Check if branch exists on a remote
@@ -151,16 +147,14 @@ impl RepositoryCliExt for Repository {
worktree_path,
changed_directory,
branch_name: Some(branch_name.to_string()),
- no_delete_branch,
- force_delete,
+ deletion_mode,
target_branch,
})
}
fn remove_current_worktree(
&self,
- no_delete_branch: bool,
- force_delete: bool,
+ deletion_mode: BranchDeletionMode,
) -> anyhow::Result<RemoveResult> {
// Cannot remove the main working tree (only linked worktrees can be removed)
if !self.is_in_worktree()? {
@@ -199,8 +193,7 @@ impl RepositoryCliExt for Repository {
worktree_path: current_path,
changed_directory: true,
branch_name,
- no_delete_branch,
- force_delete,
+ deletion_mode,
target_branch,
})
}
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 41b0a1979..f81b45b67 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -357,6 +357,45 @@ impl SwitchBranchInfo {
}
}
+/// How the branch should be handled after worktree removal.
+///
+/// This enum replaces the previous `no_delete_branch: bool, force_delete: bool` pattern,
+/// 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(no_delete_branch: bool, force_delete: bool) -> Self {
+ if no_delete_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 operation
pub enum RemoveResult {
/// Removed worktree and returned to main (if needed)
@@ -366,15 +405,13 @@ pub enum RemoveResult {
changed_directory: bool,
/// Branch name, if known. None for detached HEAD state.
branch_name: Option<String>,
- no_delete_branch: bool,
- force_delete: bool,
+ deletion_mode: BranchDeletionMode,
target_branch: Option<String>,
},
/// Branch exists but has no worktree - attempt branch deletion only
BranchOnly {
branch_name: String,
- no_delete_branch: bool,
- force_delete: bool,
+ deletion_mode: BranchDeletionMode,
},
}
@@ -643,7 +680,10 @@ pub fn handle_remove(
)))?;
}
- repo.remove_worktree_by_name(worktree_name, no_delete_branch, force_delete)
+ repo.remove_worktree_by_name(
+ worktree_name,
+ BranchDeletionMode::from_flags(no_delete_branch, force_delete),
+ )
}
/// Handle removing the current worktree (supports detached HEAD state).
@@ -662,18 +702,21 @@ pub fn handle_remove_current(
crate::output::print(progress_message("Removing current worktree..."))?;
}
- repo.remove_current_worktree(no_delete_branch, force_delete)
+ repo.remove_current_worktree(BranchDeletionMode::from_flags(
+ no_delete_branch,
+ force_delete,
+ ))
}
/// Handle removing a worktree by path (for detached non-current worktrees).
///
/// This is used when a worktree is in detached HEAD state and we're not
/// currently in it. We can still remove the worktree, we just don't know
-/// which branch (if any) to delete.
+/// which branch (if any) to delete. Branch deletion is not attempted
+/// since no branch is associated with a detached HEAD worktree.
pub fn handle_remove_by_path(
path: &std::path::Path,
branch: Option<String>,
- force_delete: bool,
background: bool,
) -> anyhow::Result<RemoveResult> {
let repo = Repository::current();
@@ -697,8 +740,7 @@ pub fn handle_remove_by_path(
worktree_path: path.to_path_buf(),
changed_directory: false,
branch_name: branch,
- no_delete_branch: true, // Can't delete branch for detached worktree
- force_delete,
+ deletion_mode: BranchDeletionMode::Keep, // Can't delete branch for detached worktree
target_branch: None,
})
}
@@ -1154,8 +1196,7 @@ mod tests {
worktree_path: PathBuf::from("/worktree"),
changed_directory: true,
branch_name: Some("feature".to_string()),
- no_delete_branch: false,
- force_delete: false,
+ deletion_mode: BranchDeletionMode::SafeDelete,
target_branch: Some("main".to_string()),
};
match result {
@@ -1164,16 +1205,15 @@ mod tests {
worktree_path,
changed_directory,
branch_name,
- no_delete_branch,
- force_delete,
+ deletion_mode,
target_branch,
} => {
assert_eq!(main_path.to_str().unwrap(), "/main");
assert_eq!(worktree_path.to_str().unwrap(), "/worktree");
assert!(changed_directory);
assert_eq!(branch_name.as_deref(), Some("feature"));
- assert!(!no_delete_branch);
- assert!(!force_delete);
+ assert!(!deletion_mode.should_keep());
+ assert!(!deletion_mode.is_force());
assert_eq!(target_branch.as_deref(), Some("main"));
}
_ => panic!("Expected RemovedWorktree variant"),
@@ -1184,18 +1224,16 @@ mod tests {
fn test_remove_result_branch_only() {
let result = RemoveResult::BranchOnly {
branch_name: "stale-branch".to_string(),
- no_delete_branch: true,
- force_delete: false,
+ deletion_mode: BranchDeletionMode::Keep,
};
match result {
RemoveResult::BranchOnly {
branch_name,
- no_delete_branch,
- force_delete,
+ deletion_mode,
} => {
assert_eq!(branch_name, "stale-branch");
- assert!(no_delete_branch);
- assert!(!force_delete);
+ assert!(deletion_mode.should_keep());
+ assert!(!deletion_mode.is_force());
}
_ => panic!("Expected BranchOnly variant"),
}
@@ -1208,20 +1246,17 @@ mod tests {
worktree_path: PathBuf::from("/worktree"),
changed_directory: false,
branch_name: None, // Detached HEAD
- no_delete_branch: true,
- force_delete: true,
+ deletion_mode: BranchDeletionMode::ForceDelete,
target_branch: None,
};
match result {
RemoveResult::RemovedWorktree {
branch_name,
- no_delete_branch,
- force_delete,
+ deletion_mode,
..
} => {
assert!(branch_name.is_none());
- assert!(no_delete_branch);
- assert!(force_delete);
+ assert!(deletion_mode.is_force());
}
_ => panic!("Expected RemovedWorktree variant"),
}
diff --git a/src/main.rs b/src/main.rs
index 302f9451c..6941b6e35 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1378,7 +1378,7 @@ fn main() {
}
} else {
// Non-current worktree is detached - remove by path (no branch to delete)
- match handle_remove_by_path(path, None, force_delete, background) {
+ match handle_remove_by_path(path, None, background) {
Ok(result) => {
handle_remove_output(&result, None, background, verify)?;
}
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 5f72ae1b2..03c189976 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -6,7 +6,7 @@ use std::path::Path;
use crate::commands::command_executor::CommandContext;
use crate::commands::execute_pre_remove_commands;
use crate::commands::process::spawn_detached;
-use crate::commands::worktree::{RemoveResult, SwitchBranchInfo, SwitchResult};
+use crate::commands::worktree::{BranchDeletionMode, RemoveResult, SwitchBranchInfo, SwitchResult};
use worktrunk::config::WorktrunkConfig;
use worktrunk::git::GitError;
use worktrunk::git::IntegrationReason;
@@ -192,11 +192,11 @@ fn handle_branch_deletion_result(
///
/// `target_branch`: The branch we checked integration against (shown in reason)
fn get_flag_note(
- no_delete_branch: bool,
+ deletion_mode: BranchDeletionMode,
outcome: &BranchDeletionOutcome,
target_branch: Option<&str>,
) -> String {
- if no_delete_branch {
+ if deletion_mode.should_keep() {
return " (--no-delete-branch)".to_string();
}
@@ -219,17 +219,16 @@ fn get_flag_note(
/// Format message for remove worktree operation (includes emoji and color for consistency)
///
/// `target_branch`: The branch we checked integration against (Some = merge context, None = explicit remove)
-#[allow(clippy::too_many_arguments)]
fn format_remove_worktree_message(
main_path: &std::path::Path,
changed_directory: bool,
branch_name: &str,
branch: Option<&str>,
- no_delete_branch: bool,
+ deletion_mode: BranchDeletionMode,
outcome: &BranchDeletionOutcome,
target_branch: Option<&str>,
) -> String {
- let flag_note = get_flag_note(no_delete_branch, outcome, target_branch);
+ let flag_note = get_flag_note(deletion_mode, outcome, target_branch);
let branch_display = branch.or(Some(branch_name));
let path_display = format_path_for_display(main_path);
@@ -243,7 +242,7 @@ fn format_remove_worktree_message(
// Determine action suffix based on what happened to the branch
let action_suffix = if branch_deleted {
"worktree & branch"
- } else if no_delete_branch {
+ } else if deletion_mode.should_keep() {
// User explicitly kept the branch via --no-delete-branch
"worktree"
} else if matches!(outcome, BranchDeletionOutcome::NotDeleted) {
@@ -465,16 +464,14 @@ pub fn handle_remove_output(
worktree_path,
changed_directory,
branch_name,
- no_delete_branch,
- force_delete,
+ deletion_mode,
target_branch,
} => handle_removed_worktree_output(
main_path,
worktree_path,
*changed_directory,
branch_name.as_deref(),
- *no_delete_branch,
- *force_delete,
+ *deletion_mode,
target_branch.as_deref(),
branch,
background,
@@ -482,17 +479,15 @@ pub fn handle_remove_output(
),
RemoveResult::BranchOnly {
branch_name,
- no_delete_branch,
- force_delete,
- } => handle_branch_only_output(branch_name, *no_delete_branch, *force_delete),
+ deletion_mode,
+ } => handle_branch_only_output(branch_name, *deletion_mode),
}
}
/// Handle output for BranchOnly removal (branch exists but no worktree)
fn handle_branch_only_output(
branch_name: &str,
- no_delete_branch: bool,
- force_delete: bool,
+ deletion_mode: BranchDeletionMode,
) -> anyhow::Result<()> {
// Warn that no worktree was found (user asked to remove it)
super::print(warning_message(cformat!(
@@ -500,7 +495,7 @@ fn handle_branch_only_output(
)))?;
// Attempt branch deletion (unless --no-delete-branch was specified)
- if no_delete_branch {
+ if deletion_mode.should_keep() {
// User explicitly requested no branch deletion - nothing more to do
super::flush()?;
return Ok(());
@@ -513,12 +508,12 @@ fn handle_branch_only_output(
let default_branch = repo.default_branch().ok();
let check_target = default_branch.as_deref().unwrap_or("HEAD");
- let result = delete_branch_if_safe(&repo, branch_name, check_target, force_delete);
+ let result = delete_branch_if_safe(&repo, branch_name, check_target, deletion_mode.is_force());
let (deletion, _) = handle_branch_deletion_result(result, branch_name, false)?;
if !matches!(deletion.outcome, BranchDeletionOutcome::NotDeleted) {
let flag_note = get_flag_note(
- no_delete_branch,
+ deletion_mode,
&deletion.outcome,
Some(&deletion.effective_target),
);
@@ -538,8 +533,7 @@ fn handle_removed_worktree_output(
worktree_path: &std::path::Path,
changed_directory: bool,
branch_name: Option<&str>,
- no_delete_branch: bool,
- force_delete: bool,
+ deletion_mode: BranchDeletionMode,
target_branch: Option<&str>,
branch: Option<&str>,
background: bool,
@@ -609,12 +603,12 @@ fn handle_removed_worktree_output(
// Determine outcome upfront (check once, not in background script)
// Only show effective_target in message if we had a meaningful target (not tautological "HEAD" fallback)
- let (outcome, effective_target) = if no_delete_branch {
+ let (outcome, effective_target) = if deletion_mode.should_keep() {
(
BranchDeletionOutcome::NotDeleted,
target_branch.map(String::from),
)
- } else if force_delete {
+ } else if deletion_mode.is_force() {
(
BranchDeletionOutcome::ForceDeleted,
target_branch.map(String::from),
@@ -641,10 +635,10 @@ fn handle_removed_worktree_output(
BranchDeletionOutcome::ForceDeleted | BranchDeletionOutcome::Integrated(_)
);
- let flag_note = get_flag_note(no_delete_branch, &outcome, effective_target.as_deref());
+ let flag_note = get_flag_note(deletion_mode, &outcome, effective_target.as_deref());
// Reason in parentheses: user flags shown explicitly, integration reason for automatic cleanup
- let action = if no_delete_branch {
+ let action = if deletion_mode.should_keep() {
cformat!(
"<cyan>Removing <bold>{branch_name}</> worktree in background; retaining branch{flag_note}</>"
)
@@ -660,7 +654,7 @@ fn handle_removed_worktree_output(
super::print(progress_message(action))?;
// Show hint for unmerged branches (same as synchronous path)
- if !no_delete_branch && !should_delete_branch {
+ if !deletion_mode.should_keep() && !should_delete_branch {
super::print(hint_message(cformat!(
"<bright-black>wt remove -D</> deletes unmerged branches"
)))?;
@@ -702,11 +696,15 @@ fn handle_removed_worktree_output(
// Delete the branch (unless --no-delete-branch was specified)
// Only show effective_target in message if we had a meaningful target (not tautological "HEAD" fallback)
- let (outcome, effective_target, show_hint) = if !no_delete_branch {
+ let (outcome, effective_target, show_hint) = if !deletion_mode.should_keep() {
let deletion_repo = worktrunk::git::Repository::at(main_path);
let check_target = target_branch.unwrap_or("HEAD");
- let result =
- delete_branch_if_safe(&deletion_repo, branch_name, check_target, force_delete);
+ let result = delete_branch_if_safe(
+ &deletion_repo,
+ branch_name,
+ check_target,
+ deletion_mode.is_force(),
+ );
let (deletion, needs_hint) = handle_branch_deletion_result(result, branch_name, true)?;
// Only use effective_target for display if we had a real target (not "HEAD" fallback)
let display_target = target_branch.map(|_| deletion.effective_target);
@@ -725,7 +723,7 @@ fn handle_removed_worktree_output(
changed_directory,
branch_name,
branch,
- no_delete_branch,
+ deletion_mode,
&outcome,
effective_target.as_deref(),
)))?;
@@ -949,19 +947,31 @@ mod tests {
fn test_get_flag_note() {
// --no-delete-branch flag
assert_eq!(
- get_flag_note(true, &BranchDeletionOutcome::NotDeleted, None),
+ get_flag_note(
+ BranchDeletionMode::Keep,
+ &BranchDeletionOutcome::NotDeleted,
+ None
+ ),
" (--no-delete-branch)"
);
// NotDeleted without flag
assert_eq!(
- get_flag_note(false, &BranchDeletionOutcome::NotDeleted, None),
+ get_flag_note(
+ BranchDeletionMode::SafeDelete,
+ &BranchDeletionOutcome::NotDeleted,
+ None
+ ),
""
);
// Force deleted
assert_eq!(
- get_flag_note(false, &BranchDeletionOutcome::ForceDeleted, None),
+ get_flag_note(
+ BranchDeletionMode::ForceDelete,
+ &BranchDeletionOutcome::ForceDeleted,
+ None
+ ),
" (--force-delete)"
);
@@ -974,7 +984,7 @@ mod tests {
];
for (reason, expected_contains) in cases {
let note = get_flag_note(
- false,
+ BranchDeletionMode::SafeDelete,
&BranchDeletionOutcome::Integrated(reason),
Some("main"),
);
@@ -988,7 +998,7 @@ mod tests {
// NoAddedChanges is special - no target shown
let note = get_flag_note(
- false,
+ BranchDeletionMode::SafeDelete,
&BranchDeletionOutcome::Integrated(IntegrationReason::NoAddedChanges),
Some("main"),
);
@@ -1006,7 +1016,7 @@ mod tests {
false,
"feature",
Some("feature"),
- false,
+ BranchDeletionMode::SafeDelete,
&BranchDeletionOutcome::Integrated(IntegrationReason::SameCommit),
Some("main"),
);
@@ -1020,7 +1030,7 @@ mod tests {
false,
"feature",
Some("feature"),
- true,
+ BranchDeletionMode::Keep,
&BranchDeletionOutcome::NotDeleted,
None,
);
@@ -1034,7 +1044,7 @@ mod tests {
true,
"feature",
Some("feature"),
- false,
+ BranchDeletionMode::ForceDelete,
&BranchDeletionOutcome::ForceDeleted,
None,
);
@@ -1047,7 +1057,7 @@ mod tests {
false,
"feature",
Some("feature"),
- false,
+ BranchDeletionMode::SafeDelete,
&BranchDeletionOutcome::NotDeleted,
None,
);