Skip to content

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

feat: Implement background worktree removal

Maximilian Roosf91aa4e071bd
diff --git a/src/cli.rs b/src/cli.rs
index 9e34969f4..f485a0a86 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -489,6 +489,10 @@ Switch to default in primary:
/// Keep branch after removal
#[arg(long = "no-delete-branch")]
no_delete_branch: bool,
+
+ /// Background removal for large repos
+ #[arg(long)]
+ background: bool,
},
/// Merge worktree into target branch
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 8d845d41b..104c49707 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -199,7 +199,7 @@ pub fn handle_merge(
no_delete_branch: false,
target_branch: Some(target_branch.clone()),
};
- crate::output::handle_remove_output(&remove_result, Some(&current_branch), true)?;
+ crate::output::handle_remove_output(&remove_result, Some(&current_branch), true, false)?;
} else {
// Print comprehensive summary (worktree preserved)
handle_merge_summary_output(None)?;
diff --git a/src/main.rs b/src/main.rs
index 8e80e74f7..381b228c7 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -264,11 +264,12 @@ fn main() {
Commands::Remove {
worktrees,
no_delete_branch,
+ background,
} => {
if worktrees.is_empty() {
// No worktrees specified, remove current worktree
handle_remove(None, no_delete_branch)
- .and_then(|result| handle_remove_output(&result, None, false))
+ .and_then(|result| handle_remove_output(&result, None, false, background))
} else {
// When removing multiple worktrees, we need to handle the current worktree last
// to avoid deleting the directory we're currently in
@@ -301,13 +302,18 @@ fn main() {
// Progress messages shown by handle_remove_output for all cases
for worktree in others.iter() {
let result = handle_remove(Some(worktree.as_str()), no_delete_branch)?;
- handle_remove_output(&result, Some(worktree.as_str()), false)?;
+ handle_remove_output(&result, Some(worktree.as_str()), false, background)?;
}
// Remove current worktree last (if it was in the list)
if let Some(current_name) = current {
let result = handle_remove(Some(current_name.as_str()), no_delete_branch)?;
- handle_remove_output(&result, Some(current_name.as_str()), false)?;
+ handle_remove_output(
+ &result,
+ Some(current_name.as_str()),
+ false,
+ background,
+ )?;
}
Ok(())
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 432108581..9d7911d16 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1,5 +1,6 @@
//! Output handlers for worktree operations using the global output context
+use crate::commands::process::spawn_detached;
use crate::commands::worktree::{RemoveResult, SwitchResult};
use crate::output::global::format_switch_success;
use worktrunk::git::GitError;
@@ -138,14 +139,55 @@ pub fn execute_user_command(command: &str) -> Result<(), GitError> {
Ok(())
}
+/// Build shell command for background worktree removal
+///
+/// Constructs a command that:
+/// 1. Removes the worktree using `git worktree remove`
+/// 2. Conditionally deletes the branch if it's fully merged
+///
+/// The command replicates the same safety checks done in handle_remove_output:
+/// - Uses `git merge-base --is-ancestor` to check if branch is merged
+/// - Only deletes with `-D` if the branch is an ancestor of the target
+fn build_remove_command(
+ worktree_path: &std::path::Path,
+ branch_name: &str,
+ no_delete_branch: bool,
+ target_branch: &str,
+) -> String {
+ use shell_escape::escape;
+
+ let worktree_path_str = worktree_path.to_string_lossy();
+ let worktree_escaped = escape(worktree_path_str.as_ref().into());
+ let branch_escaped = escape(branch_name.into());
+ let target_escaped = escape(target_branch.into());
+
+ if no_delete_branch {
+ // Just remove the worktree
+ format!("git worktree remove {}", worktree_escaped)
+ } else {
+ // Remove worktree and conditionally delete branch if merged
+ format!(
+ "git worktree remove {} && if git merge-base --is-ancestor {} {}; then git branch -D {}; fi",
+ worktree_escaped, branch_escaped, target_escaped, branch_escaped
+ )
+ }
+}
+
/// Handle output for a remove operation
pub fn handle_remove_output(
result: &RemoveResult,
branch: Option<&str>,
strict_branch_deletion: bool,
+ background: bool,
) -> Result<(), GitError> {
- // Track whether branch was actually deleted (will be computed based on deletion attempt)
- let branch_deleted = if let RemoveResult::RemovedWorktree {
+ // For non-worktree removals, show message immediately
+ if !matches!(result, RemoveResult::RemovedWorktree { .. }) {
+ super::success(format_remove_message(result, branch, false))?;
+ super::flush()?;
+ return Ok(());
+ }
+
+ let RemoveResult::RemovedWorktree {
primary_path,
worktree_path,
changed_directory,
@@ -153,15 +195,40 @@ pub fn handle_remove_output(
no_delete_branch,
target_branch,
} = result
- {
- // 1. Emit cd directive if needed - shell will execute this immediately
- if *changed_directory {
- super::change_directory(primary_path)?;
- super::flush()?; // Force flush to ensure shell processes the cd
- }
+ else {
+ unreachable!("Already handled non-RemovedWorktree cases above")
+ };
- // 2. Do the deletion (shell already changed directory if needed)
- // Progress message already shown at start of handle_remove()
+ // 1. Emit cd directive if needed - shell will execute this immediately
+ if *changed_directory {
+ super::change_directory(primary_path)?;
+ super::flush()?; // Force flush to ensure shell processes the cd
+ }
+
+ if background {
+ // Background mode: spawn detached process
+ let check_target = target_branch.as_deref().unwrap_or("HEAD");
+ let remove_command =
+ build_remove_command(worktree_path, branch_name, *no_delete_branch, check_target);
+
+ // Spawn the removal in background - runs from primary_path (where we cd'd to)
+ let log_path = spawn_detached(
+ primary_path,
+ &remove_command,
+ &format!("remove-{}", branch_name),
+ )?;
+
+ // Show info message indicating backgrounding (not "success" - work hasn't completed)
+ super::info(format!(
+ "Removal queued for {GREEN_BOLD}{branch_name}{GREEN_BOLD:#} (background)"
+ ))?;
+ super::info(format!("Log: {}", log_path.display()))?;
+
+ super::flush()?;
+ Ok(())
+ } else {
+ // Synchronous mode: remove immediately and report actual results
+ // Track whether branch was actually deleted (will be computed based on deletion attempt)
let repo = worktrunk::git::Repository::current();
if let Err(err) = repo.remove_worktree(worktree_path) {
return Err(match err {
@@ -174,16 +241,12 @@ pub fn handle_remove_output(
});
}
- // 3. Delete the branch (unless --no-delete-branch was specified)
- // Returns true if branch was successfully deleted, false otherwise
- if !no_delete_branch {
+ // Delete the branch (unless --no-delete-branch was specified)
+ let branch_deleted = if !no_delete_branch {
let deletion_repo = worktrunk::git::Repository::at(primary_path);
-
- // Determine what to check against: target branch if specified, otherwise HEAD
let check_target = target_branch.as_deref().unwrap_or("HEAD");
// Use git merge-base --is-ancestor to check if branch is merged to target
- // This is the same safety check that `git branch -d` does, but we can specify the target
let delete_result = match deletion_repo.run_command(&[
"merge-base",
"--is-ancestor",
@@ -217,13 +280,11 @@ pub fn handle_remove_output(
}
// If branch deletion fails in non-strict mode, show a warning but don't error
- // Show the warning message with branch name
super::warning(format!(
"{WARNING}Could not delete branch {WARNING_BOLD}{branch_name}{WARNING_BOLD:#}{WARNING:#}"
))?;
// Show the git error in a gutter-formatted block (raw output, no styling)
- // Extract the raw error message without our formatting
let raw_error = match &e {
GitError::CommandFailed(msg) => msg.as_str(),
_ => &e.to_string(),
@@ -234,18 +295,13 @@ pub fn handle_remove_output(
}
} else {
false
- }
- } else {
- false
- };
+ };
- // Show success message (includes emoji and color)
- super::success(format_remove_message(result, branch, branch_deleted))?;
-
- // Flush output
- super::flush()?;
-
- Ok(())
+ // Show success message (includes emoji and color)
+ super::success(format_remove_message(result, branch, branch_deleted))?;
+ super::flush()?;
+ Ok(())
+ }
}
/// Execute a command with streaming output
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snap
index 803724770..d4f4d886e 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmplQc7bx/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpYAlSYi/test-config.toml
---
success: true
exit_code: 0
@@ -628,7 +628,7 @@ _wt() {
return 0
;;
wt__remove)
- opts="-C -v -h --no-delete-branch --verbose --help [WORKTREES]..."
+ opts="-C -v -h --no-delete-branch --background --verbose --help [WORKTREES]..."
if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index 0bbe27e9f..aa6a127b4 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpLl28QZ/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpk0twDT/test-config.toml
---
success: true
exit_code: 0
@@ -289,6 +289,7 @@ complete -c wt -n "__fish_wt_using_subcommand switch" -s v -l verbose -d 'Show g
complete -c wt -n "__fish_wt_using_subcommand switch" -s h -l help -d 'Print help'
complete -c wt -n "__fish_wt_using_subcommand remove" -s C -d 'Change working directory' -r -F
complete -c wt -n "__fish_wt_using_subcommand remove" -l no-delete-branch -d 'Keep branch after removal'
+complete -c wt -n "__fish_wt_using_subcommand remove" -l background -d 'Background removal for large repos'
complete -c wt -n "__fish_wt_using_subcommand remove" -s v -l verbose -d 'Show git commands and debug info'
complete -c wt -n "__fish_wt_using_subcommand remove" -s h -l help -d 'Print help'
complete -c wt -n "__fish_wt_using_subcommand merge" -s C -d 'Change working directory' -r -F
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index e8ef472fe..c3f5cc091 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpVHSm2d/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpYQy0PC/test-config.toml
---
success: true
exit_code: 0
@@ -435,6 +435,7 @@ _arguments "${_arguments_options[@]}" : \
_arguments "${_arguments_options[@]}" : \
'-C+[Change working directory]:path:_files' \
'--no-delete-branch[Keep branch after removal]' \
+'--background[Background removal for large repos]' \
'-v[Show git commands and debug info]' \
'--verbose[Show git commands and debug info]' \
'-h[Print help]' \