Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(git): build every plumbing diff through PlumbingDiff (#4147)
Maximilian Roosfc56d06912be
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8ce28d7d5..7a8dd2588 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -109,7 +109,7 @@ When no structured alternative exists, document the fragility inline.### Plumbing for Output `wt` Consumes-Porcelain commands read display configuration that changes what they report: `diff.relative` once made `wt remove` delete an unmerged branch, and `color.ui=always` and `diff.external` leaked into LLM prompts. When `wt` parses, caches, renders, or prompts with git's output, it runs plumbing (`diff-tree`, `diff-index`, `diff-files`, `for-each-ref`), which ignores that configuration. Diffs go through `PreparedDiff::capture`, which restores the `git diff` defaults plumbing lacks. `git status` has no plumbing equivalent, so it pins its behavior with explicit flags. Output shown as git's own view, like `wt step diff`, stays porcelain.+Porcelain commands read display configuration that changes what they report: `diff.relative` once made `wt remove` delete an unmerged branch, and `color.ui=always` and `diff.external` leaked into LLM prompts. When `wt` parses, caches, renders, or prompts with git's output, it runs plumbing (`diff-tree`, `diff-index`, `diff-files`, `for-each-ref`), which ignores that configuration apart from `submodule.<name>.ignore`. `PlumbingDiff::args` builds every plumbing diff with `--ignore-submodules=none` to override that setting, and a test rejects one spelled by hand. Rendered and prompted diffs go through `PreparedDiff::capture`, which also restores the `git diff` defaults plumbing lacks. `git status` has no plumbing equivalent, so it pins its behavior with explicit flags. Output shown as git's own view, like `wt step diff`, stays porcelain.### Immutable Ids Over List Positionsdiff --git a/src/commands/picker/log_formatter.rs b/src/commands/picker/log_formatter.rsindex 5f1547455..1f9a1da2a 100644--- a/src/commands/picker/log_formatter.rs+++ b/src/commands/picker/log_formatter.rs@@ -7,7 +7,7 @@ use std::fmt::Write;use ansi_str::AnsiStr;use unicode_width::UnicodeWidthStr;-use worktrunk::git::{Repository, parse_numstat_line};+use worktrunk::git::{PlumbingDiff, Repository, parse_numstat_line};use worktrunk::shell_exec::Cmd;use worktrunk::styling::{ADDITION, DELETION};@@ -46,14 +46,7 @@ pub(super) fn batch_fetch_stats(return HashMap::new();};let Ok(output) = Cmd::new("git")- .args([- "diff-tree",- "--numstat",- "-r",- "--root",- "--ignore-submodules=none",- "--stdin",- ])+ .args(PlumbingDiff::Tree.args(&["--numstat", "-r", "--root", "--stdin"])).current_dir(repo_path).stdin_bytes(stdin_data).run()diff --git a/src/git/diff.rs b/src/git/diff.rsindex cb3601615..514f71d25 100644--- a/src/git/diff.rs+++ b/src/git/diff.rs@@ -141,6 +141,36 @@ impl DiffStats {}}+/// A git plumbing diff command.+///+/// Plumbing diffs ignore the user's diff display configuration but still+/// honor `submodule.<name>.ignore`, from repository config or `.gitmodules`,+/// which hides gitlink changes. Every plumbing diff `wt` runs is built by+/// [`Self::args`], which overrides that setting.+#[derive(Debug, Clone, Copy)]+pub enum PlumbingDiff {+ /// `git diff-tree`: tree against tree.+ Tree,+ /// `git diff-index`: tree against the index or working tree.+ Index,+ /// `git diff-files`: index against working tree.+ Files,+}++impl PlumbingDiff {+ /// Arguments for `git <command> --ignore-submodules=none <args>`.+ pub fn args<'a>(self, args: &[&'a str]) -> Vec<&'a str> {+ let command = match self {+ Self::Tree => "diff-tree",+ Self::Index => "diff-index",+ Self::Files => "diff-files",+ };+ let mut all = vec![command, "--ignore-submodules=none"];+ all.extend_from_slice(args);+ all+ }+}+#[cfg(test)]mod tests {use insta::assert_snapshot;diff --git a/src/git/mod.rs b/src/git/mod.rsindex cc2ecc677..497b0dcd8 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -61,7 +61,7 @@ pub(crate) fn is_bare_repo_dir(dir: &Path) -> bool {// Re-exports from submodulespub use ci_platform::ForgeKind;pub(crate) use diff::DiffStats;-pub use diff::{LineDiff, parse_numstat_line};+pub use diff::{LineDiff, PlumbingDiff, parse_numstat_line};pub use error::{// Typed leaf error for buffered command-runner failures (downcast target)CommandError,diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rsindex 22f423794..5da204010 100644--- a/src/git/repository/diff.rs+++ b/src/git/repository/diff.rs@@ -6,7 +6,7 @@ use std::path::PathBuf;use anyhow::{Context, bail};use dashmap::mapref::entry::Entry;-use crate::git::CommandError;+use crate::git::{CommandError, PlumbingDiff};use crate::shell_exec::Cmd;use super::working_tree::{TempIndex, WorkingTree, path_to_logging_context};@@ -94,21 +94,16 @@ impl<'a> PreparedDiff<'a> {&self,options: impl IntoIterator<Item = impl Into<String>>,) -> anyhow::Result<String> {+ let command = match &self.sides {+ DiffSides::WorkingTree(_) => PlumbingDiff::Index.args(&[]),+ DiffSides::Staged(_) => {+ PlumbingDiff::Index.args(&["--cached", "--ita-invisible-in-index"])+ }+ DiffSides::Commits(..) => PlumbingDiff::Tree.args(&["-r"]),+ };let mut args = vec!["--no-optional-locks".to_string()];- match &self.sides {- DiffSides::WorkingTree(_) => args.push("diff-index".into()),- DiffSides::Staged(_) => args.extend([- "diff-index".into(),- "--cached".into(),- "--ita-invisible-in-index".into(),- ]),- DiffSides::Commits(..) => args.extend(["diff-tree".into(), "-r".into()]),- }- args.extend([- "--find-renames".into(),- "--textconv".into(),- "--ignore-submodules=none".into(),- ]);+ args.extend(command.into_iter().map(String::from));+ args.extend(["--find-renames".into(), "--textconv".into()]);args.extend(options.into_iter().map(Into::into));args.push("--end-of-options".into());args.extend(self.revisions());@@ -326,17 +321,15 @@ impl Repository {/// a file is renamed in one branch but has uncommitted changes under the/// old name).pub fn changed_files(&self, base: &str, head: &str) -> anyhow::Result<Vec<String>> {- let stdout = self.run_command(&[- "diff-tree",+ let stdout = self.run_command(&PlumbingDiff::Tree.args(&["-r","--name-only","-z",- "--ignore-submodules=none","--end-of-options",base,head,"--",- ])?;+ ]))?;Ok(stdout.split('\0').filter(|path| !path.is_empty())@@ -658,16 +651,14 @@ impl Repository {.iter().map(|path| format!(":(top){path}")).collect();- let mut args = vec![- "diff-tree",+ let mut args = PlumbingDiff::Tree.args(&["-r","--shortstat","--find-renames",- "--ignore-submodules=none",&merge_base,head_sha,"--",- ];+ ]);args.extend(sparse_pathspecs.iter().map(String::as_str));let stdout = self.run_command(&args)?;diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rsindex aa3cc1882..0a16e4968 100644--- a/src/git/repository/integration.rs+++ b/src/git/repository/integration.rs@@ -7,7 +7,7 @@ use anyhow::{Context, bail};use serde::{Deserialize, Serialize};use super::{RefSnapshot, Repository};-use crate::git::{IntegrationReason, check_integration, compute_integration_lazy};+use crate::git::{IntegrationReason, PlumbingDiff, check_integration, compute_integration_lazy};use crate::shell_exec::Cmd;/// Integration targets for `wt list`'s status column.@@ -193,17 +193,7 @@ impl Repository {return Ok(true);};- // `--ignore-submodules=none` because `submodule.<name>.ignore`, from- // user config or `.gitmodules`, hides gitlink changes even from- // plumbing, and a branch that only moves a submodule has added changes.- let args = [- "diff-tree",- "--quiet",- "--ignore-submodules=none",- &merge_base,- branch_sha,- "--",- ];+ let args = PlumbingDiff::Tree.args(&["--quiet", &merge_base, branch_sha, "--"]);let output = self.run_command_output(&args)?;let result = match output.status.code() {Some(0) => false,@@ -397,10 +387,7 @@ impl Repository {////// 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`]. Both also pass- /// `--ignore-submodules=none`: plumbing still honors- /// `submodule.<name>.ignore`, and a submodule bump dropped from both sides- /// would let a branch match a target commit that never carried the bump.+ /// 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@@ -440,14 +427,7 @@ impl Repository {// Compute the squashed patch-id (combined diff of all branch changes).let branch_pids = self.patch_ids_from(- &[- "diff-tree",- "--patch",- "--ignore-submodules=none",- &merge_base,- branch,- "--",- ],+ &PlumbingDiff::Tree.args(&["--patch", &merge_base, branch, "--"]),None,)?;let Some(branch_pid) = branch_pids.split_whitespace().next() else {@@ -464,12 +444,7 @@ impl Repository {// 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",- "--patch",- "--ignore-submodules=none",- ],+ &PlumbingDiff::Tree.args(&["--stdin", "--patch"]),Some(target_commits.into_bytes()),)?;@@ -1330,7 +1305,7 @@ mod has_added_changes_error_tests {assert!(cmd_err.command_string()- .starts_with("git diff-tree --quiet"),+ .starts_with("git diff-tree --ignore-submodules=none --quiet"),"{err:#}");}diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex 138ccb0ad..1c2f2cdaa 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -13,7 +13,7 @@ use crate::shell_exec::Cmd;use dunce::canonicalize;use super::{GitError, LineDiff, Repository};-use crate::git::CommandError;+use crate::git::{CommandError, PlumbingDiff};const TEMP_INDEX_PREFIX: &str = "worktrunk-temp-index-";@@ -690,13 +690,7 @@ impl<'a> WorkingTree<'a> {/// all.pub fn unmerged_paths(&self) -> anyhow::Result<Vec<String>> {let output = self- .run_command(&[- "diff-files",- "--name-only",- "--diff-filter=U",- "-z",- "--ignore-submodules=none",- ])+ .run_command(&PlumbingDiff::Files.args(&["--name-only", "--diff-filter=U", "-z"])).context("Failed to list unmerged paths")?;Ok(output.split('\0')@@ -891,14 +885,12 @@ impl<'a> WorkingTree<'a> {/// Get line diff statistics for working tree changes (unstaged + staged).pub fn working_tree_diff_stats(&self) -> anyhow::Result<LineDiff> {- let stdout = self.run_command(&[- "diff-index",+ let stdout = self.run_command(&PlumbingDiff::Index.args(&["--shortstat","--find-renames",- "--ignore-submodules=none","HEAD","--",- ])?;+ ]))?;Ok(LineDiff::from_shortstat(&stdout))}@@ -922,16 +914,14 @@ impl<'a> WorkingTree<'a> {return self.working_tree_diff_stats();}- let numstat_args = [- "diff-index",+ let numstat_args = PlumbingDiff::Index.args(&["--numstat","-z","--find-renames",- "--ignore-submodules=none","--end-of-options","HEAD","--",- ];+ ]);let tracked_output = self.run_command_output(&numstat_args)?;if !tracked_output.status.success() {return Err(@@ -1799,7 +1789,7 @@ mod tests {assert!(cmd_err.command_string()- .starts_with("git diff-index --numstat -z --find-renames --ignore-submodules=none --end-of-options HEAD")+ .starts_with("git diff-index --ignore-submodules=none --numstat -z --find-renames --end-of-options HEAD"));}diff --git a/tests/CLAUDE.md b/tests/CLAUDE.mdindex 2f86e5f1c..6dbd68428 100644--- a/tests/CLAUDE.md+++ b/tests/CLAUDE.md@@ -565,8 +565,9 @@ custom verifier must fail for every violation it claims to check—diagnosticSeveral guards read `src/`, or the snapshot corpus, as text rather thancompiling it: no stray `println!` outside the allowlist, no `eprintln!` thatresolves to std's macro instead of anstream's, no bare `env!("VERGEN_…")`, no-`include_str!` of a path the package won't ship, no host path in a `.snap`, and-nothing but `src/testing/mod.rs` spawning `wt` through `CARGO_BIN_EXE_wt`.+`include_str!` of a path the package won't ship, no host path in a `.snap`, no+plumbing diff built outside `PlumbingDiff::args`, and nothing but+`src/testing/mod.rs` spawning `wt` through `CARGO_BIN_EXE_wt`.Each one asserts *absence* over what its walk handed it.That polarity is what makes the failure mode silent. A file that drops out ofdiff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rsindex ac472d1dc..8afa11368 100644--- a/tests/integration_tests/list.rs+++ b/tests/integration_tests/list.rs@@ -2432,6 +2432,7 @@ fn mock_summary_cache(summary: &str,) {use sha2::{Digest, Sha256};+ use worktrunk::git::PlumbingDiff;// Compute combined diff (matching compute_combined_diff in summary.rs)let mut diff = String::new();@@ -2449,7 +2450,7 @@ fn mock_summary_cache(let patch_args = ["--find-renames", "--textconv", "--patch"];if let Ok(output) = repo.git_command()- .args(["diff-tree", "-r"])+ .args(PlumbingDiff::Tree.args(&["-r"])).args(patch_args).args([merge_base.as_str(), head.as_str()]).run()@@ -2463,7 +2464,8 @@ fn mock_summary_cache(let wt_str = wt_path.display().to_string();if let Ok(output) = repo.git_command()- .args(["-C", &wt_str, "diff-index"])+ .args(["-C", &wt_str])+ .args(PlumbingDiff::Index.args(&[])).args(patch_args).arg("HEAD").run()diff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rsindex 4c65abaac..5b526ed87 100644--- a/tests/integration_tests/repository.rs+++ b/tests/integration_tests/repository.rs@@ -3,8 +3,10 @@use std::fs;use std::path::Path;-use worktrunk::git::{InProgressOperation, RefType, Repository};+use path_slash::PathExt as _;+use worktrunk::git::{InProgressOperation, PlumbingDiff, RefType, Repository};+use crate::common::source_scan::visit_files;use crate::common::{BareRepoTest, TestRepo};// =============================================================================@@ -1253,6 +1255,41 @@ fn test_submodule_bump_survives_submodule_ignore() {);}+/// `PlumbingDiff::args` is the one place that spells a plumbing diff command,+/// so no diff under `src/` or `tests/` can skip its submodule override. The+/// needles come from `PlumbingDiff` too, so this guard spells none of them.+#[test]+fn test_plumbing_diffs_are_built_by_plumbing_diff() {+ let root = Path::new(env!("CARGO_MANIFEST_DIR"));+ let builder = root.join("src").join("git").join("diff.rs");+ let needles = [PlumbingDiff::Tree, PlumbingDiff::Index, PlumbingDiff::Files]+ .map(|diff| format!("\"{}\"", diff.args(&[])[0]));+ let mut offenders = Vec::new();+ for dir in ["src", "tests"] {+ let scanned = visit_files(+ &root.join(dir),+ "rs",+ "plumbing-diff scan",+ &mut |path, contents| {+ for needle in &needles {+ if path != builder && contents.contains(needle.as_str()) {+ let relative = path.strip_prefix(root).unwrap().to_slash_lossy();+ offenders.push(format!("{relative} spells {needle}"));+ }+ }+ },+ );+ assert!(+ scanned > 0,+ "the plumbing-diff scan read no files under {dir}"+ );+ }+ assert!(+ offenders.is_empty(),+ "build these with PlumbingDiff::args: {offenders:#?}"+ );+}+#[test]fn test_branch_diff_stats_scoped_to_sparse_checkout() {let repo = TestRepo::new();