Skip to content

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

refactor: compute BranchOnly integration in prepare_worktree_removal (#1989)

Maximilian Roos9fa326d21188
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 3bd46ad9f..b468b8f04 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -304,7 +304,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
current_wt.ensure_clean("remove worktree after merge", Some(&current_branch), false)?;
let worktree_root = current_wt.root()?;
- let integration_reason = compute_integration_reason(
+ let (integration_reason, _) = compute_integration_reason(
repo,
Some(&current_branch),
Some(&target_branch),
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index 95b15cb6c..ab3506c65 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -835,6 +835,8 @@ pub mod tests {
branch_name: "feature".to_string(),
deletion_mode: BranchDeletionMode::SafeDelete,
pruned: false,
+ target_branch: None,
+ integration_reason: None,
};
PickerCollector::do_removal(&repo, &result).unwrap();
@@ -859,6 +861,8 @@ pub mod tests {
branch_name: "unmerged".to_string(),
deletion_mode: BranchDeletionMode::SafeDelete,
pruned: false,
+ target_branch: None,
+ integration_reason: None,
};
PickerCollector::do_removal(&repo, &result).unwrap();
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 9734a8cd4..ac00df61d 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -208,13 +208,20 @@ impl RepositoryCliExt for Repository {
}
// Phase 4: Return BranchOnly early (after validation), or continue to
- // worktree-level checks.
+ // worktree-level checks. Compute integration here (same as Phase 5 does
+ // for RemovedWorktree) so the output handler doesn't re-derive it.
let (worktree_path, branch_name, is_current) = match resolved {
Resolved::BranchOnly { branch, pruned } => {
+ let default_branch = self.default_branch();
+ let target = default_branch.as_deref().or(Some("HEAD"));
+ let (integration_reason, target_branch) =
+ compute_integration_reason(self, Some(&branch), target, deletion_mode);
return Ok(RemoveResult::BranchOnly {
branch_name: branch,
deletion_mode,
pruned,
+ target_branch,
+ integration_reason,
});
}
Resolved::Worktree {
@@ -253,7 +260,7 @@ impl RepositoryCliExt for Repository {
// Pre-compute integration reason to avoid race conditions when removing
// multiple worktrees in background mode.
- let integration_reason = compute_integration_reason(
+ let (integration_reason, _) = compute_integration_reason(
self,
branch_name.as_deref(),
target_branch.as_deref(),
@@ -412,13 +419,15 @@ pub(crate) fn is_primary_worktree(repo: &Repository) -> anyhow::Result<bool> {
Ok(primary.as_deref() == Some(current_root.as_path()))
}
-/// Compute integration reason for branch deletion.
+/// Compute integration reason and effective target for branch deletion.
///
-/// Returns `None` if:
+/// Returns `(None, None)` if:
/// - `deletion_mode` is `ForceDelete` (skip integration check)
/// - `branch_name` is `None` (detached HEAD)
/// - `target_branch` is `None` (no target to check against)
-/// - Branch is not integrated into target (safe deletion not confirmed)
+///
+/// When `Some`, the effective target may differ from the local default branch
+/// (e.g., `origin/main` when upstream is ahead).
///
/// Note: Integration is computed even for `Keep` mode so we can inform the user
/// if the flag had an effect (branch was integrated) or not (branch was unmerged).
@@ -427,16 +436,21 @@ pub(crate) fn compute_integration_reason(
branch_name: Option<&str>,
target_branch: Option<&str>,
deletion_mode: BranchDeletionMode,
-) -> Option<IntegrationReason> {
+) -> (Option<IntegrationReason>, Option<String>) {
// Skip for force delete (we'll delete regardless of integration status)
// But compute for keep mode so we can inform user if the flag had no effect
if deletion_mode.is_force() {
- return None;
+ return (None, None);
}
- let (branch, target) = branch_name.zip(target_branch)?;
+ let (branch, target) = match branch_name.zip(target_branch) {
+ Some(pair) => pair,
+ None => return (None, None),
+ };
// On error, return None (informational only)
- let (_, reason) = repo.integration_reason(branch, target).ok()?;
- reason
+ match repo.integration_reason(branch, target) {
+ Ok((effective_target, reason)) => (reason, Some(effective_target)),
+ Err(_) => (None, None),
+ }
}
/// Reject removing the default branch unless force-delete is set.
diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rs
index f078d26c0..acb343af0 100644
--- a/src/commands/worktree/types.rs
+++ b/src/commands/worktree/types.rs
@@ -216,6 +216,14 @@ pub enum RemoveResult {
deletion_mode: BranchDeletionMode,
/// True if the worktree was pruned before returning this result.
pruned: bool,
+ /// Integration target for display. May be the effective target (e.g.,
+ /// `origin/main` when upstream is ahead) or the local default branch.
+ /// `None` when no default branch is configured.
+ target_branch: Option<String>,
+ /// Pre-computed integration reason, same as `RemovedWorktree`.
+ /// Computed in `prepare_worktree_removal` so the output handler
+ /// doesn't need to re-derive a `Repository` for the check.
+ integration_reason: Option<worktrunk::git::IntegrationReason>,
},
}
@@ -363,17 +371,23 @@ mod tests {
branch_name: "stale-branch".to_string(),
deletion_mode: BranchDeletionMode::Keep,
pruned: false,
+ target_branch: None,
+ integration_reason: None,
};
match result {
RemoveResult::BranchOnly {
branch_name,
deletion_mode,
pruned,
+ target_branch,
+ integration_reason,
} => {
assert_eq!(branch_name, "stale-branch");
assert!(deletion_mode.should_keep());
assert!(!deletion_mode.is_force());
assert!(!pruned);
+ assert!(target_branch.is_none());
+ assert!(integration_reason.is_none());
}
_ => panic!("Expected BranchOnly variant"),
}
@@ -385,16 +399,22 @@ mod tests {
branch_name: "pruned-branch".to_string(),
deletion_mode: BranchDeletionMode::SafeDelete,
pruned: true,
+ target_branch: Some("main".to_string()),
+ integration_reason: None,
};
match result {
RemoveResult::BranchOnly {
branch_name,
deletion_mode,
pruned,
+ target_branch,
+ integration_reason,
} => {
assert_eq!(branch_name, "pruned-branch");
assert!(!deletion_mode.should_keep());
assert!(pruned);
+ assert_eq!(target_branch.as_deref(), Some("main"));
+ assert!(integration_reason.is_none());
}
_ => panic!("Expected BranchOnly variant"),
}
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index ad71013d7..fd5c9e545 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -195,10 +195,6 @@ pub(super) struct RepoCache {
/// Populated by `integration_reason()`, avoids redundant `compute_integration_lazy()`
/// calls when the same branch is checked multiple times (e.g., step_prune Phase 1
/// followed by prepare_worktree_removal).
- ///
- /// TODO: `handle_branch_only_output` creates a fresh `Repository::current()` for
- /// branch-only removals, bypassing this cache. Thread the pre-computed reason
- /// through `RemoveResult::BranchOnly` to eliminate that redundant check.
pub(super) integration_reasons: DashMap<(String, String), (String, Option<IntegrationReason>)>,
/// Tree SHA cache: tree spec (e.g., "refs/heads/main^{tree}") -> SHA.
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index aa9e79773..7f310aa96 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -9,9 +9,7 @@ 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, delete_branch_if_safe,
-};
+use crate::commands::branch_deletion::{BranchDeletionOutcome, BranchDeletionResult};
use crate::commands::command_executor::CommandContext;
use crate::commands::hooks::{
HookFailureStrategy, announce_and_spawn_background_hooks, execute_hook,
@@ -729,7 +727,16 @@ pub fn handle_remove_output(
branch_name,
deletion_mode,
pruned,
- } => handle_branch_only_output(branch_name, *deletion_mode, *pruned, quiet),
+ target_branch,
+ integration_reason,
+ } => handle_branch_only_output(
+ branch_name,
+ *deletion_mode,
+ *pruned,
+ *integration_reason,
+ target_branch.as_deref(),
+ quiet,
+ ),
}
}
@@ -741,6 +748,8 @@ fn handle_branch_only_output(
branch_name: &str,
deletion_mode: BranchDeletionMode,
pruned: bool,
+ integration_reason: Option<IntegrationReason>,
+ target_branch: Option<&str>,
quiet: bool,
) -> anyhow::Result<()> {
let branch_info = if pruned {
@@ -756,15 +765,34 @@ fn handle_branch_only_output(
return Ok(());
}
- let repo = worktrunk::git::Repository::current()?;
+ let check_target = target_branch.unwrap_or("HEAD");
- // Get default branch for integration check and reason display
- // Falls back to HEAD if default branch can't be determined
- let default_branch = repo.default_branch();
- let check_target = default_branch.as_deref().unwrap_or("HEAD");
+ // Decide outcome from pre-computed integration (computed in prepare_worktree_removal).
+ let outcome = if deletion_mode.is_force() {
+ Some(BranchDeletionOutcome::ForceDeleted)
+ } else {
+ integration_reason.map(BranchDeletionOutcome::Integrated)
+ };
- let result = delete_branch_if_safe(&repo, branch_name, check_target, deletion_mode.is_force());
- let deletion = handle_branch_deletion_result(result, branch_name)?;
+ let deletion = if let Some(outcome) = outcome {
+ let repo = worktrunk::git::Repository::current()?;
+ let result = repo.run_command(&["branch", "-D", branch_name]);
+ handle_branch_deletion_result(
+ result.map(|_| BranchDeletionResult {
+ outcome,
+ integration_target: check_target.to_string(),
+ }),
+ branch_name,
+ )?
+ } else {
+ BranchDeletionDisplay {
+ result: BranchDeletionResult {
+ outcome: BranchDeletionOutcome::NotDeleted,
+ integration_target: check_target.to_string(),
+ },
+ show_unmerged_hint: true,
+ }
+ };
if matches!(deletion.result.outcome, BranchDeletionOutcome::NotDeleted) {
eprintln!("{}", info_message(&branch_info));