Skip to content

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

Enhance branch deletion to handle squash merges

Maximilian Roosa81498c15779
diff --git a/README.md b/README.md
index 37762f532..3f548999d 100644
--- a/README.md
+++ b/README.md
@@ -624,6 +624,17 @@ Removes worktree directory, git metadata, and branch. Requires clean working tre
- Removes specified worktree(s) and branches
- Current worktree removed last (switches to main first)
+### Branch deletion
+
+By default, branches are deleted only when their content has been integrated:
+
+- Traditional merge: branch is an ancestor of the target (git's `-d` behavior)
+- Squash merge/rebase: branch's tree SHA matches target's tree SHA
+
+This handles workflows where PRs are squash-merged or rebased, which don't preserve
+commit ancestry but do integrate the content. Use `-D` to delete unintegrated
+branches, or `--no-delete-branch` to always keep branches.
+
### Background removal (default)
- Returns immediately for continued work
diff --git a/src/cli.rs b/src/cli.rs
index 80db6b68a..d103f30c9 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -866,6 +866,17 @@ Removes worktree directory, git metadata, and branch. Requires clean working tre
- Removes specified worktree(s) and branches
- Current worktree removed last (switches to main first)
+### Branch deletion
+
+By default, branches are deleted only when their content has been integrated:
+
+- Traditional merge: branch is an ancestor of the target (git's `-d` behavior)
+- Squash merge/rebase: branch's tree SHA matches target's tree SHA
+
+This handles workflows where PRs are squash-merged or rebased, which don't preserve
+commit ancestry but do integrate the content. Use `-D` to delete unintegrated
+branches, or `--no-delete-branch` to always keep branches.
+
### Background removal (default)
- Returns immediately for continued work
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 764488ef7..a57bd70b2 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -1067,12 +1067,21 @@ impl Repository {
Ok(branch)
}
+ /// Check if two refs have identical tree content (same files/directories).
+ /// Returns true when content is identical even if commit history differs.
+ ///
+ /// Useful for detecting squash merges or rebases where the content has been
+ /// integrated but commit ancestry doesn't show the relationship.
+ pub fn trees_match(&self, ref1: &str, ref2: &str) -> anyhow::Result<bool> {
+ let tree1 = self.rev_parse_tree(&format!("{ref1}^{{tree}}"))?;
+ let tree2 = self.rev_parse_tree(&format!("{ref2}^{{tree}}"))?;
+ Ok(tree1 == tree2)
+ }
+
/// Check if HEAD's tree SHA matches a branch's tree SHA.
/// Returns true when content is identical even if commit history differs.
pub fn head_tree_matches_branch(&self, branch: &str) -> anyhow::Result<bool> {
- let head_tree = self.rev_parse_tree("HEAD^{tree}")?;
- let branch_tree = self.rev_parse_tree(&format!("{branch}^{{tree}}"))?;
- Ok(head_tree == branch_tree)
+ self.trees_match("HEAD", branch)
}
fn rev_parse_tree(&self, spec: &str) -> anyhow::Result<String> {
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 5844358e4..b7f19ca8e 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -4,12 +4,87 @@ use crate::commands::process::spawn_detached;
use crate::commands::worktree::{RemoveResult, SwitchResult};
use crate::output::global::format_switch_success;
use worktrunk::git::GitError;
+use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
use worktrunk::shell::Shell;
use worktrunk::styling::{
CYAN, CYAN_BOLD, GREEN, GREEN_BOLD, WARNING, WARNING_BOLD, format_with_gutter,
};
+/// Check if a branch's content has been integrated into the target.
+///
+/// Returns true if the branch is safe to delete because either:
+/// - The branch is an ancestor of the target (traditional merge), OR
+/// - The branch's tree SHA matches the target's tree SHA (squash merge/rebase)
+///
+/// Returns false 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
+/// be determined.
+fn is_branch_integrated(repo: &Repository, branch_name: &str, target: &str) -> bool {
+ // Check traditional merge relationship
+ if repo.is_ancestor(branch_name, target).unwrap_or(false) {
+ return true;
+ }
+
+ // Check if tree content matches (handles squash merge/rebase)
+ repo.trees_match(branch_name, target).unwrap_or(false)
+}
+
+/// Attempt to delete a branch if it's integrated or force_delete is set.
+///
+/// Returns:
+/// - `Ok(true)` if branch was deleted
+/// - `Ok(false)` if branch was not deleted (not integrated, and not force)
+/// - `Err` if git command failed
+fn delete_branch_if_safe(
+ repo: &Repository,
+ branch_name: &str,
+ target: &str,
+ force_delete: bool,
+) -> anyhow::Result<bool> {
+ if !force_delete && !is_branch_integrated(repo, branch_name, target) {
+ return Ok(false);
+ }
+ repo.run_command(&["branch", "-D", branch_name])?;
+ Ok(true)
+}
+
+/// Handle the result of a branch deletion attempt.
+///
+/// Shows appropriate warnings for non-deleted branches.
+///
+/// Returns:
+/// - `Ok(true)` if branch was deleted
+/// - `Ok(false)` if branch was not deleted (warning shown)
+fn handle_branch_deletion_result(
+ result: anyhow::Result<bool>,
+ branch_name: &str,
+) -> anyhow::Result<bool> {
+ match result {
+ Ok(true) => Ok(true),
+ Ok(false) => {
+ // Branch not integrated - show warning
+ super::warning(format!(
+ "{WARNING}Could not delete branch {WARNING_BOLD}{branch_name}{WARNING_BOLD:#}{WARNING:#}"
+ ))?;
+ super::gutter(format_with_gutter(
+ &format!("error: the branch '{}' is not fully merged", branch_name),
+ "",
+ None,
+ ))?;
+ Ok(false)
+ }
+ Err(e) => {
+ // Git command failed - show warning with error details
+ super::warning(format!(
+ "{WARNING}Could not delete branch {WARNING_BOLD}{branch_name}{WARNING_BOLD:#}{WARNING:#}"
+ ))?;
+ super::gutter(format_with_gutter(&e.to_string(), "", None))?;
+ Ok(false)
+ }
+ }
+}
+
/// Get flag acknowledgment note for remove messages
fn get_flag_note(no_delete_branch: bool, force_delete: bool, branch_deleted: bool) -> &'static str {
if no_delete_branch {
@@ -240,49 +315,18 @@ fn handle_branch_only_output(
}
let repo = worktrunk::git::Repository::current();
+ let result = delete_branch_if_safe(&repo, branch_name, "HEAD", force_delete);
+ let deleted = handle_branch_deletion_result(result, branch_name)?;
- // Use git branch -D if force_delete is true, otherwise check if merged first
- let delete_result = if force_delete {
- // Force delete - use -D directly
- repo.run_command(&["branch", "-D", branch_name])
- } else {
- // Check if branch is merged to HEAD using is_ancestor
- match repo.is_ancestor(branch_name, "HEAD") {
- Ok(true) => {
- // Branch is an ancestor of HEAD (fully merged), safe to delete
- repo.run_command(&["branch", "-D", branch_name])
- }
- Ok(false) | Err(_) => {
- // Branch is not fully merged
- Err(anyhow::anyhow!(
- "error: the branch '{}' is not fully merged",
- branch_name
- ))
- }
- }
- };
-
- match delete_result {
- Ok(_) => {
- // Branch removed successfully
- let flag_note = if force_delete {
- " (--force-delete)"
- } else {
- ""
- };
- super::success(format!(
- "{GREEN}Removed branch {GREEN_BOLD}{branch_name}{GREEN_BOLD:#}{GREEN:#}{flag_note}"
- ))?;
- }
- Err(e) => {
- // Show a warning but don't error - branch still exists
- 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)
- super::gutter(format_with_gutter(&e.to_string(), "", None))?;
- }
+ if deleted {
+ let flag_note = if force_delete {
+ " (--force-delete)"
+ } else {
+ ""
+ };
+ super::success(format!(
+ "{GREEN}Removed branch {GREEN_BOLD}{branch_name}{GREEN_BOLD:#}{GREEN:#}{flag_note}"
+ ))?;
}
super::flush()?;
@@ -320,12 +364,10 @@ fn handle_removed_worktree_output(
// Force delete requested - always delete
true
} else {
- // Check if branch is fully merged to target
+ // Check if branch is integrated (ancestor or matching tree content)
let check_target = target_branch.unwrap_or("HEAD");
let deletion_repo = worktrunk::git::Repository::at(main_path);
- deletion_repo
- .is_ancestor(branch_name, check_target)
- .unwrap_or(false)
+ is_branch_integrated(&deletion_repo, branch_name, check_target)
};
// Show progress message based on what we'll do
@@ -379,43 +421,10 @@ fn handle_removed_worktree_output(
// Delete the branch (unless --no-delete-branch was specified)
let branch_deleted = if !no_delete_branch {
let deletion_repo = worktrunk::git::Repository::at(main_path);
-
- // Use git branch -D if force_delete is true, otherwise check if merged first
- let delete_result = if force_delete {
- // Force delete - use -D directly
- deletion_repo.run_command(&["branch", "-D", branch_name])
- } else {
- let check_target = target_branch.unwrap_or("HEAD");
-
- // Check if branch is merged to target using is_ancestor
- match deletion_repo.is_ancestor(branch_name, check_target) {
- Ok(true) => {
- // Branch is an ancestor of target (fully merged), safe to delete
- deletion_repo.run_command(&["branch", "-D", branch_name])
- }
- Ok(false) | Err(_) => {
- // Branch is not fully merged to target
- Err(anyhow::anyhow!(
- "error: the branch '{}' is not fully merged",
- branch_name
- ))
- }
- }
- };
-
- match delete_result {
- Ok(_) => true,
- Err(e) => {
- // Show a warning but don't error - branch still exists
- 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)
- super::gutter(format_with_gutter(&e.to_string(), "", None))?;
- false
- }
- }
+ let check_target = target_branch.unwrap_or("HEAD");
+ let result =
+ delete_branch_if_safe(&deletion_repo, branch_name, check_target, force_delete);
+ handle_branch_deletion_result(result, branch_name)?
} else {
false
};
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 30dd03a17..1de987274 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -329,3 +329,77 @@ fn test_remove_branch_only_force_delete() {
None,
);
}
+
+/// Test that a branch with matching tree content (but not an ancestor) is deleted.
+///
+/// This simulates a squash merge workflow where:
+/// - Feature branch has commits ahead of main
+/// - Main is updated (e.g., via squash merge on GitHub) with the same content
+/// - Branch is NOT an ancestor of main, but tree SHAs match
+/// - Branch should be deleted because content is integrated
+#[test]
+fn test_remove_branch_matching_tree_content() {
+ let repo = setup_remove_repo();
+
+ // Create a feature branch from main
+ repo.git_command(&["branch", "feature-squashed"])
+ .output()
+ .unwrap();
+
+ // On feature branch: add a file
+ repo.git_command(&["checkout", "feature-squashed"])
+ .output()
+ .unwrap();
+ std::fs::write(repo.root_path().join("feature.txt"), "squash content").unwrap();
+ repo.git_command(&["add", "feature.txt"]).output().unwrap();
+ repo.git_command(&["commit", "-m", "Add feature (on feature branch)"])
+ .output()
+ .unwrap();
+
+ // On main: add the same file with same content (simulates squash merge result)
+ repo.git_command(&["checkout", "main"]).output().unwrap();
+ std::fs::write(repo.root_path().join("feature.txt"), "squash content").unwrap();
+ repo.git_command(&["add", "feature.txt"]).output().unwrap();
+ repo.git_command(&["commit", "-m", "Add feature (squash merged)"])
+ .output()
+ .unwrap();
+
+ // Verify the setup: feature-squashed is NOT an ancestor of main (different commits)
+ let is_ancestor = repo
+ .git_command(&["merge-base", "--is-ancestor", "feature-squashed", "main"])
+ .output()
+ .unwrap();
+ assert!(
+ !is_ancestor.status.success(),
+ "feature-squashed should NOT be an ancestor of main"
+ );
+
+ // Verify: tree SHAs should match
+ let feature_tree = String::from_utf8(
+ repo.git_command(&["rev-parse", "feature-squashed^{tree}"])
+ .output()
+ .unwrap()
+ .stdout,
+ )
+ .unwrap();
+ let main_tree = String::from_utf8(
+ repo.git_command(&["rev-parse", "main^{tree}"])
+ .output()
+ .unwrap()
+ .stdout,
+ )
+ .unwrap();
+ assert_eq!(
+ feature_tree.trim(),
+ main_tree.trim(),
+ "Tree SHAs should match (same content)"
+ );
+
+ // Remove the branch - should succeed because tree content matches main
+ snapshot_remove(
+ "remove_branch_matching_tree_content",
+ &repo,
+ &["feature-squashed"],
+ None,
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__help__help_remove.snap b/tests/snapshots/integration__integration_tests__help__help_remove.snap
index 145f81e55..6876351d6 100644
--- a/tests/snapshots/integration__integration_tests__help__help_remove.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_remove.snap
@@ -9,6 +9,7 @@ info:
CLICOLOR_FORCE: "1"
COLUMNS: "150"
GIT_EDITOR: ""
+ SOURCE_DATE_EPOCH: "1735776000"
WORKTRUNK_BIN: ""
WORKTRUNK_CONFIG_PATH: /nonexistent/test/config.toml
---
@@ -61,6 +62,17 @@ Removes worktree directory, git metadata, and branch. Requires clean working tre
- Removes specified worktree(s) and branches
- Current worktree removed last (switches to main first)
+### Branch deletion
+
+By default, branches are deleted only when their content has been integrated:
+
+- Traditional merge: branch is an ancestor of the target (git's -d behavior)
+- Squash merge/rebase: branch's tree SHA matches target's tree SHA
+
+This handles workflows where PRs are squash-merged or rebased, which don't preserve
+commit ancestry but do integrate the content. Use -D to delete unintegrated
+branches, or --no-delete-branch to always keep branches.
+
### Background removal (default)
- Returns immediately for continued work
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
new file mode 100644
index 000000000..6f02d61d8
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_branch_matching_tree_content.snap
@@ -0,0 +1,28 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - feature-squashed
+ 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_BIN: ""
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+⚪ No worktree found for branch feature-squashed
+✅ Removed branch feature-squashed
+
+----- stderr -----