Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(integration): make squash-merge detection immune to diff.* git config (#2821)
Maximilian Roos31fa792098c5
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rsindex c48937d57..1b7b69a3b 100644--- a/src/git/repository/integration.rs+++ b/src/git/repository/integration.rs@@ -43,12 +43,13 @@ pub struct MergeProbeResult {/// the target side before giving up.////// [`Repository::is_squash_merged_via_patch_id`] runs-/// `git log -p {merge-base}..{target} | git patch-id` — one patch per commit-/// in the range. That range is unbounded: on a fast-moving repo an old branch-/// can sit tens of thousands of commits behind the tip, and a single such-/// check then dominates `wt list`, `wt remove`, and `wt step prune` (the-/// latter goes visibly silent waiting for it). A cheap graph-only-/// `git rev-list --count` pre-flight enforces this cap.+/// `git rev-list {merge-base}..{target} | git diff-tree --stdin -p | git+/// patch-id` — one patch per commit in the range. That range is unbounded:+/// on a fast-moving repo an old branch can sit tens of thousands of commits+/// behind the tip, and a single such check then dominates `wt list`,+/// `wt remove`, and `wt step prune` (the latter goes visibly silent waiting+/// for it). A cheap graph-only `git rev-list --count` pre-flight enforces+/// this cap.////// `500` is conservative because count is only a rough proxy for cost — the/// per-commit work scales with `changed_files × changed_lines`, so a few@@ -417,9 +418,13 @@ impl Repository {/// the target has a commit containing the exact same file changes as the whole branch/// — i.e., a squash merge.///+ /// Both sides of the comparison generate their diffs with `git diff-tree`+ /// (plumbing), so the patch-ids are immune to the user's `diff.*` git+ /// config — see [`Self::patch_ids_from`].+ ////// Only runs when `merge-tree` conflicts (both sides modified the same files),/// since `MergeAddsNothing` handles the non-conflict case. Cost scales with the- /// number of commits on target since the merge-base (`git log -p`), so it is+ /// number of commits on target since the merge-base (`git diff-tree`), so it is/// capped at [`PATCH_ID_SCAN_MAX_COMMITS`].////// Returns `Ok(true)` if a matching squash-merge commit is found on the target,@@ -430,13 +435,13 @@ impl Repository {return Ok(false);};- // Bound the target-side history walk. `git log -p {merge_base}..{target}`- // diffs every commit landed on the default branch since this branch- // diverged; on a fast-moving repo with an old branch that is tens of- // thousands of commits, turning one integration check into seconds (or- // tens of seconds) of work — visible as `wt step prune` / `wt list`- // going silent. A `git rev-list --count` pre-flight (graph walk only,- // no diffs) is cheap; bail above the cap. See the limitation note on+ // Bound the target-side history walk. The patch-id scan diffs every+ // commit landed on the default branch since this branch diverged; on+ // a fast-moving repo with an old branch that is tens of thousands of+ // commits, turning one integration check into seconds (or tens of+ // seconds) of work — visible as `wt step prune` / `wt list` going+ // silent. A `git rev-list --count` pre-flight (graph walk only, no+ // diffs) is cheap; bail above the cap. See the limitation note on// [`PATCH_ID_SCAN_MAX_COMMITS`].let target_commit_count: usize = self.run_command(&["rev-list", "--count", &format!("{merge_base}..{target}")])?@@ -451,14 +456,24 @@ impl Repository {}// Compute the squashed patch-id (combined diff of all branch changes).- let branch_pids = self.patch_ids_from(&["diff-tree", "-p", &merge_base, branch])?;+ let branch_pids = self.patch_ids_from(&["diff-tree", "-p", &merge_base, branch], None)?;let Some(branch_pid) = branch_pids.split_whitespace().next() else {return Ok(false);};- // Get all target commits' patch-ids in one pass.- let target_pids =- self.patch_ids_from(&["log", "-p", "--reverse", &format!("{merge_base}..{target}")])?;+ // Get all target commits' patch-ids in one pass. The diffs are+ // generated by `git diff-tree` — plumbing, like the branch side —+ // never `git log -p` (porcelain). Both sides must use the same+ // generator: `git patch-id --verbatim` hashes context lines, and+ // `log -p` honors `diff.context` / `diff.algorithm` from the user's+ // git config while `diff-tree` ignores them, so a mismatched pair+ // never agrees on a byte-identical change. `diff-tree --stdin` reads+ // the commit list on stdin and emits one diff per commit.+ let target_commits = self.run_command(&["rev-list", &format!("{merge_base}..{target}")])?;+ let target_pids = self.patch_ids_from(+ &["diff-tree", "--stdin", "-p"],+ Some(target_commits.into_bytes()),+ )?;Ok(target_pids.lines()@@ -466,22 +481,27 @@ impl Repository {}/// Pipe the output of `git <args>` directly into `git patch-id --verbatim`- /// and return the patch-id output.+ /// and return the patch-id output. `stdin`, when set, feeds `git <args>`'s+ /// standard input — used to pass a `git rev-list` commit list into+ /// `git diff-tree --stdin`.////// The intermediate diff never passes through this process — it flows from/// one git child to the other via an OS pipe. Keeps raw diffs out of our/// `-vv` debug stream (where `log_output` would otherwise dump every line- /// of `git diff-tree -p` / `git log -p`).+ /// of `git diff-tree -p`).////// Uses `--verbatim` (not `--stable`) to avoid false positives from/// whitespace normalization — `--stable` strips whitespace, so/// tabs-vs-spaces would produce matching patch-ids even though the content/// differs.- fn patch_ids_from(&self, args: &[&str]) -> anyhow::Result<String> {- let source = Cmd::new("git")+ fn patch_ids_from(&self, args: &[&str], stdin: Option<Vec<u8>>) -> anyhow::Result<String> {+ let mut source = Cmd::new("git").args(args.iter().copied()).current_dir(&self.discovery_path).context(self.logging_context());+ if let Some(data) = stdin {+ source = source.stdin_bytes(data);+ }let sink = Cmd::new("git").args(["patch-id", "--verbatim"]).current_dir(&self.discovery_path)@@ -851,7 +871,7 @@ mod hex_sha_tests {}#[cfg(test)]-mod patch_id_cap_tests {+mod patch_id_tests {use super::*;use crate::testing::TestRepo;use std::fmt::Write as _;@@ -951,4 +971,64 @@ mod patch_id_cap_tests {"should bail (return false) when base..target exceeds {PATCH_ID_SCAN_MAX_COMMITS}");}++ /// Squash-merge detection must not depend on the user's `diff.*` git+ /// config. `git patch-id --verbatim` hashes context lines, so the two+ /// sides of the comparison must generate their diffs identically. Both+ /// now use `git diff-tree` (plumbing — ignores `diff.context`,+ /// `diff.algorithm`, …); the target side once used `git log -p`+ /// (porcelain — honors them), so a repo with a non-default `diff.context`+ /// made `log -p` emit a different patch-id for a byte-identical change,+ /// and a genuinely squash-merged branch was reported as not integrated.+ ///+ /// This fixture sets non-default `diff.*` config in the repo's *local*+ /// config (hermetic — bites regardless of the machine's global git+ /// config) and builds a squash merge followed by a commit re-touching+ /// the same line, so `git merge-tree` conflicts and the patch-id+ /// fallback actually runs.+ #[test]+ fn detects_squash_merge_under_nondefault_diff_config() {+ let test = TestRepo::new();+ let repo = &test.repo;++ // `diff.context` is the active discriminator below; `diff.algorithm`+ // is set too, to prove immunity to that latent second trigger.+ test.run_git(&["config", "diff.context", "25"]);+ test.run_git(&["config", "diff.algorithm", "histogram"]);++ // A 60-line file: a one-line change in the middle yields a hunk+ // whose context window differs between `diff.context = 3` and `= 25`,+ // so the two diff generators produce different `--verbatim`+ // patch-ids unless both ignore the config.+ let path = test.path().join("file");+ let base: String = (1..=60).map(|i| format!("l{i}\n")).collect();+ std::fs::write(&path, &base).unwrap();+ test.run_git(&["add", "file"]);+ test.run_git(&["commit", "-m", "base"]);++ let changed = base.replace("l30\n", "FEATURE\n");++ // feature branch: the change that should be detected as integrated.+ test.run_git(&["checkout", "-b", "feature"]);+ std::fs::write(&path, &changed).unwrap();+ test.run_git(&["commit", "-am", "feature change"]);++ // target (main): a squash-merge of feature, then a follow-up commit+ // re-touching the same line. The follow-up makes `merge-tree`+ // conflict — the only path that reaches the patch-id fallback.+ test.run_git(&["checkout", "main"]);+ std::fs::write(&path, &changed).unwrap();+ test.run_git(&["commit", "-am", "squash-merge feature"]);+ std::fs::write(&path, changed.replace("FEATURE\n", "PADDED\n")).unwrap();+ test.run_git(&["commit", "-am", "follow-up on same line"]);++ let snapshot = repo.capture_refs().unwrap();+ let signals = compute_integration_lazy(repo, &snapshot, "feature", "main").unwrap();++ assert_eq!(+ check_integration(&signals),+ Some(IntegrationReason::PatchIdMatch),+ "squash merge must be detected via patch-id regardless of diff.* config"+ );+ }}diff --git a/src/shell_exec.rs b/src/shell_exec.rsindex 2e0606883..ef1eda63f 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -1064,22 +1064,19 @@ impl Cmd {/// inspect either child's exit status and stderr. `source_output.stdout`/// is empty (it was routed to the sink via OS pipe).///- /// Timeouts, `stdin_bytes`, and `external()` logging are not supported on- /// either side. The pipeline consumes one semaphore permit even though it- /// runs two processes concurrently — acquiring two would deadlock under- /// `concurrency = 1`.+ /// `stdin_bytes` on the source feeds the pipeline's input (the sink's+ /// stdin always comes from the source). Timeouts and `external()` logging+ /// are not supported on either side. The pipeline consumes one semaphore+ /// permit even though it runs two processes concurrently — acquiring two+ /// would deadlock under `concurrency = 1`.pub fn pipe_into(- self,+ mut self,next: Cmd,) -> std::io::Result<(std::process::Output, std::process::Output)> {assert!(!self.shell_wrap && !next.shell_wrap,"Cmd::shell() commands cannot be used with pipe_into");- assert!(- self.stdin_data.is_none(),- "pipe_into source cannot also use stdin_bytes"- );assert!(next.stdin_data.is_none(),"pipe_into sink cannot use stdin_bytes (stdin comes from source)"@@ -1112,10 +1109,16 @@ impl Cmd {let first_log = WtTraceLog::new(self.context.as_deref(), &first_cmd_str);let second_log = WtTraceLog::new(next.context.as_deref(), &second_cmd_str);+ let source_stdin = self.stdin_data.take();+let mut first = self.direct_command();self.apply_common_settings(&mut first);first- .stdin(Stdio::null())+ .stdin(if source_stdin.is_some() {+ Stdio::piped()+ } else {+ Stdio::null()+ }).stdout(Stdio::piped()).stderr(Stdio::piped());@@ -1124,6 +1127,17 @@ impl Cmd {.stdout.take().expect("stdout was configured as piped");+ // Pair the source's stdin pipe with the data to write; a writer+ // thread (below) drains it concurrently with the rest of the pipeline.+ let first_stdin = source_stdin.map(|data| {+ (+ first_child+ .stdin+ .take()+ .expect("stdin was configured as piped"),+ data,+ )+ });let mut second = next.direct_command();next.apply_common_settings(&mut second);@@ -1159,6 +1173,19 @@ impl Cmd {first_stderr_pipe.read_to_end(&mut buf).map(|_| buf)});+ // Feed the source's stdin (e.g. a `git rev-list` commit list+ // piped into `git diff-tree --stdin`) on a thread, concurrent+ // with the drain below — writing it all up front would deadlock+ // once the source's stdout pipe fills. A short write (the source+ // exited early) surfaces as its non-zero exit status, which+ // callers already inspect.+ if let Some((mut stdin, data)) = first_stdin {+ s.spawn(move || {+ let _ = stdin.write_all(&data);+ // `stdin` drops here, closing the pipe so the source sees EOF.+ });+ }+// Drain `next` first (its `wait_with_output` reads its own// stdout/stderr), so `first`'s writes can complete.let second_result = second_child.wait_with_output();