Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: distinguish merge-tree conflicts from real errors (#1896)
Maximilian Roosd74b04ea72de
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rsindex 2576dd950..62245afa9 100644--- a/src/git/repository/integration.rs+++ b/src/git/repository/integration.rs@@ -135,11 +135,23 @@ impl Repository {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])?;- Ok(!clean_merge)++ // Unrelated histories (no common ancestor) can't be merged — that's a conflict.+ if self.merge_base(&base, &head)?.is_none() {+ return Ok(true);+ }++ // Exit codes: 0 = clean merge, 1 = conflicts, 128+ = error (invalid ref, corrupt repo)+ let output = self.run_command_output(&["merge-tree", "--write-tree", &base, &head])?;++ if output.status.code() == Some(1) {+ return Ok(true);+ }+ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ anyhow::bail!("git merge-tree failed for {base} {head}: {}", stderr.trim());+ }+ Ok(false)}/// Check if merging a branch into target would add anything (not already integrated).@@ -155,20 +167,24 @@ impl Repository {branch: &str,target: &str,) -> anyhow::Result<Option<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]);+ // Exit codes: 0 = clean merge, 1 = conflicts, 128+ = error (invalid ref, corrupt repo)+ let output = self.run_command_output(&["merge-tree", "--write-tree", target, branch])?;- let Ok(merge_tree) = merge_result else {- // merge-tree failed (likely conflicts) — caller should try patch-id fallback+ if output.status.code() == Some(1) {+ // Conflicts — caller should try patch-id fallbackreturn Ok(None);- };-- let merge_tree = merge_tree.trim();- if merge_tree.is_empty() {- // Empty output is unexpected - treat as having changes- return Ok(Some(true));}+ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ anyhow::bail!(+ "git merge-tree failed for {target} {branch}: {}",+ stderr.trim()+ );+ }++ // Clean merge — first line of stdout is the resulting tree SHA+ let merge_tree = String::from_utf8_lossy(&output.stdout);+ let merge_tree = merge_tree.lines().next().unwrap_or("").trim();// Get target's tree for comparisonlet target_tree = self.rev_parse_tree(&format!("{target}^{{tree}}"))?;@@ -242,6 +258,17 @@ impl Repository {) -> anyhow::Result<MergeProbeResult> {let branch = self.resolve_preferring_branch(branch);let target = self.resolve_preferring_branch(target);++ // Orphan branches (no common ancestor) can't be merge-tree simulated+ // (git exits 128 with "refusing to merge unrelated histories") and have+ // no merge-base for patch-id either. Short-circuit: they always have changes.+ if self.merge_base(&target, &branch)?.is_none() {+ return Ok(MergeProbeResult {+ would_merge_add: true,+ is_patch_id_match: false,+ });+ }+let merge_result = self.would_merge_add_to_target(&branch, &target)?;match merge_result {Some(would_add) => Ok(MergeProbeResult {diff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rsindex d1adb43e6..6d0b63544 100644--- a/tests/integration_tests/repository.rs+++ b/tests/integration_tests/repository.rs@@ -544,6 +544,115 @@ fn test_integration_functions_handle_remote_refs() {assert!(repository.is_ancestor("origin/main", "main").unwrap());}+// =============================================================================+// merge-tree exit code handling tests+// =============================================================================++/// has_merge_conflicts returns false for clean merges (exit 0)+/// and true for conflicts (exit 1).+#[test]+fn test_has_merge_conflicts_clean_vs_conflicting() {+ let repo = TestRepo::new();+ fs::write(repo.root_path().join("base.txt"), "base\n").unwrap();+ repo.run_git(&["add", "base.txt"]);+ repo.run_git(&["commit", "-m", "Base"]);++ // Clean merge: feature adds a new file (no overlap with main)+ repo.run_git(&["checkout", "-b", "clean-feature"]);+ fs::write(repo.root_path().join("new.txt"), "new\n").unwrap();+ repo.run_git(&["add", "new.txt"]);+ repo.run_git(&["commit", "-m", "Add new file"]);+ repo.run_git(&["checkout", "main"]);++ // Conflicting merge: feature edits the same file differently+ repo.run_git(&["checkout", "-b", "conflict-feature"]);+ fs::write(repo.root_path().join("base.txt"), "conflict\n").unwrap();+ repo.run_git(&["add", "base.txt"]);+ repo.run_git(&["commit", "-m", "Edit base"]);+ repo.run_git(&["checkout", "main"]);+ fs::write(repo.root_path().join("base.txt"), "main-edit\n").unwrap();+ repo.run_git(&["add", "base.txt"]);+ repo.run_git(&["commit", "-m", "Edit base on main"]);++ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();+ assert!(+ !repository+ .has_merge_conflicts("main", "clean-feature")+ .unwrap()+ );+ assert!(+ repository+ .has_merge_conflicts("main", "conflict-feature")+ .unwrap()+ );+}++/// has_merge_conflicts returns true (not Err) for orphan branches,+/// since unrelated histories can't be cleanly merged.+#[test]+fn test_has_merge_conflicts_orphan_branch() {+ let repo = TestRepo::new();++ repo.run_git(&["checkout", "--orphan", "orphan"]);+ repo.run_git(&["rm", "-rf", "."]);+ fs::write(repo.root_path().join("orphan.txt"), "orphan\n").unwrap();+ repo.run_git(&["add", "orphan.txt"]);+ repo.run_git(&["commit", "-m", "Orphan commit"]);+ repo.run_git(&["checkout", "main"]);++ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();++ // Orphan branches have no merge base — treated as conflicting, not as an error+ assert!(repository.has_merge_conflicts("main", "orphan").unwrap());+}++/// merge_integration_probe short-circuits for orphan branches:+/// would_merge_add=true, is_patch_id_match=false.+#[test]+fn test_merge_integration_probe_orphan_branch() {+ let repo = TestRepo::new();++ repo.run_git(&["checkout", "--orphan", "orphan"]);+ repo.run_git(&["rm", "-rf", "."]);+ fs::write(repo.root_path().join("orphan.txt"), "orphan\n").unwrap();+ repo.run_git(&["add", "orphan.txt"]);+ repo.run_git(&["commit", "-m", "Orphan commit"]);+ repo.run_git(&["checkout", "main"]);++ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();+ let probe = repository+ .merge_integration_probe("orphan", "main")+ .unwrap();++ assert!(probe.would_merge_add, "orphan branch always has changes");+ assert!(+ !probe.is_patch_id_match,+ "no patch-id match possible without merge base"+ );+}++/// merge_integration_probe correctly detects already-integrated branches+/// (clean merge that doesn't change target tree).+#[test]+fn test_merge_integration_probe_already_integrated() {+ let repo = TestRepo::new();++ // Create feature, then merge it into main via fast-forward+ repo.run_git(&["checkout", "-b", "feature"]);+ fs::write(repo.root_path().join("feature.txt"), "content\n").unwrap();+ repo.run_git(&["add", "feature.txt"]);+ repo.run_git(&["commit", "-m", "Feature"]);+ repo.run_git(&["checkout", "main"]);+ repo.run_git(&["merge", "feature"]);++ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();+ let probe = repository+ .merge_integration_probe("feature", "main")+ .unwrap();++ assert!(!probe.would_merge_add, "already-merged branch adds nothing");+}+// =============================================================================// Bug: repo_path() inside git submodules// =============================================================================