Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(git): run diffs through plumbing so user git config can't change what wt reads (#4146)
Maximilian Roose13643d6981c
diff --git a/CLAUDE.md b/CLAUDE.mdindex d7a3de552..8ce28d7d5 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -100,13 +100,17 @@ Prefer exit codes / `--porcelain` / `--json` over parsing human-readable message| Tool | Fragile | Structured ||------|---------|------------|-| `git diff` | `--stat` (localized) | `--numstat`, `--shortstat` (`(+)`/`(-)` hardcoded) |-| `git status` | default | `--porcelain=v2` |+| `git diff-tree` / `diff-index` | `--stat` (localized) | `--numstat`, `--shortstat` (`(+)`/`(-)` hardcoded) |+| `git status` | default | `--porcelain=v2 -z` || `git merge-base` | error messages | exit codes || `gh` / `glab` | default | `--json` |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.+### Immutable Ids Over List Positions`stash@{0}` names a position in a list any process can reorder, so a handle captured before a mutation window and used after it can resolve to a different object — restoring the target worktree's autostash by position after `git push` silently restored a concurrent writer's entry and reported success. Capture the immutable id instead (`git stash list --format=%H`, `git stash create`, `rev-parse`) and act on that; where an operation accepts only a positional selector, re-derive it from something stable immediately beforehand. An index into a collection `wt` owns is a different thing — this is about namespaces other processes can mutate. The strongest form is not to enter the shared namespace at all: the autostash this rule came from was later deleted outright, replaced by a two-tree merge that leaves the target worktree's changes in place (`advance_target` in `src/commands/worktree/push.rs`).diff --git a/src/commands/commit.rs b/src/commands/commit.rsindex 2ffabaca2..012a91e9a 100644--- a/src/commands/commit.rs+++ b/src/commands/commit.rs@@ -148,7 +148,7 @@ impl<'a> CommitGenerator<'a> {}if show_progress {- let stats_parts = wt.diff_stats_summary(&["diff", "--staged", "--shortstat"]);+ let stats_parts = wt.prepare_staged_diff(wt.index_base()?).stats_summary();let changes_type = match stage_mode {StageMode::Tracked => "tracked changes",diff --git a/src/commands/list/collect/execution.rs b/src/commands/list/collect/execution.rsindex ed42fc4fd..e9d27a85a 100644--- a/src/commands/list/collect/execution.rs+++ b/src/commands/list/collect/execution.rs@@ -32,7 +32,7 @@ use super::types::{TaskError, TaskKind, TaskResult};/// Tasks that require a valid commit SHA. Skipped for unborn branches (no commits yet)./// Without this, these tasks would fail on the null OID and show as errors in the table.///-/// `WorkingTreeDiff` runs `git diff HEAD` and `WorkingTreeConflicts` runs+/// `WorkingTreeDiff` runs `git diff-index HEAD` and `WorkingTreeConflicts` runs/// `git merge-tree` against the worktree's HEAD SHA — both fail on a null OID/// with `fatal: ambiguous argument 'HEAD'` / `fatal: 0000… is not a valid/// object`. Their seed defaults (`None` for the diff, `Some(None)` for thediff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rsindex e7f351d50..7fde02c35 100644--- a/src/commands/list/mod.rs+++ b/src/commands/list/mod.rs@@ -58,15 +58,16 @@//! - `git status --porcelain` - Working tree state (uses index cache)//! - `git rev-list --count <base>..<head>` - Ahead/behind counts (uses commit graph)//! - Working tree line diffs:-//! - Without untracked files: `git diff --shortstat --find-renames HEAD`+//! - Without untracked files: `git diff-index --shortstat --find-renames HEAD`//! - With untracked files: `git ls-files --others`, a temporary index copy plus-//! `git add --intent-to-add`, and two `git diff --numstat -z --find-renames HEAD` calls-//! - `git diff --shortstat <base>...<head>` - Branch line diffs (uses tree objects)+//! `git add --intent-to-add`, and two `git diff-index --numstat -z --find-renames HEAD` calls+//! - `git diff-tree -r --shortstat --find-renames <merge-base> <head>` - Branch line diffs+//! (uses tree objects)//! - `git rev-parse <ref>` - Ref resolution (uses ref cache)//!-//! `HEAD±` always enables rename detection because pairing a tracked deletion with an-//! untracked destination makes a move line-neutral. `main…±` compares committed trees-//! and continues to use the user's configured rename policy.+//! Both line-diff columns use plumbing with rename detection on, so the user's diff+//! configuration can't change them. For `HEAD±`, renames also pair a tracked deletion+//! with an untracked destination, making a move line-neutral.//!//! Plus one global command://! - `git worktree list --porcelain` - List all worktrees (uses ref cache)diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 13cfacb58..4c92bdaf5 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -186,28 +186,26 @@ pub(crate) fn force_serial_concurrent() -> bool {std::env::var_os("WORKTRUNK_TEST_SERIAL_CONCURRENT").is_some()}-/// Show detailed diffstat for a given commit range.+/// Show detailed diffstat from `base` to `head`.////// Displays the diff statistics (file changes, insertions, deletions) in a gutter format./// Used after commit/squash to show what was included in the commit.-///-/// # Arguments-/// * `repo` - The repository to query-/// * `range` - The commit range to diff (e.g., "HEAD~1..HEAD" or "main..HEAD")-pub(crate) fn show_diffstat(repo: &worktrunk::git::Repository, range: &str) -> anyhow::Result<()> {- let mut args = vec!["diff", "--color=always", "--stat"];+pub(crate) fn show_diffstat(+ repo: &worktrunk::git::Repository,+ base: &str,+ head: &str,+) -> anyhow::Result<()> {+ let mut options = vec!["--color=always".to_string(), "--stat".to_string()];// With no detectable width, omit the flag and let git use its default width.- let stat_width_arg;if let Some(term_width) = worktrunk::styling::terminal_width() {let stat_width = term_width.saturating_sub(worktrunk::styling::GUTTER_OVERHEAD);- stat_width_arg = format!("--stat-width={stat_width}");- args.push(&stat_width_arg);+ options.push(format!("--stat-width={stat_width}"));}- // Fence the range positional so a target branch named like a flag- // (`-x..HEAD`) can't be misparsed as an option.- args.push("--end-of-options");- args.push(range);- let diff_stat = repo.run_command(&args)?.trim_end().to_string();+ let diff_stat = repo+ .prepare_diff(base, head)+ .capture(options)?+ .trim_end()+ .to_string();if !diff_stat.is_empty() {eprintln!("{}", format_with_gutter(&diff_stat, None));diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rsindex fcdd825a1..c75b88a34 100644--- a/src/commands/picker/items.rs+++ b/src/commands/picker/items.rs@@ -374,7 +374,7 @@ impl SkimItem for HeaderSkimItem {/// What the shared porcelain snapshot says about the worktree diff path./// Only an untracked file requires the temporary-index path; tracked-only-/// changes can use ordinary `git diff` without copying or updating an index.+/// changes can diff against the real index without copying or updating one.#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum WorktreeDiffState {Clean,@@ -727,11 +727,11 @@ pub(super) fn pr_status_pane_eq(#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pub(super) struct LocalContent {/// `working_tree`: staged, unstaged, or untracked changes exist. Matches the- /// pane's temporary-index `git diff HEAD`. `Some(false)` for a branch-only- /// row (no working tree to diff).+ /// pane's temporary-index `git diff-index HEAD`. `Some(false)` for a+ /// branch-only row (no working tree to diff).working_tree: Option<bool>,/// Tracked working-tree changes exist. The Summary pane's existing- /// combined-diff source uses ordinary `git diff HEAD`, which intentionally+ /// combined-diff source uses `git diff-index HEAD` on the real index, which intentionally/// excludes untracked files, so its availability must not reuse the/// untracked-inclusive `working_tree` signal above.summary_working_tree: Option<bool>,@@ -914,7 +914,7 @@ struct Tab {/// a `u16` (`render_text` in skim 5.7.0's `src/tui/preview.rs` clamps with/// `u16::try_from(self.scroll_y).unwrap_or(u16::MAX)`), so a body over 65,535/// lines renders a tail the user can never scroll to and is given no sign of.-/// A `git diff <default>...<branch>` on a long-lived branch clears that on its+/// A branch diff against the default branch on a long-lived branch clears that on its/// own. The cap sits under the ceiling rather than at it because the body isn't/// the whole pane: the tab bar and this notice ride above it and count toward/// the same total.@@ -1388,8 +1388,8 @@ impl PickerRow {}/// Compute a live worktree diff. Porcelain selects the cheapest path, but- /// never supplies the diff itself: tracked-only changes use ordinary- /// `git diff`, while untracked or unknown state uses a temporary index so+ /// never supplies the diff itself: tracked-only changes diff against the+ /// real index, while untracked or unknown state uses a temporary index so/// untracked files are included without touching the real index.fn compute_live_worktree_diff(repo: &Repository,@@ -1399,14 +1399,16 @@ impl PickerRow {state: WorktreeDiffState,) -> anyhow::Result<Option<String>> {let worktree = repo.worktree_at(path);- let diff = match state {- WorktreeDiffState::Clean => return Ok(None),- WorktreeDiffState::TrackedOnly => worktree.prepare_diff([base]),- WorktreeDiffState::HasUntracked | WorktreeDiffState::Unknown => {- worktree.prepare_diff_with_untracked([base])?+ match state {+ WorktreeDiffState::Clean => Ok(None),+ WorktreeDiffState::TrackedOnly => {+ worktree.prepare_diff(base).capture_stat_and_patch(width)}- };- diff.capture_stat_and_patch(width)+ WorktreeDiffState::HasUntracked | WorktreeDiffState::Unknown => worktree+ .temp_index_with_untracked()?+ .prepare_diff(base)+ .capture_stat_and_patch(width),+ }}fn unavailable_diff(branch: &str, label: &str) -> String {@@ -1439,7 +1441,7 @@ impl PickerRow {"{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no comparison base for a complete diff\n");};- let Some(base) = spec.working_base.as_deref() else {+ let Some(base) = spec.diff_base.as_deref() else {return Self::unavailable_diff(branch, "complete diff");};@@ -1528,8 +1530,11 @@ impl PickerRow {return render(&cached);}+ let Some(base) = spec.diff_base.as_deref() else {+ return Self::unavailable_diff(branch, "committed diff");+ };let body = match repo- .prepare_diff(spec.revs.iter().cloned())+ .prepare_diff(base, item.head()).capture_stat_and_patch(width){Ok(body) => body,@@ -1631,12 +1636,19 @@ impl PickerRow {// Ahead or diverged shows this branch's unique changes// (upstream…head); behind-only shows what upstream has// (head…upstream).- let range = if ahead > 0 {- format!("{upstream_sha}...{}", item.head())+ let (base, head) = if ahead > 0 {+ (upstream_sha, item.head())} else {- format!("{}...{upstream_sha}", item.head())+ (item.head(), upstream_sha)};- match repo.prepare_diff([range]).capture_stat_and_patch(width) {+ let body = repo.merge_base(base, head).and_then(|merge_base| {+ let Some(merge_base) = merge_base else {+ anyhow::bail!("{base} and {head} have no merge base");+ };+ repo.prepare_diff(merge_base, head)+ .capture_stat_and_patch(width)+ });+ match body {Ok(body) => body,Err(error) => {log::debug!("Could not compute upstream diff for {branch}: {error:#}");@@ -3065,6 +3077,44 @@ mod tests {);}+ #[test]+ fn branch_diff_with_several_merge_bases() {+ // Criss-cross merges give `main` and `feature` two merge bases.+ // `git diff-tree --merge-base` refuses that; the preview diffs from+ // one resolved merge base, as `git diff main...feature` does.+ let (t, repo) = repo_with_main();+ let commit = |file: &str| {+ std::fs::write(t.path().join(file), file).unwrap();+ repo.run_command(&["add", file]).unwrap();+ repo.run_command(&["commit", "--message", file]).unwrap();+ repo.run_command(&["rev-parse", "HEAD"])+ .unwrap()+ .trim()+ .to_string()+ };+ repo.run_command(&["branch", "feature"]).unwrap();+ let main_side = commit("main-side.txt");+ repo.run_command(&["checkout", "feature"]).unwrap();+ let feature_side = commit("feature-side.txt");+ repo.run_command(&["merge", "--no-edit", &main_side])+ .unwrap();+ commit("feature-only.txt");+ repo.run_command(&["checkout", "main"]).unwrap();+ repo.run_command(&["merge", "--no-edit", &feature_side])+ .unwrap();+ let bases = repo+ .run_command(&["merge-base", "--all", "main", "feature"])+ .unwrap();+ assert_eq!(bases.lines().count(), 2, "fixture needs two merge bases");++ let item = item_at(&repo, "feature");+ let output = PickerRow::compute_branch_diff_preview(&repo, &item, 80);+ assert!(+ output.contains("feature-only.txt"),+ "expected the branch diff, got: {output:?}"+ );+ }+#[test]fn unified_diff_is_net_change_and_subsidiary_diffs_include_untracked() {use crate::commands::list::model::WorktreeData;@@ -3246,7 +3296,7 @@ mod tests {#[test]fn diff_preview_fences_flag_like_refs() {// A ref whose name starts with `-` must reach git as a positional, not- // an option. Without the `--end-of-options` fence, `git diff <sha>+ // an option. Without the `--end-of-options` fence, `git diff-tree <sha>// -weird` misparses `-weird` as a flag and errors out; the fence lets// it resolve as a ref. `git branch` rejects leading-dash names, so the// ref is created via `update-ref`.@@ -3261,7 +3311,7 @@ mod tests {.unwrap();let out = repo- .prepare_diff([root.trim(), "-weird"])+ .prepare_diff(root.trim(), "-weird").capture_stat_and_patch(80).expect("diff commands succeed").expect("non-empty diff between the two refs");diff --git a/src/commands/picker/log_formatter.rs b/src/commands/picker/log_formatter.rsindex 0a9531509..5f1547455 100644--- a/src/commands/picker/log_formatter.rs+++ b/src/commands/picker/log_formatter.rs@@ -46,7 +46,14 @@ pub(super) fn batch_fetch_stats(return HashMap::new();};let Ok(output) = Cmd::new("git")- .args(["diff-tree", "--numstat", "-r", "--root", "--stdin"])+ .args([+ "diff-tree",+ "--numstat",+ "-r",+ "--root",+ "--ignore-submodules=none",+ "--stdin",+ ]).current_dir(repo_path).stdin_bytes(stdin_data).run()diff --git a/src/commands/step/commit.rs b/src/commands/step/commit.rsindex a318f632a..3e1effb4a 100644--- a/src/commands/step/commit.rs+++ b/src/commands/step/commit.rs@@ -107,7 +107,7 @@ fn preview_commit(} else {None};- let index_override = temp_index.as_ref().map(|temp| temp.path());+ let staging_index = temp_index.as_ref();let ctx = env.context(yes);let project_append = resolve_template_for_preview(&ctx, &commit_config, dry_run)?;@@ -115,7 +115,7 @@ fn preview_commit(let prompt = crate::llm::build_commit_prompt(&commit_config,&wt,- index_override,+ staging_index,project_append.as_deref(),)?;if !dry_run {@@ -125,7 +125,7 @@ fn preview_commit(let message = crate::llm::generate_commit_message(&commit_config,&wt,- index_override,+ staging_index,project_append.as_deref(),)?;print_dry_run(&prompt, &commit_config, &message)diff --git a/src/commands/step/diff.rs b/src/commands/step/diff.rsindex 580e1d6c6..52ac36d96 100644--- a/src/commands/step/diff.rs+++ b/src/commands/step/diff.rs@@ -7,7 +7,7 @@ use worktrunk::git::Repository;////// Shows all changes since branching from the target: committed, staged, unstaged,/// and untracked files in a single diff. Stages untracked files into a temp index-/// (`WorkingTree::prepare_diff_with_untracked`) so they appear in the diff+/// (`WorkingTree::temp_index_with_untracked`) so they appear in the diff/// without mutating the real index — git's stat cache stays warm and tracked/// files aren't re-hashed.///@@ -32,8 +32,8 @@ pub fn step_diff(.context("No common ancestor with target branch")?;// Stream diff to stdout — git handles pager and coloring.- wt.prepare_diff_with_untracked([merge_base])?- .stream(extra_args)?;+ wt.temp_index_with_untracked()?+ .stream_diff(&merge_base, extra_args)?;Ok(())}diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rsindex 751a6e8e3..c21835ad4 100644--- a/src/commands/step/prune.rs+++ b/src/commands/step/prune.rs@@ -708,7 +708,14 @@ fn worktree_age(fn orphan_branch_age(repo: &Repository, branch: &str, now_secs: u64) -> Option<Duration> {let ref_name = format!("refs/heads/{branch}");let stdout = repo- .run_command(&["reflog", "show", "--date=unix", "--format=%gd", &ref_name])+ .run_command(&[+ "reflog",+ "show",+ "--no-show-signature",+ "--date=unix",+ "--format=%gd",+ &ref_name,+ ]).ok()?;let created_epoch = stdout.trim()diff --git a/src/commands/step/rebase.rs b/src/commands/step/rebase.rsindex f0cf0b1e4..7db99a7b3 100644--- a/src/commands/step/rebase.rs+++ b/src/commands/step/rebase.rs@@ -54,7 +54,15 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {);}- let rebase_result = repo.run_command(&["rebase", "--end-of-options", &integration_target]);+ // `--no-update-refs` overrides `rebase.updateRefs`, which would also move+ // other local branches stacked in the rebased range; a worktree's rebase+ // rewrites only its own branch.+ let rebase_result = repo.run_command(&[+ "rebase",+ "--no-update-refs",+ "--end-of-options",+ &integration_target,+ ]);// If rebase failed, classify the failure (interrupt vs conflict vs other).if let Err(e) = rebase_result {diff --git a/src/commands/step/squash.rs b/src/commands/step/squash.rsindex cedb70fea..8d78409b9 100644--- a/src/commands/step/squash.rs+++ b/src/commands/step/squash.rs@@ -226,9 +226,9 @@ pub fn handle_squash(// Get total stats (commits + any working tree changes)let total_stats = if has_staged {- wt.diff_stats_summary(&["diff", "--shortstat", &merge_base, "--cached"])+ wt.prepare_staged_diff(&merge_base).stats_summary()} else {- wt.diff_stats_summary(&["diff", "--shortstat", &range])+ wt.prepare_commit_diff(&merge_base, "HEAD").stats_summary()};let with_changes = if has_staged {diff --git a/src/commands/worktree/push.rs b/src/commands/worktree/push.rsindex 54ce02bc4..1b10cb0b5 100644--- a/src/commands/worktree/push.rs+++ b/src/commands/worktree/push.rs@@ -197,12 +197,9 @@ impl MergeContext {let commit_count = repo.count_commits(&target_branch, "HEAD")?;let stats_summary = if commit_count > 0 {- repo.current_worktree().diff_stats_summary(&[- "diff",- "--shortstat",- "--end-of-options",- &format!("{}..HEAD", target_branch),- ])+ repo.current_worktree()+ .prepare_commit_diff(&target_branch, "HEAD")+ .stats_summary()} else {Vec::new()};@@ -263,7 +260,7 @@ impl MergeContext {eprintln!("{}", format_with_gutter(&log_output, None));// Diff statistics- crate::commands::show_diffstat(&self.repo, &format!("{}..HEAD", self.target_branch))?;+ crate::commands::show_diffstat(&self.repo, &self.target_branch, "HEAD")?;Ok(())}@@ -568,18 +565,23 @@ pub fn handle_no_ff_merge(feature_branch, ctx.target_branch);+ let mut commit_tree_args = vec![+ "commit-tree",+ &tree,+ "-p",+ &ctx.target_tip,+ "-p",+ &ctx.head_sha,+ "-m",+ &merge_message,+ ];+ // Sign as `git merge --no-ff` would; `commit-tree` ignores `commit.gpgSign`.+ if ctx.repo.signs_commits()? {+ commit_tree_args.push("--gpg-sign");+ }let merge_sha = ctx.repo- .run_command(&[- "commit-tree",- &tree,- "-p",- &ctx.target_tip,- "-p",- &ctx.head_sha,- "-m",- &merge_message,- ])+ .run_command(&commit_tree_args).context("Failed to create merge commit")?.trim().to_string();diff --git a/src/git/mod.rs b/src/git/mod.rsindex 9c815ce33..cc2ecc677 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -31,7 +31,7 @@ mod test;//// Heavy operations protected:// - git rev-list --count (accesses commit-graph via mmap)-// - git diff --shortstat (accesses pack files and indexes via mmap)+// - git diff-tree --shortstat (accesses pack files and indexes via mmap)use crate::path::canonicalize_with_parents;use crate::sync::Semaphore;use std::sync::LazyLock;diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rsindex a4e438295..22f423794 100644--- a/src/git/repository/diff.rs+++ b/src/git/repository/diff.rs@@ -12,44 +12,45 @@ use crate::shell_exec::Cmd;use super::working_tree::{TempIndex, WorkingTree, path_to_logging_context};use super::{DiffStats, LineDiff, Repository};-enum DiffSource<'repo> {- Repository {- repo: &'repo Repository,- path: PathBuf,- },- TempIndex(TempIndex),+enum DiffSource<'a> {+ Repository { repo: &'a Repository, path: PathBuf },+ TempIndex(&'a TempIndex),}-/// A fully specified `git diff` whose execution can be captured or streamed.+enum DiffSides {+ /// A tree-ish against the worktree's files, seen through the source's index.+ WorkingTree(String),+ /// A tree-ish against the source's index.+ Staged(String),+ /// One tree-ish against another.+ Commits(String, String),+}++/// A fully specified diff that `wt` captures to parse, render, cache, or send+/// to an LLM.+///+/// Captures run git's plumbing (`diff-index`, `diff-tree`), which ignores+/// `diff.external`, `diff.relative`, `color.ui=always`, and the prefix+/// settings. Captures restore the `git diff` defaults plumbing lacks: rename+/// detection, textconv filters, and hiding intent-to-add entries from a staged+/// diff. They also override `submodule.<name>.ignore`, which plumbing still+/// honors and which would hide a submodule bump. Plumbing's default output is+/// the raw format, so every capture names the format it wants (`--patch`,+/// `--stat`).///-/// The source owns a temporary index when untracked files must participate in-/// the diff. Keeping that index alive in this value makes multi-command reads-/// such as a stat followed by a patch observe the same prepared worktree state.+/// A diff prepared from a [`TempIndex`] borrows it, so every read — a stat,+/// then a patch — observes the same index state.#[must_use]-pub struct PreparedDiff<'repo> {- source: DiffSource<'repo>,- revisions: Vec<String>,+pub struct PreparedDiff<'a> {+ source: DiffSource<'a>,+ sides: DiffSides,}-impl<'repo> PreparedDiff<'repo> {- fn new(- repo: &'repo Repository,- path: PathBuf,- revisions: impl IntoIterator<Item = impl Into<String>>,- ) -> Self {+impl<'a> PreparedDiff<'a> {+ fn new(repo: &'a Repository, path: PathBuf, sides: DiffSides) -> Self {Self {source: DiffSource::Repository { repo, path },- revisions: revisions.into_iter().map(Into::into).collect(),- }- }-- fn with_temp_index(- index: TempIndex,- revisions: impl IntoIterator<Item = impl Into<String>>,- ) -> Self {- Self {- source: DiffSource::TempIndex(index),- revisions: revisions.into_iter().map(Into::into).collect(),+ sides,}}@@ -76,33 +77,54 @@ impl<'repo> PreparedDiff<'repo> {Ok(String::from_utf8_lossy(&output.stdout).into_owned())}- /// Capture one diff invocation with `options` placed before the revisions.+ fn revisions(&self) -> Vec<String> {+ match &self.sides {+ DiffSides::WorkingTree(base) | DiffSides::Staged(base) => vec![base.clone()],+ DiffSides::Commits(from, to) => vec![from.clone(), to.clone()],+ }+ }++ /// Capture one plumbing diff invocation with `options` placed before the+ /// revisions.///- /// Revisions are fenced with `--end-of-options`, so even a ref beginning- /// with `-` is treated as a positional argument.+ /// Revisions sit between `--end-of-options`, so a ref beginning with `-`+ /// stays a revision, and `--`, so a path sharing a ref's name can't make+ /// the argument ambiguous.pub fn capture(&self,options: impl IntoIterator<Item = impl Into<String>>,- ) -> anyhow::Result<String> {- self.capture_with_git_options(std::iter::empty::<String>(), options)- }-- /// Capture one diff invocation with git-wide options placed before the- /// `diff` subcommand and diff options placed after it.- pub fn capture_with_git_options(- &self,- git_options: impl IntoIterator<Item = impl Into<String>>,- diff_options: impl IntoIterator<Item = impl Into<String>>,) -> anyhow::Result<String> {let mut args = vec!["--no-optional-locks".to_string()];- args.extend(git_options.into_iter().map(Into::into));- args.push("diff".to_string());- args.extend(diff_options.into_iter().map(Into::into));- args.push("--end-of-options".to_string());- args.extend(self.revisions.iter().cloned());+ 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(options.into_iter().map(Into::into));+ args.push("--end-of-options".into());+ args.extend(self.revisions());+ args.push("--".into());self.run(&args)}+ /// Summarize the diff for display, like `["3 files", "+45", "-12"]`.+ ///+ /// Empty when the diff fails or has no changes.+ pub fn stats_summary(&self) -> Vec<String> {+ self.capture(["--shortstat"])+ .map(|output| DiffStats::from_shortstat(&output).format_summary())+ .unwrap_or_default()+ }+/// Capture a stat header followed by the colored patch.////// Returns `None` when the stat is empty, avoiding the second git command.@@ -116,50 +138,99 @@ impl<'repo> PreparedDiff<'repo> {return Ok(None);}- let patch = self.capture(["--color=always"])?;+ let patch = self.capture(["--patch", "--color=always"])?;Ok(Some(format!("{stat}{patch}")))}-- /// Stream the diff, preserving `wt step diff`'s argument order so git owns- /// paging, coloring, and interpretation of caller-supplied arguments.- pub fn stream(&self, extra_args: &[String]) -> anyhow::Result<()> {- let mut args = vec!["diff".to_string()];- args.extend(self.revisions.iter().cloned());- args.extend_from_slice(extra_args);- self.command(&args).stream()- }}impl Repository {- /// Prepare an immutable revision diff in this repository's context.- pub fn prepare_diff(- &self,- revisions: impl IntoIterator<Item = impl Into<String>>,- ) -> PreparedDiff<'_> {- PreparedDiff::new(self, self.discovery_path().to_path_buf(), revisions)+ /// Prepare an immutable diff from one tree-ish to another in this+ /// repository's context.+ ///+ /// For `git diff A...B`, pass the merge base as `from`: `diff-tree` reads+ /// a literal `A...B` as no revisions, and its `--merge-base` fails when+ /// there are several merge bases.+ pub fn prepare_diff(&self, from: impl Into<String>, to: impl Into<String>) -> PreparedDiff<'_> {+ PreparedDiff::new(+ self,+ self.discovery_path().to_path_buf(),+ DiffSides::Commits(from.into(), to.into()),+ )}}impl<'repo> WorkingTree<'repo> {- /// Prepare a diff against this worktree's tracked index and files.- pub fn prepare_diff(- &self,- revisions: impl IntoIterator<Item = impl Into<String>>,- ) -> PreparedDiff<'repo> {- PreparedDiff::new(self.repo, self.path.clone(), revisions)+ /// Prepare a diff from `base` to this worktree's tracked index and files.+ pub fn prepare_diff(&self, base: impl Into<String>) -> PreparedDiff<'repo> {+ PreparedDiff::new(+ self.repo,+ self.path.clone(),+ DiffSides::WorkingTree(base.into()),+ )}- /// Prepare a diff that also includes untracked files without changing the- /// real index.- pub fn prepare_diff_with_untracked(- &self,- revisions: impl IntoIterator<Item = impl Into<String>>,- ) -> anyhow::Result<PreparedDiff<'repo>> {+ /// A temporary copy of this worktree's index with untracked files+ /// registered, so a diff prepared from it includes them without changing+ /// the real index.+ pub fn temp_index_with_untracked(&self) -> anyhow::Result<TempIndex> {let index = self.temp_index()?;index.register_untracked()?;- Ok(PreparedDiff::with_temp_index(index, revisions))+ Ok(index)+ }++ /// Prepare a diff from one tree-ish to another, resolved in this worktree+ /// so that `HEAD` names this worktree's HEAD.+ pub fn prepare_commit_diff(+ &self,+ from: impl Into<String>,+ to: impl Into<String>,+ ) -> PreparedDiff<'repo> {+ PreparedDiff::new(+ self.repo,+ self.path.clone(),+ DiffSides::Commits(from.into(), to.into()),+ )+ }++ /// Prepare a diff from `base` to this worktree's staged changes.+ ///+ /// For the changes a commit would record, `base` is [`Self::index_base`].+ pub fn prepare_staged_diff(&self, base: impl Into<String>) -> PreparedDiff<'repo> {+ PreparedDiff::new(self.repo, self.path.clone(), DiffSides::Staged(base.into()))+ }+}++impl TempIndex {+ /// Prepare a diff from `base` to the worktree's files, seen through this+ /// index.+ pub fn prepare_diff(&self, base: impl Into<String>) -> PreparedDiff<'_> {+ PreparedDiff {+ source: DiffSource::TempIndex(self),+ sides: DiffSides::WorkingTree(base.into()),+ }+ }++ /// Prepare a diff from `base` to what this index has staged.+ pub fn prepare_staged_diff(&self, base: impl Into<String>) -> PreparedDiff<'_> {+ PreparedDiff {+ source: DiffSource::TempIndex(self),+ sides: DiffSides::Staged(base.into()),+ }}+ /// Stream porcelain `git diff <base> <extra_args>` from the worktree's+ /// files, seen through this index.+ ///+ /// Porcelain, unlike [`PreparedDiff`]: `wt step diff` hands the user git's+ /// own view, so git owns paging, coloring, and the caller's arguments.+ pub fn stream_diff(&self, base: &str, extra_args: &[String]) -> anyhow::Result<()> {+ let mut args = vec!["diff".to_string(), base.to_string()];+ args.extend_from_slice(extra_args);+ self.command(args).stream()+ }+}++impl<'repo> WorkingTree<'repo> {/// Get recent commit subjects for style reference.////// Returns up to `count` commit subjects (first line of message), excluding merges.@@ -197,22 +268,6 @@ impl<'repo> WorkingTree<'repo> {}})}-- /// Get formatted diff stats summary for display.- ///- /// Returns a vector of formatted strings like ["3 files", "+45", "-12"].- /// Returns empty vector if diff command fails or produces no output.- ///- /// Callers pass args including `--shortstat` which produces a single summary line.- ///- /// Worktree-scoped for the same reason as [`Self::recent_commit_subjects`]:- /// every caller diffs the index or HEAD, both of which are per-worktree.- pub fn diff_stats_summary(&self, args: &[&str]) -> Vec<String> {- self.run_command(args)- .ok()- .map(|output| DiffStats::from_shortstat(&output).format_summary())- .unwrap_or_default()- }}/// Subject and body for one commit in a range.@@ -263,36 +318,30 @@ impl Repository {.context("Failed to parse commit count")}- /// Get files changed between base and head.+ /// Get files changed between base and head, as repository-root-relative+ /// paths.///- /// For renames and copies, both old and new paths are included to ensure- /// overlap detection works correctly (e.g., detecting conflicts when a file- /// is renamed in one branch but has uncommitted changes under the old name).+ /// `diff-tree` detects no renames, so a moved file lists both its old and+ /// new path — what overlap detection needs (e.g., detecting conflicts when+ /// 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 range = format!("{}..{}", base, head);- let stdout =- self.run_command(&["diff", "--name-status", "-z", "--end-of-options", &range])?;-- // Format: STATUS\0PATH\0 or STATUS\0NEW_PATH\0OLD_PATH\0 for renames/copies- let mut files = Vec::new();- let mut parts = stdout.split('\0').filter(|s| !s.is_empty());-- while let Some(status) = parts.next() {- let path = parts- .next()- .ok_or_else(|| anyhow::anyhow!("Malformed git diff output: status without path"))?;- files.push(path.to_string());-- // For renames (R) and copies (C), the old path follows- if status.starts_with('R') || status.starts_with('C') {- let old_path = parts.next().ok_or_else(|| {- anyhow::anyhow!("Malformed git diff output: rename/copy without old path")- })?;- files.push(old_path.to_string());- }- }-- Ok(files)+ let stdout = self.run_command(&[+ "diff-tree",+ "-r",+ "--name-only",+ "-z",+ "--ignore-submodules=none",+ "--end-of-options",+ base,+ head,+ "--",+ ])?;+ Ok(stdout+ .split('\0')+ .filter(|path| !path.is_empty())+ .map(str::to_string)+ .collect())}/// Get short SHA, commit timestamp and subject for multiple commits in a@@ -603,13 +652,23 @@ impl Repository {return Ok(LineDiff::default());};- let range = format!("{}..{}", merge_base, head_sha);- let mut args = vec!["diff", "--shortstat", &range];-- if !sparse_paths.is_empty() {- args.push("--");- args.extend(sparse_paths.iter().map(|s| s.as_str()));- }+ // Sparse paths are root-relative, but git resolves pathspecs against+ // the cwd, which is the user's subdirectory when run from one.+ let sparse_pathspecs: Vec<String> = sparse_paths+ .iter()+ .map(|path| format!(":(top){path}"))+ .collect();+ let mut args = vec![+ "diff-tree",+ "-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)?;let result = LineDiff::from_shortstat(&stdout);diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rsindex 9ce8f3cb3..aa3cc1882 100644--- a/src/git/repository/integration.rs+++ b/src/git/repository/integration.rs@@ -40,11 +40,15 @@ pub fn select_comparison_base<'a>(targets.map(|t| t.primary.as_str()).or(default_branch)}-/// Git's well-known empty-tree object. Diffing a commit against it yields the-/// commit's full content as additions — the orphan-branch fallback for the-/// diff/summary preview panes, which can't three-dot-diff a branch that shares-/// no history with the comparison base.-pub(super) const EMPTY_TREE_SHA: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";+/// Git's well-known empty-tree object in a SHA-1 repository. Diffing a commit+/// against it yields the commit's full content as additions — the+/// orphan-branch fallback for the diff/summary preview panes, and the staged+/// diff's base on an unborn branch. [`Repository::empty_tree_sha`] picks the+/// id for the repository's object format.+pub(super) const EMPTY_TREE_SHA1: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";++/// The empty-tree object in a SHA-256 repository.+const EMPTY_TREE_SHA256: &str = "6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321";/// The upstream-aware base a branch's content is measured against in the/// diff/summary preview panes — [`IntegrationTargets::primary`], resolved once@@ -72,16 +76,12 @@ pub(in crate::git) struct ComparisonBase {/// [`Repository::branch_diff_spec`].#[derive(Debug, Clone)]pub struct BranchDiffSpec {- /// The `git diff` revision arguments to splice in after `diff` and any- /// options: a single three-dot range `["{base}...{head}"]` normally, or- /// `["{empty-tree}", "{head}"]` for an orphan.- pub revs: Vec<String>,- /// Single tree-ish to compare with the worktree when rendering a unified- /// committed + uncommitted diff: the merge-base SHA normally, or the empty- /// tree for an orphan. `None` only when merge-base resolution failed; unlike- /// the committed-only three-dot diff, a worktree diff has no correct range- /// fallback in that case.- pub working_base: Option<String>,+ /// The tree-ish the branch's changes are measured from, for both the+ /// committed diff (to the branch head) and the unified diff (to the+ /// worktree): the merge-base SHA normally, or the empty tree for an+ /// orphan. `None` when merge-base resolution failed, so the panes report+ /// the diff as unavailable rather than guess a base.+ pub diff_base: Option<String>,/// Display name of the comparison base, for "no file changes vs X".pub base_name: String,/// Stable SHA identifying the base for disk-cache keying: the base's commit@@ -193,9 +193,27 @@ impl Repository {return Ok(true);};- let range = format!("{merge_base}..{branch_sha}");- let output = self.run_command(&["diff", "--name-only", &range])?;- let result = !output.trim().is_empty();+ // `--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 output = self.run_command_output(&args)?;+ let result = match output.status.code() {+ Some(0) => false,+ Some(1) => true,+ _ => {+ return Err(+ crate::git::CommandError::from_failed_output("git", &args, &output).into(),+ );+ }+ };super::sha_cache::put_has_added_changes(self, branch_sha, target_sha, result);Ok(result)}@@ -379,7 +397,10 @@ 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`].+ /// 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.////// Only runs when `merge-tree` conflicts (both sides modified the same files),/// since `MergeAddsNothing` handles the non-conflict case. Cost scales with the@@ -418,7 +439,17 @@ 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], None)?;+ let branch_pids = self.patch_ids_from(+ &[+ "diff-tree",+ "--patch",+ "--ignore-submodules=none",+ &merge_base,+ branch,+ "--",+ ],+ None,+ )?;let Some(branch_pid) = branch_pids.split_whitespace().next() else {return Ok(false);};@@ -433,7 +464,12 @@ 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", "-p"],+ &[+ "diff-tree",+ "--stdin",+ "--patch",+ "--ignore-submodules=none",+ ],Some(target_commits.into_bytes()),)?;@@ -639,6 +675,16 @@ impl Repository {Some(ComparisonBase { name, sha })}+ /// The empty tree's object id in this repository's object format.+ pub(super) fn empty_tree_sha(&self) -> anyhow::Result<&'static str> {+ Ok(+ match self.config_value("extensions.objectFormat")?.as_deref() {+ Some("sha256") => EMPTY_TREE_SHA256,+ _ => EMPTY_TREE_SHA1,+ },+ )+ }+/// Resolve how to diff a branch's content against the mainline for the/// diff/summary preview panes. `head` is a resolved commit SHA. See/// [`BranchDiffSpec`]. Returns `None` when there's no comparison base (no@@ -647,32 +693,21 @@ impl Repository {let base = self.comparison_base()?;let base_sha = base.sha.as_str();- // Orphan (no merge base with the base): a three-dot range is- // ill-defined, so diff the full content against the empty tree. A- // merge-base *error* (invalid/unreachable object) is NOT an orphan —- // fall through to the normal three-dot range and let the diff surface- // the failure rather than dumping the whole tree as "the branch".- let (revs, working_base, cache_sha) = match self.merge_base_by_sha(base_sha, head) {- Ok(None) => (- vec![EMPTY_TREE_SHA.to_string(), head.to_string()],- Some(EMPTY_TREE_SHA.to_string()),- EMPTY_TREE_SHA.to_string(),- ),- Ok(Some(merge_base)) => (- vec![format!("{base_sha}...{head}")],- Some(merge_base),- base_sha.to_string(),- ),- Err(_) => (- vec![format!("{base_sha}...{head}")],- None,- base_sha.to_string(),- ),+ // Orphan (no merge base with the base): diff the full content against+ // the empty tree. A merge-base *error* (invalid/unreachable object) is+ // NOT an orphan — leave the base unresolved so the panes report the+ // failure rather than dumping the whole tree as "the branch".+ let (diff_base, cache_sha) = match self.merge_base_by_sha(base_sha, head) {+ Ok(None) => {+ let empty_tree = self.empty_tree_sha().ok()?;+ (Some(empty_tree.to_string()), empty_tree.to_string())+ }+ Ok(Some(merge_base)) => (Some(merge_base), base_sha.to_string()),+ Err(_) => (None, base_sha.to_string()),};Some(BranchDiffSpec {- revs,- working_base,+ diff_base,base_name: base.name.clone(),cache_sha,})@@ -1186,6 +1221,60 @@ mod patch_id_tests {"squash merge must be detected via patch-id regardless of diff.* config");}++ /// Patch-ids count a submodule bump under `submodule.<name>.ignore = all`,+ /// which hides the bump from plain plumbing. The branch edits a file and+ /// bumps a submodule: a target squash that dropped the bump must not+ /// match, and one that carried it must. Each target re-touches the same+ /// line afterwards so `merge-tree` conflicts and the patch-id fallback+ /// runs.+ #[test]+ fn patch_id_counts_submodule_bump_under_submodule_ignore() {+ let test = TestRepo::new();+ let repo = &test.repo;+ let path = test.path().join("file");+ let gitlink = |sha: &str| format!("160000,{sha},sub");++ std::fs::write(+ test.path().join(".gitmodules"),+ "[submodule \"sub\"]\n\tpath = sub\n\turl = ./sub\n",+ )+ .unwrap();+ std::fs::write(&path, "one\ntwo\nthree\n").unwrap();+ test.run_git(&["add", ".gitmodules", "file"]);+ test.run_git(&["commit", "--message", "base"]);+ let base = test.git_output(&["rev-parse", "HEAD"]);+ test.run_git(&["update-index", "--add", "--cacheinfo", &gitlink(&base)]);+ test.run_git(&["commit", "--message", "add submodule"]);+ let fork = test.git_output(&["rev-parse", "HEAD"]);++ let commit_on = |branch: &str, bump: bool| {+ test.run_git(&["switch", "--create", branch, &fork]);+ std::fs::write(&path, "one\nFEATURE\nthree\n").unwrap();+ test.run_git(&["add", "file"]);+ if bump {+ test.run_git(&["update-index", "--cacheinfo", &gitlink(&fork)]);+ }+ test.run_git(&["commit", "--message", branch]);+ };+ commit_on("feature", true);+ for (target, bump) in [("dropped", false), ("carried", true)] {+ commit_on(target, bump);+ std::fs::write(&path, "one\nPADDED\nthree\n").unwrap();+ test.run_git(&["add", "file"]);+ test.run_git(&["commit", "--message", "follow-up on same line"]);+ }+ test.run_git(&["config", "submodule.sub.ignore", "all"]);++ let snapshot = repo.capture_refs().unwrap();+ let reason = |target: &str| {+ check_integration(+ &compute_integration_lazy(repo, &snapshot, "feature", target).unwrap(),+ )+ };+ assert_eq!(reason("dropped"), None);+ assert_eq!(reason("carried"), Some(IntegrationReason::PatchIdMatch));+ }}#[cfg(test)]@@ -1212,6 +1301,41 @@ mod merge_tree_error_tests {}}+#[cfg(test)]+mod has_added_changes_error_tests {+ use super::*;+ use crate::testing::TestRepo;++ /// A `git diff-tree` failure (here: the branch's tree object is missing)+ /// must surface as a typed `CommandError`, not read as "no added changes",+ /// which would let `wt remove` delete the branch.+ #[test]+ fn diff_tree_failure_is_command_error() {+ let test = TestRepo::with_initial_commit();+ let target_sha = test.git_output(&["rev-parse", "HEAD"]);+ std::fs::write(test.root_path().join("added.txt"), "added\n").unwrap();+ test.run_git(&["add", "added.txt"]);+ test.run_git(&["commit", "--message", "add file"]);+ let branch_sha = test.git_output(&["rev-parse", "HEAD"]);+ let tree = test.git_output(&["rev-parse", "HEAD^{tree}"]);+ let (dir, file) = tree.split_at(2);+ std::fs::remove_file(test.root_path().join(".git/objects").join(dir).join(file)).unwrap();+ let repo = Repository::at(test.root_path()).unwrap();++ let err = repo+ .has_added_changes_by_sha(&branch_sha, &target_sha)+ .unwrap_err();+ let cmd_err =+ crate::git::CommandError::find_in(&err).expect("error should carry a CommandError");+ assert!(+ cmd_err+ .command_string()+ .starts_with("git diff-tree --quiet"),+ "{err:#}"+ );+ }+}+#[cfg(test)]mod merge_tree_cache_tests {use super::*;diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex f4b8c7130..16a74d6bd 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -1731,6 +1731,14 @@ impl Repository {self.config_bool("core.bare")}+ /// Whether `commit.gpgSign` asks for signed commits.+ ///+ /// `git commit` and `git merge` honor it; `git commit-tree` ignores it, so+ /// a commit meant to match what porcelain would record passes `-S` itself.+ pub fn signs_commits(&self) -> anyhow::Result<bool> {+ self.config_bool("commit.gpgSign")+ }+/// Get the sparse checkout paths for this repository.////// Returns the list of paths from `git sparse-checkout list`. For non-sparse@@ -1931,14 +1939,14 @@ impl Repository {/// Run a git command and return whether it succeeded (exit code 0).////// This is useful for commands that use exit codes for boolean results,- /// like `git merge-base --is-ancestor` or `git diff --quiet`.+ /// like `git merge-base --is-ancestor`.////// # Examples/// ```no_run/// use worktrunk::git::Repository;////// let repo = Repository::current()?;- /// let is_clean = repo.run_command_check(&["diff", "--quiet", "--exit-code"])?;+ /// let merged = repo.run_command_check(&["merge-base", "--is-ancestor", "feature", "main"])?;/// # Ok::<(), anyhow::Error>(())/// ```pub fn run_command_check(&self, args: &[&str]) -> anyhow::Result<bool> {diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rsindex 54f97b6d2..a78590f15 100644--- a/src/git/repository/tests.rs+++ b/src/git/repository/tests.rs@@ -1065,7 +1065,7 @@ fn build_worktree_config_bare_layout() -> (tempfile::TempDir, std::path::PathBuf"commit-tree","-m","init",- super::integration::EMPTY_TREE_SHA,+ super::integration::EMPTY_TREE_SHA1,]).run().unwrap();diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex af6f085b5..138ccb0ad 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -483,6 +483,18 @@ impl<'a> WorkingTree<'a> {.filter(|s| !s.is_empty()))}+ /// The tree-ish the index is compared against for staged changes: HEAD,+ /// or the empty tree on an unborn branch.+ ///+ /// Porcelain `git diff --cached` picks this itself; plumbing+ /// (`diff-index --cached`) needs it spelled out.+ pub fn index_base(&self) -> anyhow::Result<String> {+ match self.head_sha()? {+ Some(head) => Ok(head),+ None => Ok(self.repo.empty_tree_sha()?.to_string()),+ }+ }+/// Return cached `git status --porcelain` output for this worktree.////// Keyed by worktree path in the shared `RepoCache`, so parallel tasks that@@ -678,7 +690,13 @@ impl<'a> WorkingTree<'a> {/// all.pub fn unmerged_paths(&self) -> anyhow::Result<Vec<String>> {let output = self- .run_command(&["diff", "--name-only", "--diff-filter=U", "-z"])+ .run_command(&[+ "diff-files",+ "--name-only",+ "--diff-filter=U",+ "-z",+ "--ignore-submodules=none",+ ]).context("Failed to list unmerged paths")?;Ok(output.split('\0')@@ -873,13 +891,20 @@ 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", "--shortstat", "--find-renames", "HEAD"])?;+ let stdout = self.run_command(&[+ "diff-index",+ "--shortstat",+ "--find-renames",+ "--ignore-submodules=none",+ "HEAD",+ "--",+ ])?;Ok(LineDiff::from_shortstat(&stdout))}/// Working-tree diff stats vs HEAD that also count untracked files.- /// The scope matches `wt step diff`; explicit rename detection keeps- /// `HEAD±` stable across user Git configuration.+ /// The scope matches `wt step diff`. Plumbing ignores the user's diff+ /// configuration, and explicit rename detection pairs moves.////// Untracked paths enter a temporary index as intent-to-add entries, which/// lets one diff pair them with tracked deletions as renames without writing@@ -898,12 +923,14 @@ impl<'a> WorkingTree<'a> {}let numstat_args = [- "diff",+ "diff-index","--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() {@@ -1772,7 +1799,7 @@ mod tests {assert!(cmd_err.command_string()- .starts_with("git diff --numstat -z --find-renames --end-of-options HEAD")+ .starts_with("git diff-index --numstat -z --find-renames --ignore-submodules=none --end-of-options HEAD"));}diff --git a/src/llm.rs b/src/llm.rsindex cda6d3f4f..63cf1ec5c 100644--- a/src/llm.rs+++ b/src/llm.rs@@ -5,7 +5,9 @@ use std::fmt;use std::path::Path;use std::sync::Arc;use worktrunk::config::CommitGenerationConfig;-use worktrunk::git::{CommandError, CommitMessageDetail, ErrorExt, Repository, WorkingTree};+use worktrunk::git::{+ CommandError, CommitMessageDetail, ErrorExt, Repository, TempIndex, WorkingTree,+};use worktrunk::shell_exec::{Cmd, ShellConfig};use minijinja::Environment;@@ -155,23 +157,6 @@ const MAX_SQUASH_COMMITS: usize = 200;/// Lock file patterns that are filtered out when diff is too largeconst LOCK_FILE_PATTERNS: &[&str] = &[".lock", "-lock.json", "-lock.yaml", ".lock.hcl"];-/// Git `-c` overrides forcing the `a/`/`b/` diff prefix format regardless of-/// user config: `diff.noprefix`, `diff.mnemonicPrefix`, and (git >= 2.45)-/// `diff.srcPrefix`/`diff.dstPrefix` can all change the header format that-/// [`parse_diff_sections`] splits file sections on, so every full diff-/// destined for [`prepare_diff`] must carry these flags. Unknown config keys-/// are ignored by older git.-pub(crate) const DIFF_PREFIX_OVERRIDES: [&str; 8] = [- "-c",- "diff.noprefix=false",- "-c",- "diff.mnemonicPrefix=false",- "-c",- "diff.srcPrefix=a/",- "-c",- "diff.dstPrefix=b/",-];-/// Prepared diff output with optional filtering appliedpub(crate) struct PreparedDiff {/// The diff content (possibly filtered/truncated)@@ -189,8 +174,9 @@ fn is_lock_file(filename: &str) -> bool {/// Extract the destination path from a `diff --git` header line.///-/// [`DIFF_PREFIX_OVERRIDES`] pins the prefixes to `a/` and `b/`, so the-/// destination begins at the last ` b/` — or, when git quotes the pair,+/// Every diff fed to [`prepare_diff`] comes from plumbing (`diff-index`,+/// `diff-tree`), which ignores the prefix settings and always writes `a/` and+/// `b/`, so the destination begins at the last ` b/` — or, when git quotes the pair,/// at the last ` "b/`. Quoting is not optional: `core.quotePath` escapes a/// non-ASCII name, and a name holding `"` or `\` is quoted whatever that/// setting says, so a parser that only knows the bare form fails on both.@@ -412,7 +398,7 @@ pub(crate) fn prepare_diff(diff: String, stat: String) -> PreparedDiff {struct PromptContext<'a> {/// The diff to describe (staged changes for commit, combined diff for squash)git_diff: &'a str,- /// Diff statistics summary (output of git diff --stat)+ /// Diff statistics summary (`--stat` output)git_diff_stat: &'a str,/// Current branch namebranch: &'a str,@@ -524,7 +510,7 @@ const DEFAULT_SQUASH_TEMPLATE: &str = r#"<task>Write a commit message for the co/// All LLM execution should go through this function to maintain consistency.pub(crate) fn execute_llm_command(command: &str, prompt: &str) -> anyhow::Result<String> {// TODO(diff-pipe): Consider splitting the prompt template around- // `{{ git_diff }}` and piping `git diff` directly into the LLM via+ // `{{ git_diff }}` and piping the diff directly into the LLM via// `Cmd::pipe_into` (preamble + epilogue through env vars). Avoids buffering// MB-scale diffs in our process memory and removes them from our logs// entirely. See conversation around PR #2136 for sketch.@@ -717,8 +703,8 @@ fn build_prompt(/// --branch <b>` and `wt step relocate --commit` commit somewhere else, and/// reading the diff from the cwd instead handed the LLM an empty diff.///-/// `index_override` is forwarded to git operations that read the staging area, so-/// `--dry-run` can preview against a temp index without touching the user's real one.+/// `staging_index` is the temporary index `--dry-run` staged into, read in+/// place of the real one so the preview doesn't touch it.////// `project_append` is the approved project-level append fragment (or/// `None` to skip). It is rendered with the main template's context and@@ -728,7 +714,7 @@ fn build_prompt(pub(crate) fn generate_commit_message(commit_generation_config: &CommitGenerationConfig,wt: &WorkingTree<'_>,- index_override: Option<&Path>,+ staging_index: Option<&TempIndex>,project_append: Option<&str>,) -> anyhow::Result<String> {// Check if commit generation is configured (non-empty command)@@ -738,7 +724,7 @@ pub(crate) fn generate_commit_message(// failure of the LLM command itself gets the `LlmCommandFailed`// wrapper — mirroring `generate_squash_message`.let prompt =- build_commit_prompt(commit_generation_config, wt, index_override, project_append)?;+ build_commit_prompt(commit_generation_config, wt, staging_index, project_append)?;// A slow or hung command is otherwise silent (stdout is captured); the// watchdog surfaces a "still waiting" status. Held until this function// returns, clearing the block before the caller prints the message.@@ -758,11 +744,7 @@ pub(crate) fn generate_commit_message(}// Fallback: generate a descriptive commit message based on changed files- let file_list = run_git_capture(- &["diff", "--staged", "--name-only", "-z"],- wt.path(),- index_override,- )?;+ let file_list = staged_diff(wt, staging_index)?.capture(["--name-only", "-z"])?;let staged_files = file_list.split('\0').map(|s| s.trim())@@ -789,28 +771,17 @@ pub(crate) fn generate_commit_message(Ok(message)}-/// Run a git command and capture stdout, mirroring [`Repository::run_command`]-/// (including its [`CommandError`] on non-zero exit).-///-/// Used by call sites that need to set `GIT_INDEX_FILE` (`--dry-run`) and so can't go-/// through `Repository::run_command`. Without this check, a failing `git diff` would-/// silently feed an empty diff to the LLM.-fn run_git_capture(- args: &[&str],- cwd: &Path,- index_override: Option<&Path>,-) -> anyhow::Result<String> {- let mut cmd = Cmd::new("git").args(args.iter().copied()).current_dir(cwd);- if let Some(index) = index_override {- cmd = cmd.env("GIT_INDEX_FILE", index);- }- let output = cmd- .run()- .with_context(|| format!("Failed to execute: git {}", args.join(" ")))?;- if !output.status.success() {- return Err(CommandError::from_failed_output("git", args, &output).into());- }- Ok(String::from_utf8_lossy(&output.stdout).into_owned())+/// The changes a commit from `wt` would record, read from `staging_index`+/// when given and from the real index otherwise.+fn staged_diff<'a>(+ wt: &WorkingTree<'a>,+ staging_index: Option<&'a TempIndex>,+) -> anyhow::Result<worktrunk::git::PreparedDiff<'a>> {+ let base = wt.index_base()?;+ Ok(match staging_index {+ Some(index) => index.prepare_staged_diff(base),+ None => wt.prepare_staged_diff(base),+ })}/// Build the commit prompt from staged changes.@@ -822,25 +793,17 @@ fn run_git_capture(/// Every input is read from `wt`, the worktree being committed — which is not/// always the invoking one (see [`generate_commit_message`]).///-/// `index_override` points git at an alternate index via `GIT_INDEX_FILE` — used by-/// `--dry-run` to preview what `git add` per the user's `--stage` flag would produce-/// without modifying the real index.+/// `staging_index` is the temporary index `--dry-run` staged per the user's+/// `--stage` flag, read in place of the real index.pub(crate) fn build_commit_prompt(config: &CommitGenerationConfig,wt: &WorkingTree<'_>,- index_override: Option<&Path>,+ staging_index: Option<&TempIndex>,project_append: Option<&str>,) -> anyhow::Result<String> {- let cwd = wt.path();-- let mut diff_args: Vec<&str> = DIFF_PREFIX_OVERRIDES.to_vec();- diff_args.extend(["--no-pager", "diff", "--staged"]);- let diff_output = run_git_capture(&diff_args, cwd, index_override)?;- let diff_stat = run_git_capture(- &["--no-pager", "diff", "--staged", "--stat"],- cwd,- index_override,- )?;+ let staged = staged_diff(wt, staging_index)?;+ let diff_output = staged.capture(["--patch"])?;+ let diff_stat = staged.capture(["--stat"])?;// Prepare diff (may filter if too large)let prepared = prepare_diff(diff_output, diff_stat);@@ -933,10 +896,9 @@ pub(crate) fn build_squash_prompt(let repo = Repository::current()?;// Get the combined diff and diffstat for all commits being squashed- let mut diff_args: Vec<&str> = DIFF_PREFIX_OVERRIDES.to_vec();- diff_args.extend(["--no-pager", "diff", merge_base, "HEAD"]);- let diff_output = repo.run_command(&diff_args)?;- let diff_stat = repo.run_command(&["--no-pager", "diff", merge_base, "HEAD", "--stat"])?;+ let squashed = repo.prepare_diff(merge_base, "HEAD");+ let diff_output = squashed.capture(["--patch"])?;+ let diff_stat = squashed.capture(["--stat"])?;// Prepare diff (may filter if too large)let prepared = prepare_diff(diff_output, diff_stat);@@ -1047,21 +1009,6 @@ mod tests {);}- /// `run_git_capture` must surface a non-zero exit as a typed [`CommandError`]- /// carrying the command and its captured stderr — without that, the dry-run- /// path would feed an empty diff to the LLM on a `git` failure.- #[test]- fn test_run_git_capture_bails_on_nonzero_exit() {- let err = run_git_capture(&["frobnicate-nonexistent"], Path::new("."), None).unwrap_err();- let cmd_err = CommandError::find_in(&err).expect("error should carry a CommandError");- assert_eq!(cmd_err.command_string(), "git frobnicate-nonexistent");- assert!(- cmd_err.stderr.contains("frobnicate-nonexistent"),- "stderr should name the failing command; got: {}",- cmd_err.stderr- );- }-/// Git failures while constructing a configured prompt surface directly;/// they must not be mislabeled as a failure of the configured LLM command.#[test]diff --git a/src/summary.rs b/src/summary.rsindex 045b698aa..0a3759a07 100644--- a/src/summary.rs+++ b/src/summary.rs@@ -41,7 +41,7 @@ use worktrunk::styling::INFO_SYMBOL;use worktrunk::sync::Semaphore;use worktrunk::utils::epoch_now;-use crate::llm::{DIFF_PREFIX_OVERRIDES, execute_llm_command, prepare_diff};+use crate::llm::{execute_llm_command, prepare_diff};/// Limits concurrent LLM calls to avoid overwhelming the network / LLM/// provider. 8 permits balances parallelism with resource usage — LLM calls@@ -237,33 +237,28 @@ pub(crate) fn compute_combined_diff(// Branch diff vs the comparison base — skipped for the default-branch row// itself (the baseline) and when no comparison base resolves.let is_default_branch = repo.default_branch().as_deref() == Some(branch);- if !is_default_branch && let Some(spec) = repo.branch_diff_spec(head) {- // `--end-of-options` guards a base name that could begin with `-`; the- // stat and full-diff invocations differ only by the `--stat` flag.- // The prefix overrides keep the diff parseable into per-file sections- // by `prepare_diff` (same guard as `build_commit_prompt`).- let prepared = repo.prepare_diff(spec.revs.iter().cloned());- let run_branch_diff = |opts: &[&str], out: &mut String| {- if let Ok(text) =- prepared.capture_with_git_options(DIFF_PREFIX_OVERRIDES, opts.iter().copied())- {- out.push_str(&text);- }- };- run_branch_diff(&["--stat"], &mut stat);- run_branch_diff(&[], &mut diff);+ if !is_default_branch+ && let Some(spec) = repo.branch_diff_spec(head)+ && let Some(base) = spec.diff_base+ {+ let prepared = repo.prepare_diff(base, head);+ if let Ok(text) = prepared.capture(["--stat"]) {+ stat.push_str(&text);+ }+ if let Ok(text) = prepared.capture(["--patch"]) {+ diff.push_str(&text);+ }}// Working tree diff: uncommitted changesif let Some(wt_path) = worktree_path {- let prepared = repo.worktree_at(wt_path).prepare_diff(["HEAD"]);+ let prepared = repo.worktree_at(wt_path).prepare_diff("HEAD");if let Ok(wt_stat) = prepared.capture(["--stat"])&& !wt_stat.trim().is_empty(){stat.push_str(&wt_stat);}- if let Ok(wt_diff) =- prepared.capture_with_git_options(DIFF_PREFIX_OVERRIDES, std::iter::empty::<&str>())+ if let Ok(wt_diff) = prepared.capture(["--patch"])&& !wt_diff.trim().is_empty(){diff.push_str(&wt_diff);diff --git a/src/testing/mod.rs b/src/testing/mod.rsindex 722baf1d9..a5f48e11a 100644--- a/src/testing/mod.rs+++ b/src/testing/mod.rs@@ -1414,8 +1414,10 @@ impl TestRepo {}/// Shared initializer for `new()`, `bare()`, and `empty()`: makes a tempdir- /// and runs `git init` with the given arguments inside it.- fn init_repo(git_args: &[&str]) -> Self {+ /// and runs `git init` with the given arguments inside it. Public for a+ /// test that needs an `init` option no named constructor covers, such as+ /// `--object-format=sha256`.+ pub fn init_repo(git_args: &[&str]) -> Self {shell_exec::enable_hermetic_test_env();let temp_dir = test_tempdir();let root = temp_dir.path().join("repo");diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rsindex d49b73fb4..ac472d1dc 100644--- a/tests/integration_tests/list.rs+++ b/tests/integration_tests/list.rs@@ -2445,8 +2445,15 @@ fn mock_summary_cache(let head = String::from_utf8_lossy(&head_output.stdout).trim().to_string();- let merge_base = format!("main...{}", head);- if let Ok(output) = repo.git_command().args(["diff", &merge_base]).run() {+ let merge_base = repo.git_output(&["merge-base", "main", &head]);+ let patch_args = ["--find-renames", "--textconv", "--patch"];+ if let Ok(output) = repo+ .git_command()+ .args(["diff-tree", "-r"])+ .args(patch_args)+ .args([merge_base.as_str(), head.as_str()])+ .run()+ {let branch_diff = String::from_utf8_lossy(&output.stdout);diff.push_str(&branch_diff);}@@ -2456,7 +2463,9 @@ fn mock_summary_cache(let wt_str = wt_path.display().to_string();if let Ok(output) = repo.git_command()- .args(["-C", &wt_str, "diff", "HEAD"])+ .args(["-C", &wt_str, "diff-index"])+ .args(patch_args)+ .arg("HEAD").run(){let wt_diff = String::from_utf8_lossy(&output.stdout);diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex 51cc37d9e..dd7f0233d 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -100,6 +100,21 @@ fn test_merge_fast_forward(merge_scenario: (TestRepo, PathBuf)) {));}+/// A diff between two revisions passes them as two arguments, and git checks+/// each against the filesystem, so a directory named like the target branch+/// must not make the merge's diffs ambiguous.+#[rstest]+fn test_merge_with_directory_named_like_target(merge_scenario: (TestRepo, PathBuf)) {+ let (repo, feature_wt) = merge_scenario;+ fs::create_dir(feature_wt.join("main")).unwrap();++ let output = make_snapshot_cmd(&repo, "merge", &["main"], Some(&feature_wt))+ .output()+ .unwrap();++ assert!(output.status.success(), "{output:?}");+}+////// When git runs a subcommand, it sets `GIT_EXEC_PATH` in the environment./// Shell integration cannot work in this case because cd directives cannot@@ -1811,6 +1826,33 @@ fn test_merge_rebase_true_rebase(mut repo: TestRepo) {));}+/// `rebase.updateRefs` would also move a branch stacked inside the rebased+/// range; `wt step rebase` rewrites only the worktree's own branch.+#[rstest]+fn test_step_rebase_leaves_stacked_branches(mut repo: TestRepo) {+ let feature_wt = repo.add_worktree("feature");+ repo.commit_in_worktree(&feature_wt, "base.txt", "base\n", "Stack base");+ repo.run_git_in(&feature_wt, &["branch", "stacked"]);+ repo.commit_in_worktree(&feature_wt, "top.txt", "top\n", "Stack top");+ fs::write(repo.root_path().join("main-update.txt"), "main\n").unwrap();+ repo.run_git(&["add", "main-update.txt"]);+ repo.run_git(&["commit", "--message", "Update main"]);+ repo.run_git(&["config", "rebase.updateRefs", "true"]);+ let stacked_before = repo.git_output(&["rev-parse", "stacked"]);++ let output = make_snapshot_cmd(&repo, "step", &["rebase", "main"], Some(&feature_wt))+ .output()+ .unwrap();++ assert!(output.status.success(), "{output:?}");+ assert_eq!(repo.git_output(&["rev-parse", "stacked"]), stacked_before);+ assert_eq!(+ repo.git_output(&["merge-base", "main", "feature"]),+ repo.git_output(&["rev-parse", "main"]),+ "feature should be rebased onto main"+ );+}+// =============================================================================// --no-rebase tests// =============================================================================@@ -1929,6 +1971,44 @@ fn test_merge_no_commit_no_rebase_removes_merge_shaped_worktree(mut repo: TestRe);}+/// `wt merge --no-ff` builds its merge commit with `commit-tree`, which ignores+/// `commit.gpgSign`, so it asks for the signature `git merge --no-ff` would add.+#[cfg(unix)]+#[rstest]+fn test_merge_no_ff_signs_merge_commit(merge_scenario: (TestRepo, PathBuf)) {+ let (repo, feature_wt) = merge_scenario;+ let key = repo.root_path().parent().unwrap().join("signing-key");+ let keygen = std::process::Command::new("ssh-keygen")+ .args(["-q", "-t", "ed25519", "-N", "", "-f"])+ .arg(&key)+ .output()+ .unwrap();+ assert!(keygen.status.success(), "{keygen:?}");+ repo.run_git(&["config", "gpg.format", "ssh"]);+ repo.run_git(&["config", "user.signingKey", key.to_str().unwrap()]);+ repo.run_git(&["config", "commit.gpgSign", "true"]);++ let output = repo+ .wt_command()+ .args(["merge", "main", "--no-ff", "--no-remove", "--no-hooks"])+ .current_dir(&feature_wt)+ .output()+ .unwrap();++ assert!(output.status.success(), "{output:?}");+ assert_eq!(+ repo.git_output(&["show", "--no-patch", "--format=%P", "main"])+ .split(' ')+ .count(),+ 2+ );+ assert!(+ repo.git_output(&["cat-file", "commit", "main"])+ .contains("\ngpgsig "),+ "the merge commit must carry a signature"+ );+}+#[rstest]fn test_merge_shaped_no_ff_no_rebase_preserves_source_graph(mut repo: TestRepo) {let feature_wt = add_merge_shaped_feature(&mut repo);@@ -2914,6 +2994,93 @@ fn test_step_commit_show_prompt(repo: TestRepo) {));}+/// The staged diff hides intent-to-add entries and pairs renames, as+/// `git diff --cached` does, so the fallback message names only what the+/// commit records.+#[rstest]+fn test_step_commit_fallback_message_names_recorded_changes(repo: TestRepo) {+ fs::write(repo.root_path().join("old.txt"), "content\n").unwrap();+ repo.run_git(&["add", "old.txt"]);+ repo.run_git(&["commit", "--message", "Add old.txt"]);+ repo.run_git(&["mv", "old.txt", "new.txt"]);+ fs::write(repo.root_path().join("notes.txt"), "").unwrap();+ repo.run_git(&["add", "--intent-to-add", "notes.txt"]);++ let output = make_snapshot_cmd(+ &repo,+ "step",+ &["commit", "--stage=none", "--no-hooks"],+ None,+ )+ .output()+ .unwrap();++ assert!(output.status.success(), "{output:?}");+ assert_eq!(+ repo.git_output(&["log", "--max-count=1", "--format=%s"]),+ "Changes to new.txt"+ );+}++/// A staged diff on an unborn branch compares against the empty tree, whose+/// id depends on the repository's object format.+#[test]+fn test_step_commit_first_commit_in_sha256_repo() {+ let repo = TestRepo::init_repo(&[+ "init",+ "--quiet",+ "--initial-branch=main",+ "--object-format=sha256",+ ]);+ fs::write(repo.root_path().join("first.txt"), "first\n").unwrap();+ repo.run_git(&["add", "first.txt"]);++ let output = make_snapshot_cmd(&repo, "step", &["commit", "--no-hooks"], None)+ .output()+ .unwrap();++ assert!(output.status.success(), "{output:?}");+ assert_eq!(+ repo.git_output(&["log", "--max-count=1", "--format=%s"]),+ "Changes to first.txt"+ );+}++/// The commit and squash prompts split git's diff into per-file sections, so+/// the user's diff display settings must not change what the LLM receives.+#[rstest]+fn test_show_prompt_ignores_diff_display_config(repo_with_multi_commit_feature: TestRepo) {+ let repo = repo_with_multi_commit_feature;+ let feature_wt = repo.worktree_path("feature");+ fs::write(feature_wt.join("staged.txt"), "staged content\n").unwrap();+ repo.git_command()+ .args(["add", "staged.txt"])+ .current_dir(feature_wt)+ .run()+ .unwrap();+ let prompts = || {+ ["commit", "squash"].map(|step| {+ let output =+ make_snapshot_cmd(&repo, "step", &[step, "--show-prompt"], Some(feature_wt))+ .output()+ .unwrap();+ assert!(output.status.success(), "{output:?}");+ String::from_utf8(output.stdout).unwrap()+ })+ };++ let default_prompts = prompts();+ for (key, value) in [+ ("color.ui", "always"),+ ("diff.external", "echo"),+ ("diff.noprefix", "true"),+ ] {+ repo.run_git(&["config", key, value]);+ }++ assert_eq!(prompts(), default_prompts);+}+#[rstest]fn test_step_commit_show_prompt_no_staged_changes(repo: TestRepo) {// No staged changes - should still output the prompt (with empty diff)diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex 0f0ebf617..03cb643a2 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -1416,6 +1416,41 @@ fn test_remove_branch_only_unmerged(repo: TestRepo) {));}+/// `diff.relative` limits porcelain `git diff` to the cwd. With it set, running+/// `wt remove` from a subdirectory made a branch whose changes sat outside that+/// subdirectory look integrated, and the branch was deleted.+#[rstest]+fn test_remove_branch_only_unmerged_from_subdirectory_with_diff_relative(repo: TestRepo) {+ repo.run_git(&["switch", "--create", "feature-unmerged"]);+ fs::write(repo.root_path().join("feature.txt"), "new feature").unwrap();+ repo.run_git(&["add", "feature.txt"]);+ repo.run_git(&["commit", "--message", "Add feature"]);+ repo.run_git(&["checkout", "main"]);+ repo.run_git(&["config", "diff.relative", "true"]);+ let subdir = repo.root_path().join("subdir");+ fs::create_dir(&subdir).unwrap();++ let output = make_snapshot_cmd(&repo, "remove", &["feature-unmerged"], Some(&subdir))+ .output()+ .unwrap();++ let branch = repo+ .git_command()+ .args([+ "rev-parse",+ "--verify",+ "--quiet",+ "refs/heads/feature-unmerged",+ ])+ .run()+ .unwrap();+ assert!(+ branch.status.success(),+ "unmerged branch must survive; wt remove said: {}",+ String::from_utf8_lossy(&output.stderr)+ );+}+#[rstest]fn test_remove_branch_only_force_delete(repo: TestRepo) {// Create a branch with a unique commit (not in main)diff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rsindex 8821be5f3..4c65abaac 100644--- a/tests/integration_tests/repository.rs+++ b/tests/integration_tests/repository.rs@@ -1206,6 +1206,53 @@ fn test_sparse_checkout_paths_cached() {assert_eq!(first, &["dir1".to_string()]);}+/// `submodule.<name>.ignore = all` hides gitlink changes even from plumbing,+/// so the diffs `wt` reads override it: a branch that only moves a submodule+/// still has changes.+#[test]+fn test_submodule_bump_survives_submodule_ignore() {+ let repo = TestRepo::new();+ fs::write(+ repo.root_path().join(".gitmodules"),+ "[submodule \"sub\"]\n\tpath = sub\n\turl = ./sub\n",+ )+ .unwrap();+ repo.run_git(&["add", ".gitmodules"]);+ repo.run_git(&["commit", "--message", "add .gitmodules"]);+ let first = repo.git_output(&["rev-parse", "HEAD"]);+ let gitlink = |sha: &str| format!("160000,{sha},sub");+ repo.run_git(&["update-index", "--add", "--cacheinfo", &gitlink(&first)]);+ repo.run_git(&["commit", "--message", "add submodule"]);+ repo.run_git(&["switch", "--create", "feature"]);+ let second = repo.git_output(&["rev-parse", "HEAD"]);+ repo.run_git(&["update-index", "--cacheinfo", &gitlink(&second)]);+ repo.run_git(&["commit", "--message", "bump submodule"]);+ repo.run_git(&["switch", "main"]);+ repo.run_git(&["config", "submodule.sub.ignore", "all"]);+ let main_sha = repo.git_output(&["rev-parse", "main"]);+ let feature_sha = repo.git_output(&["rev-parse", "feature"]);+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();++ assert!(+ repository+ .has_added_changes_by_sha(&feature_sha, &main_sha)+ .unwrap()+ );+ assert_eq!(+ repository.changed_files(&main_sha, &feature_sha).unwrap(),+ ["sub"]+ );+ let stats = repository.branch_diff_stats("main", "feature").unwrap();+ assert_eq!((stats.added, stats.deleted), (1, 1));+ assert!(+ repository+ .prepare_diff(&main_sha, &feature_sha)+ .capture(["--name-only"])+ .unwrap()+ .contains("sub")+ );+}+#[test]fn test_branch_diff_stats_scoped_to_sparse_checkout() {let repo = TestRepo::new();@@ -1240,6 +1287,18 @@ fn test_branch_diff_stats_scoped_to_sparse_checkout() {assert_eq!(stats.added, 2, "sparse: only inside/ additions");assert_eq!(stats.deleted, 1, "sparse: only inside/ deletions");+ // The sparse paths are root-relative, so discovery from a subdirectory+ // counts the same changes.+ let nested_stats = Repository::at(inside.clone())+ .unwrap()+ .branch_diff_stats("main", "feature")+ .unwrap();+ assert_eq!(+ (nested_stats.added, nested_stats.deleted),+ (2, 1),+ "sparse: discovered from inside/"+ );+// Disable sparse checkout — full stats include both inside/ and outside/repo.run_git(&["sparse-checkout", "disable"]);let full_repository = Repository::at(repo.root_path().to_path_buf()).unwrap();