Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: resolve tag/branch collision in integration checks (#694)
Maximilian Roosca2d1208433c
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rsindex bca81ba30..4f4f19d12 100644--- a/src/git/repository/integration.rs+++ b/src/git/repository/integration.rs@@ -7,19 +7,40 @@ use super::Repository;use crate::git::{IntegrationReason, check_integration, compute_integration_lazy};impl Repository {+ /// Resolve a ref, preferring branches over tags when names collide.+ ///+ /// Uses git to check if `refs/heads/{ref}` exists. If so, returns the+ /// qualified form to ensure we reference the branch, not a same-named tag.+ /// Otherwise returns the original ref unchanged (for HEAD, SHAs, remote refs).+ fn resolve_preferring_branch(&self, r: &str) -> String {+ let qualified = format!("refs/heads/{r}");+ if self+ .run_command(&["rev-parse", "--verify", "-q", &qualified])+ .is_ok()+ {+ qualified+ } else {+ r.to_string()+ }+ }+/// Check if base is an ancestor of head (i.e., would be a fast-forward).////// See [`--is-ancestor`][1] for details.////// [1]: https://git-scm.com/docs/git-merge-base#Documentation/git-merge-base.txt---is-ancestorpub fn is_ancestor(&self, base: &str, head: &str) -> anyhow::Result<bool> {- self.run_command_check(&["merge-base", "--is-ancestor", base, head])+ let base = self.resolve_preferring_branch(base);+ let head = self.resolve_preferring_branch(head);+ self.run_command_check(&["merge-base", "--is-ancestor", &base, &head])}/// Check if two refs point to the same commit.pub fn same_commit(&self, ref1: &str, ref2: &str) -> anyhow::Result<bool> {+ let ref1 = self.resolve_preferring_branch(ref1);+ let ref2 = self.resolve_preferring_branch(ref2);// Parse both refs in a single git command- let output = self.run_command(&["rev-parse", ref1, ref2])?;+ let output = self.run_command(&["rev-parse", &ref1, &ref2])?;let mut lines = output.lines();let sha1 = lines.next().unwrap_or_default().trim();let sha2 = lines.next().unwrap_or_default().trim();@@ -34,8 +55,10 @@ impl Repository {/// For orphan branches (no common ancestor with target), returns true since all/// their changes are unique.pub fn has_added_changes(&self, branch: &str, target: &str) -> anyhow::Result<bool> {+ let branch = self.resolve_preferring_branch(branch);+ let target = self.resolve_preferring_branch(target);// Try to get merge-base (cached). Orphan branches return None.- let Some(merge_base) = self.merge_base(target, branch)? else {+ let Some(merge_base) = self.merge_base(&target, &branch)? else {// Orphan branches have no common ancestor, so all their changes are uniquereturn Ok(true);};@@ -52,6 +75,8 @@ impl Repository {/// 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 ref1 = self.resolve_preferring_branch(ref1);+ let ref2 = self.resolve_preferring_branch(ref2);// Parse both tree refs in a single git commandlet output = self.run_command(&["rev-parse",@@ -84,10 +109,12 @@ impl Repository {/// # Ok::<(), anyhow::Error>(())/// ```pub fn has_merge_conflicts(&self, base: &str, head: &str) -> anyhow::Result<bool> {+ let base = self.resolve_preferring_branch(base);+ let head = self.resolve_preferring_branch(head);// Use modern merge-tree --write-tree mode which exits with 1 when conflicts exist// (the old 3-argument deprecated mode always exits with 0)// run_command_check returns true for exit 0, false otherwise- let clean_merge = self.run_command_check(&["merge-tree", "--write-tree", base, head])?;+ let clean_merge = self.run_command_check(&["merge-tree", "--write-tree", &base, &head])?;Ok(!clean_merge)}@@ -107,9 +134,11 @@ impl Repository {/// - `Ok(true)` if merge would have conflicts (conservative: treat as not integrated)/// - `Err` if git commands failpub fn would_merge_add_to_target(&self, branch: &str, target: &str) -> anyhow::Result<bool> {+ let branch = self.resolve_preferring_branch(branch);+ let target = self.resolve_preferring_branch(target);// 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 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 changesdiff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rsindex 73a6e54a6..0b858795a 100644--- a/tests/integration_tests/repository.rs+++ b/tests/integration_tests/repository.rs@@ -335,3 +335,168 @@ fn test_set_config() {let value = repository.get_config("test.setting").unwrap();assert_eq!(value, Some("new-value".to_string()));}++// =============================================================================+// Bug #1: Tag/branch name collision tests+// =============================================================================++/// When a tag and branch share the same name, git resolves unqualified refs to+/// the tag by default. This can cause is_ancestor() to return incorrect results+/// if the tag points to a different commit than the branch.+///+/// This test verifies that integration checking uses qualified refs (refs/heads/)+/// to avoid this ambiguity.+#[test]+fn test_tag_branch_name_collision_is_ancestor() {+ let repo = TestRepo::new();++ // Create initial commit on main (already exists from TestRepo::new())+ let main_sha = repo.git_output(&["rev-parse", "HEAD"]);++ // Create feature branch with additional commits+ repo.run_git(&["checkout", "-b", "feature"]);+ fs::write(repo.root_path().join("feature.txt"), "feature content").unwrap();+ repo.run_git(&["add", "feature.txt"]);+ repo.run_git(&["commit", "-m", "Feature commit"]);++ // Create a tag named "feature" pointing to the MAIN commit (earlier)+ // This simulates the scenario where someone creates a tag with the same name+ repo.run_git(&["tag", "feature", &main_sha]);++ // Now git has ambiguity: "feature" could be the tag (at main_sha) or the branch (ahead)+ // The branch "feature" is NOT an ancestor of main (it's ahead)+ // But the tag "feature" points to main_sha, which IS an ancestor of main (same commit)++ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();++ // Without qualified refs, this would incorrectly return true+ // (checking the tag, which equals main, instead of the branch, which is ahead)+ // With the fix (using refs/heads/), this should correctly return false+ let result = repository.is_ancestor("feature", "main").unwrap();++ // The branch "feature" is ahead of main, so it should NOT be an ancestor+ assert!(+ !result,+ "is_ancestor should check the branch 'feature', not the tag 'feature'"+ );+}++/// Test that same_commit() correctly distinguishes between tag and branch+/// when they share the same name but point to different commits.+#[test]+fn test_tag_branch_name_collision_same_commit() {+ let repo = TestRepo::new();++ // Get main's SHA+ let main_sha = repo.git_output(&["rev-parse", "HEAD"]);++ // Create feature branch with additional commits+ repo.run_git(&["checkout", "-b", "feature"]);+ fs::write(repo.root_path().join("feature.txt"), "feature content").unwrap();+ repo.run_git(&["add", "feature.txt"]);+ repo.run_git(&["commit", "-m", "Feature commit"]);++ // Create a tag named "feature" pointing to main (different from branch)+ repo.run_git(&["tag", "feature", &main_sha]);++ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();++ // The branch "feature" is NOT at the same commit as main+ // But the tag "feature" IS at the same commit as main+ // Without qualified refs, this would incorrectly return true+ let result = repository.same_commit("feature", "main").unwrap();++ assert!(+ !result,+ "same_commit should check the branch 'feature', not the tag 'feature'"+ );+}++/// Test that trees_match() correctly distinguishes between tag and branch+/// when they share the same name but point to commits with different trees.+#[test]+fn test_tag_branch_name_collision_trees_match() {+ let repo = TestRepo::new();++ // Get main's SHA+ let main_sha = repo.git_output(&["rev-parse", "HEAD"]);++ // Create feature branch with different content+ repo.run_git(&["checkout", "-b", "feature"]);+ fs::write(repo.root_path().join("feature.txt"), "feature content").unwrap();+ repo.run_git(&["add", "feature.txt"]);+ repo.run_git(&["commit", "-m", "Feature commit"]);++ // Create a tag named "feature" pointing to main (different tree)+ repo.run_git(&["tag", "feature", &main_sha]);++ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();++ // The branch "feature" has different tree content than main+ // But the tag "feature" has the same tree as main+ // Without qualified refs, this would incorrectly return true+ let result = repository.trees_match("feature", "main").unwrap();++ assert!(+ !result,+ "trees_match should check the branch 'feature', not the tag 'feature'"+ );+}++/// Test that integration functions correctly handle HEAD (not a branch).+#[test]+fn test_integration_functions_handle_head() {+ let repo = TestRepo::new();++ // Create a commit so HEAD differs from an empty state+ fs::write(repo.root_path().join("file.txt"), "content").unwrap();+ repo.run_git(&["add", "file.txt"]);+ repo.run_git(&["commit", "-m", "Add file"]);++ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();++ // HEAD should work in all integration functions+ // (resolve_preferring_branch should pass HEAD through unchanged)+ assert!(repository.same_commit("HEAD", "main").unwrap());+ assert!(repository.is_ancestor("main", "HEAD").unwrap());+ assert!(repository.trees_match("HEAD", "main").unwrap());+}++/// Test that integration functions correctly handle commit SHAs.+#[test]+fn test_integration_functions_handle_shas() {+ let repo = TestRepo::new();++ let main_sha = repo.git_output(&["rev-parse", "HEAD"]);++ // Create feature branch+ repo.run_git(&["checkout", "-b", "feature"]);+ fs::write(repo.root_path().join("feature.txt"), "content").unwrap();+ repo.run_git(&["add", "feature.txt"]);+ repo.run_git(&["commit", "-m", "Feature"]);++ let feature_sha = repo.git_output(&["rev-parse", "HEAD"]);++ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();++ // SHAs should work in all integration functions+ // (resolve_preferring_branch should pass SHAs through unchanged)+ assert!(repository.same_commit(&main_sha, "main").unwrap());+ assert!(!repository.same_commit(&feature_sha, &main_sha).unwrap());+ assert!(repository.is_ancestor(&main_sha, &feature_sha).unwrap());+}++/// Test that integration functions correctly handle remote refs.+#[test]+fn test_integration_functions_handle_remote_refs() {+ let mut repo = TestRepo::new();+ repo.setup_remote("main");++ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();++ // Remote refs like origin/main should work+ // (resolve_preferring_branch should pass them through unchanged since+ // refs/heads/origin/main doesn't exist)+ assert!(repository.same_commit("origin/main", "main").unwrap());+ assert!(repository.is_ancestor("origin/main", "main").unwrap());+}diff --git a/tests/snapshots/integration__integration_tests__list__list_shows_warning_on_git_error.snap b/tests/snapshots/integration__integration_tests__list__list_shows_warning_on_git_error.snapindex 938380f5d..3130021d9 100644--- a/tests/snapshots/integration__integration_tests__list__list_shows_warning_on_git_error.snap+++ b/tests/snapshots/integration__integration_tests__list__list_shows_warning_on_git_error.snap@@ -44,6 +44,6 @@ exit_code: 0[107m [0m [1mfeature[22m: commit-details (fatal: bad object 0000000000000000000000000000000000000000)[107m [0m [1mfeature[22m: ahead-behind (git merge-base failed for main 0000000000000000000000000000000000000000: fatal: Not a valid commit name 0000000000000000000000000000000000000000)[107m [0m [1mfeature[22m: committed-trees-match (fatal: ambiguous argument '0000000000000000000000000000000000000000^{tree}': unknown revision or path not in the working tree.)-[107m [0m [1mfeature[22m: has-file-changes (git merge-base failed for main feature: fatal: Not a valid commit name feature)+[107m [0m [1mfeature[22m: has-file-changes (git merge-base failed for refs/heads/main refs/heads/feature: fatal: Not a valid commit name refs/heads/feature)[107m [0m [1mfeature[22m: working-tree-diff (fatal: bad object HEAD)[39m[2m↳[22m [2mTo create a diagnostic file, run with [90m-vv[39m[22m