Skip to content

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

feat: Add merge simulation check for branch integration

Maximilian Roos4e242fabc86c
diff --git a/CLAUDE.md b/CLAUDE.md
index 185082024..fc4adf5e8 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -170,6 +170,7 @@ Use consistent punctuation and structure for related messages:
// Both wt merge and wt remove show integration reason when branch is deleted
"Removing feature worktree & branch in background (already in main)" // Branch is integrated (ancestor)
"Removing feature worktree & branch in background (files match main)" // Branch is integrated (squash/rebase)
+"Removing feature worktree & branch in background (all changes in main)" // Branch is integrated (squash + main advanced)
"Removing feature worktree in background; retaining unmerged branch" // Unmerged (system keeps)
"Removing feature worktree in background; retaining branch (--no-delete-branch)" // User flag (user keeps)
```
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index b73fe731d..bc76ac216 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -1092,6 +1092,44 @@ impl Repository {
Ok(!clean_merge)
}
+ /// Check if merging a branch into target would add anything (not already integrated).
+ ///
+ /// Uses `git merge-tree` to simulate merging the branch into the target. If the
+ /// resulting tree matches the target's tree, then merging would add nothing,
+ /// meaning the branch's content is already integrated.
+ ///
+ /// This handles cases that simple tree comparison misses:
+ /// - Squash-merged branches where main has advanced with additional commits
+ /// - Rebased branches where the base has moved forward
+ ///
+ /// Returns:
+ /// - `Ok(true)` if merging would change the target (branch has unintegrated changes)
+ /// - `Ok(false)` if merging would NOT change target (branch is already integrated)
+ /// - `Ok(true)` if merge would have conflicts (conservative: treat as not integrated)
+ /// - `Err` if git commands fail
+ pub fn would_merge_add_to_target(&self, branch: &str, target: &str) -> anyhow::Result<bool> {
+ // Simulate merging branch into target
+ // On conflict, merge-tree exits non-zero and we can't get a clean tree
+ let merge_result = self.run_command(&["merge-tree", "--write-tree", target, branch]);
+
+ let Ok(merge_tree) = merge_result else {
+ // merge-tree failed (likely conflicts) - conservatively treat as having changes
+ return Ok(true);
+ };
+
+ let merge_tree = merge_tree.trim();
+ if merge_tree.is_empty() {
+ // Empty output is unexpected - treat as having changes
+ return Ok(true);
+ }
+
+ // Get target's tree for comparison
+ let target_tree = self.rev_parse_tree(&format!("{target}^{{tree}}"))?;
+
+ // If merge result differs from target's tree, merging would add something
+ Ok(merge_tree != target_tree)
+ }
+
/// Get commit subjects (first line of commit message) from a range.
pub fn commit_subjects(&self, range: &str) -> anyhow::Result<Vec<String>> {
let output = self.run_command(&["log", "--format=%s", range])?;
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index e6896611c..47574d422 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -52,6 +52,9 @@ enum IntegrationReason {
NoMarginalContribution,
/// Branch's tree SHA matches target's tree SHA (squash merge/rebase)
ContentsMatch,
+ /// Merge simulation shows branch would add nothing to target
+ /// (squash merge where target has since advanced)
+ MergeAddsNothing,
}
/// Check if a branch's content has been integrated into the target.
@@ -59,6 +62,7 @@ enum IntegrationReason {
/// Returns the reason if the branch is safe to delete:
/// - `NoMarginalContribution`: The branch has no marginal contribution to target (ancestor, merged back, etc.)
/// - `ContentsMatch`: The branch's tree SHA matches the target's tree SHA (squash merge/rebase)
+/// - `MergeAddsNothing`: Merge simulation shows branch would add nothing (squash + target advanced)
///
/// Returns None if neither condition is met, or if an error occurs (e.g., invalid refs).
/// This fail-safe default prevents accidental branch deletion when integration cannot
@@ -82,6 +86,16 @@ fn get_integration_reason(
return Some(IntegrationReason::ContentsMatch);
}
+ // Check via merge simulation: would merging this branch into target add anything?
+ // This handles squash-merged branches where target has since advanced.
+ // If merge would NOT add anything, the branch's content is already in target.
+ if !repo
+ .would_merge_add_to_target(branch_name, target)
+ .unwrap_or(true)
+ {
+ return Some(IntegrationReason::MergeAddsNothing);
+ }
+
None
}
@@ -164,6 +178,9 @@ fn get_flag_note(
format!(" (already in {target})")
}
Some(Some(IntegrationReason::ContentsMatch)) => format!(" (files match {target})"),
+ Some(Some(IntegrationReason::MergeAddsNothing)) => {
+ format!(" (all changes in {target})")
+ }
Some(None) | None => String::new(),
}
} else {
@@ -395,14 +412,23 @@ fn handle_branch_only_output(
}
let repo = worktrunk::git::Repository::current();
- let result = delete_branch_if_safe(&repo, branch_name, "HEAD", force_delete);
+
+ // 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().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 integration_reason = handle_branch_deletion_result(result, branch_name)?;
if integration_reason.is_some() {
- let flag_note = get_flag_note(no_delete_branch, force_delete, integration_reason, None);
- super::success(cformat!(
- "<green>Removed branch <bold>{branch_name}</>{flag_note}</>"
- ))?;
+ let flag_note = get_flag_note(
+ no_delete_branch,
+ force_delete,
+ integration_reason,
+ default_branch.as_deref(),
+ );
+ super::success(cformat!("Removed branch <bold>{branch_name}</>{flag_note}"))?;
}
super::flush()?;
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index cc20f741e..cb8d7eba6 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -622,3 +622,95 @@ fn test_remove_default_branch_no_tautology() {
assert_cmd_snapshot!("remove_default_branch_no_tautology", cmd);
});
}
+
+/// Test that a squash-merged branch is detected as integrated even when main advances.
+///
+/// This tests the scenario:
+/// 1. Create feature branch from main and make changes (file A)
+/// 2. Squash-merge feature into main (main now has A via squash commit)
+/// 3. Main advances with more commits (file B)
+/// 4. Try to remove feature
+///
+/// The branch should be detected as integrated because its content (A) is
+/// already in main, even though main has additional content (B).
+///
+/// This is detected via merge simulation: `git merge-tree --write-tree main feature`
+/// produces the same tree as main, meaning merging feature would add nothing.
+#[test]
+fn test_remove_squash_merged_then_main_advanced() {
+ let repo = setup_remove_repo();
+
+ // Create feature branch
+ repo.git_command(&["checkout", "-b", "feature-squash"])
+ .output()
+ .unwrap();
+
+ // Make changes on feature branch (file A)
+ std::fs::write(repo.root_path().join("feature-a.txt"), "feature content").unwrap();
+ repo.git_command(&["add", "feature-a.txt"])
+ .output()
+ .unwrap();
+ repo.git_command(&["commit", "-m", "Add feature A"])
+ .output()
+ .unwrap();
+
+ // Go back to main
+ repo.git_command(&["checkout", "main"]).output().unwrap();
+
+ // Squash merge feature into main (simulating GitHub squash merge)
+ // This creates a NEW commit on main with the same content changes
+ std::fs::write(repo.root_path().join("feature-a.txt"), "feature content").unwrap();
+ repo.git_command(&["add", "feature-a.txt"])
+ .output()
+ .unwrap();
+ repo.git_command(&["commit", "-m", "Add feature A (squash merged)"])
+ .output()
+ .unwrap();
+
+ // Main advances with another commit (file B)
+ std::fs::write(repo.root_path().join("main-b.txt"), "main content").unwrap();
+ repo.git_command(&["add", "main-b.txt"]).output().unwrap();
+ repo.git_command(&["commit", "-m", "Main advances with B"])
+ .output()
+ .unwrap();
+
+ // Verify setup: feature-squash is NOT an ancestor of main (squash creates different SHAs)
+ let is_ancestor = repo
+ .git_command(&["merge-base", "--is-ancestor", "feature-squash", "main"])
+ .output()
+ .unwrap();
+ assert!(
+ !is_ancestor.status.success(),
+ "feature-squash should NOT be an ancestor of main (squash merge)"
+ );
+
+ // Verify setup: trees don't match (main has file B that feature doesn't)
+ let feature_tree = String::from_utf8(
+ repo.git_command(&["rev-parse", "feature-squash^{tree}"])
+ .output()
+ .unwrap()
+ .stdout,
+ )
+ .unwrap();
+ let main_tree = String::from_utf8(
+ repo.git_command(&["rev-parse", "main^{tree}"])
+ .output()
+ .unwrap()
+ .stdout,
+ )
+ .unwrap();
+ assert_ne!(
+ feature_tree.trim(),
+ main_tree.trim(),
+ "Tree SHAs should differ (main has file B that feature doesn't)"
+ );
+
+ // Remove the feature branch - should succeed because content is integrated
+ // (detected via merge simulation using git merge-tree)
+ snapshot_remove(
+ "remove_squash_merged_then_main_advanced",
+ &repo,
+ &["feature-squash"],
+ None,
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_branch_matching_tree_content.snap b/tests/snapshots/integration__integration_tests__remove__remove_branch_matching_tree_content.snap
index fb3cdf0da..abe5cf1e3 100644
--- a/tests/snapshots/integration__integration_tests__remove__remove_branch_matching_tree_content.snap
+++ b/tests/snapshots/integration__integration_tests__remove__remove_branch_matching_tree_content.snap
@@ -24,4 +24,4 @@ exit_code: 0
----- stderr -----
🟑 No worktree found for branch feature-squashed
-βœ… Removed branch feature-squashed
+βœ… Removed branch feature-squashed (files match main)
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_branch_only_force_delete.snap b/tests/snapshots/integration__integration_tests__remove__remove_branch_only_force_delete.snap
index 21b9667d6..e3c8a90ef 100644
--- a/tests/snapshots/integration__integration_tests__remove__remove_branch_only_force_delete.snap
+++ b/tests/snapshots/integration__integration_tests__remove__remove_branch_only_force_delete.snap
@@ -25,4 +25,4 @@ exit_code: 0
----- stderr -----
🟑 No worktree found for branch feature-force
-βœ… Removed branch feature-force (--force-delete)
+βœ… Removed branch feature-force (--force-delete)
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_branch_only_merged.snap b/tests/snapshots/integration__integration_tests__remove__remove_branch_only_merged.snap
index d7880771b..0dd554f0a 100644
--- a/tests/snapshots/integration__integration_tests__remove__remove_branch_only_merged.snap
+++ b/tests/snapshots/integration__integration_tests__remove__remove_branch_only_merged.snap
@@ -24,4 +24,4 @@ exit_code: 0
----- stderr -----
🟑 No worktree found for branch feature-merged
-βœ… Removed branch feature-merged
+βœ… Removed branch feature-merged (already in main)
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_squash_merged_then_main_advanced.snap b/tests/snapshots/integration__integration_tests__remove__remove_squash_merged_then_main_advanced.snap
new file mode 100644
index 000000000..84652c4ff
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_squash_merged_then_main_advanced.snap
@@ -0,0 +1,27 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - feature-squash
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ 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: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1735776000"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+🟑 No worktree found for branch feature-squash
+βœ… Removed branch feature-squash (all changes in main)