Skip to content

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

refactor: consolidate merge/remove removal validation (#1625)

worktrunk-bot7f8a72a49932
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 531ea602a..8e2aeaef4 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -10,7 +10,9 @@ use super::commit::CommitOptions;
use super::context::CommandEnv;
use super::hooks::{HookFailureStrategy, execute_hook};
use super::project_config::{ApprovableCommand, collect_commands_for_hooks};
-use super::repository_ext::RepositoryCliExt;
+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,
@@ -138,21 +140,16 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
// Worktree for target is optional: if present we use it for safety checks and as destination.
let target_worktree_path = repo.worktree_for_branch(&target_branch)?;
- // When current == target or we're in the primary worktree, disable remove (can't remove it).
- // In normal repos, the primary worktree is the non-linked main worktree.
- // In bare repos, all worktrees are linked — protect the default branch worktree.
- let in_primary = !current_wt.is_linked().unwrap_or(false)
- || (repo.is_bare()?
- && repo
- .default_branch()
- .as_deref()
- .is_some_and(|db| db == current_branch));
+ // Quick check for command approval: will removal be attempted?
+ // The authoritative guard is prepare_merge_removal (shared with wt remove),
+ // but we need a lightweight answer here to decide whether to include
+ // pre-remove/post-remove hooks in the batch approval prompt.
let on_target = current_branch == target_branch;
- let remove_effective = remove && !on_target && !in_primary;
+ let remove_requested = remove && !on_target;
// Collect and approve all commands upfront for batch permission request
let (all_commands, project_id) =
- collect_merge_commands(repo, commit, verify, remove_effective, squash_enabled)?;
+ collect_merge_commands(repo, commit, verify, remove_requested, squash_enabled)?;
// Approve all commands in a single batch (shows templates, not expanded values)
let approvals = Approvals::load().context("Failed to load approvals")?;
@@ -251,58 +248,63 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
None => repo.home_path()?,
};
- // Finish worktree unless --no-remove was specified
- if remove_effective {
- // STEP 1: Check for uncommitted changes before attempting cleanup
- // This prevents showing "Cleaning up worktree..." before failing
+ // Finish worktree unless removal is disabled or blocked.
+ // Guards are shared with `wt remove`: is_primary_worktree (Phase 2) and
+ // check_not_default_branch (Phase 3) are the same helpers both paths use.
+ let removed = if !remove {
+ eprintln!("{}", info_message("Worktree preserved (--no-remove)"));
+ false
+ } else if on_target {
+ eprintln!(
+ "{}",
+ info_message("Worktree preserved (already on target branch)")
+ );
+ false
+ } else if is_primary_worktree(repo)? {
+ eprintln!("{}", info_message("Worktree preserved (primary worktree)"));
+ false
+ } else {
+ // Phase 3: reject removing default branch (merge always uses SafeDelete).
+ check_not_default_branch(repo, &current_branch, &BranchDeletionMode::SafeDelete)?;
+
+ let current_wt = repo.current_worktree();
current_wt.ensure_clean("remove worktree after merge", Some(&current_branch), false)?;
- // STEP 2: Remove worktree via shared remove output handler so final message matches wt remove
let worktree_root = current_wt.root()?;
- // After a successful merge, get integration reason
- let (_, integration_reason) = repo.integration_reason(&current_branch, &target_branch)?;
- // Compute expected_path for path mismatch detection
+ let integration_reason = compute_integration_reason(
+ repo,
+ Some(&current_branch),
+ Some(&target_branch),
+ BranchDeletionMode::SafeDelete,
+ );
let expected_path = path_mismatch(repo, &current_branch, &worktree_root, config);
- // Capture commit SHA before removal for post-remove hook template variables
let removed_commit = current_wt
.run_command(&["rev-parse", "HEAD"])
.ok()
.map(|s| s.trim().to_string());
+
let remove_result = RemoveResult::RemovedWorktree {
main_path: destination_path.clone(),
worktree_path: worktree_root,
changed_directory: true,
- branch_name: Some(current_branch.clone()),
+ branch_name: Some(current_branch.to_string()),
deletion_mode: BranchDeletionMode::SafeDelete,
- target_branch: Some(target_branch.clone()),
+ target_branch: Some(target_branch.to_string()),
integration_reason,
- // Don't force removal - if worktree has untracked files added after
- // commit, removal will fail and user can run `wt remove --force`
force_worktree: false,
expected_path,
removed_commit,
};
- // Run hooks during merge removal (pass through verify flag)
- // Approval was handled at the gate (collect_merge_commands)
crate::output::handle_remove_output(&remove_result, false, verify, false)?;
- } else {
- // Worktree preserved - show reason (priority: primary worktree > on target > --no-remove flag)
- let message = if in_primary {
- "Worktree preserved (primary worktree)"
- } else if on_target {
- "Worktree preserved (already on target branch)"
- } else {
- "Worktree preserved (--no-remove)"
- };
- eprintln!("{}", info_message(message));
- }
+ true
+ };
if verify {
// Execute post-merge commands in the destination worktree
// This runs after cleanup so the context is clear to the user
let ctx = CommandContext::new(repo, config, Some(&current_branch), &destination_path, yes);
// Show path when user's shell won't be in the destination directory where hooks run.
- let display_path = if remove_effective && !in_primary && !on_target {
+ let display_path = if removed {
// Worktree removed, user will cd to destination
crate::output::post_hook_display_path(&destination_path)
} else {
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index ffe1b7efa..a13611bcc 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -390,6 +390,17 @@ impl RepositoryCliExt for Repository {
}
}
+/// Check if the current worktree is the primary worktree (should not be removed).
+///
+/// Returns true for the main worktree in normal repos and the default branch
+/// worktree in bare repos. Used by `wt merge` to skip removal silently, and
+/// by `prepare_worktree_removal` Phase 2 (which errors instead of skipping).
+pub(crate) fn is_primary_worktree(repo: &Repository) -> anyhow::Result<bool> {
+ let current_root = repo.current_worktree().root()?;
+ let primary = repo.primary_worktree()?;
+ Ok(primary.as_deref() == Some(current_root.as_path()))
+}
+
/// Compute integration reason for branch deletion.
///
/// Returns `None` if:
@@ -400,7 +411,7 @@ impl RepositoryCliExt for Repository {
///
/// 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).
-fn compute_integration_reason(
+pub(crate) fn compute_integration_reason(
repo: &Repository,
branch_name: Option<&str>,
target_branch: Option<&str>,
@@ -421,7 +432,7 @@ fn compute_integration_reason(
///
/// The default branch is the integration target — checking it against itself is
/// tautological (same logic as `wt list`'s `is_main` guard in `check_integration_state`).
-fn check_not_default_branch(
+pub(crate) fn check_not_default_branch(
repo: &Repository,
branch: &str,
deletion_mode: &BranchDeletionMode,
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index 7542bc58a..727fe5b96 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -116,6 +116,15 @@ fn test_merge_already_on_target(repo: TestRepo) {
assert_cmd_snapshot!(make_snapshot_cmd(&repo, "merge", &[], None));
}
+#[rstest]
+fn test_merge_from_primary_worktree_to_other_branch(mut repo: TestRepo) {
+ // Create a feature branch with a commit, then merge from main worktree into it.
+ // Main worktree can't be removed, so should show "primary worktree" preservation.
+ let feature_wt = repo.add_feature();
+ drop(feature_wt); // we don't need the path; we'll run from main
+ assert_cmd_snapshot!(make_snapshot_cmd(&repo, "merge", &["feature"], None));
+}
+
#[rstest]
fn test_merge_dirty_working_tree(mut repo: TestRepo) {
// Create a feature worktree with uncommitted changes
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_already_on_target.snap b/tests/snapshots/integration__integration_tests__merge__merge_already_on_target.snap
index 7d9e4ee16..b066c85a8 100644
--- a/tests/snapshots/integration__integration_tests__merge__merge_already_on_target.snap
+++ b/tests/snapshots/integration__integration_tests__merge__merge_already_on_target.snap
@@ -42,4 +42,4 @@ exit_code: 0
----- stderr -----
○ Already up to date with main (no new commits, no rebase needed)
-○ Worktree preserved (primary worktree)
+○ Worktree preserved (already on target branch)
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_from_primary_worktree_to_other_branch.snap b/tests/snapshots/integration__integration_tests__merge__merge_from_primary_worktree_to_other_branch.snap
new file mode 100644
index 000000000..e26b2bd98
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_from_primary_worktree_to_other_branch.snap
@@ -0,0 +1,47 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ - feature
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Fast-forwarded to feature
+○ Already up to date with feature (no new commits)
+○ Worktree preserved (primary worktree)
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_post_merge_runs_from_main_branch.snap b/tests/snapshots/integration__integration_tests__merge__merge_post_merge_runs_from_main_branch.snap
index 749f23c98..196230e83 100644
--- a/tests/snapshots/integration__integration_tests__merge__merge_post_merge_runs_from_main_branch.snap
+++ b/tests/snapshots/integration__integration_tests__merge__merge_post_merge_runs_from_main_branch.snap
@@ -43,6 +43,6 @@ exit_code: 0
----- stderr -----
○ Already up to date with main (no new commits, no rebase needed)
-○ Worktree preserved (primary worktree)
+○ Worktree preserved (already on target branch)
◎ Running post-merge project hook
  echo 'post-merge ran from main' > post-merge-ran.txt
diff --git a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__merge.snap b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__merge.snap
index b02664cb6..8eb7d56d9 100644
--- a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__merge.snap
+++ b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__merge.snap
@@ -4,4 +4,4 @@ expression: "&output.combined"
---
○ Already up to date with main (no new commits, no rebase needed)
-○ Worktree preserved (primary worktree)
+○ Worktree preserved (already on target branch)