Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(switch): diff previews against the upstream-aware comparison base (#3305)

Maximilian Roosafb3f5e2283b
diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rs
index 3b610b654..a61bfdd61 100644
--- a/src/commands/list/collect/tasks.rs
+++ b/src/commands/list/collect/tasks.rs
@@ -9,7 +9,9 @@ use std::time::Duration;
use std::sync::Arc;
use anyhow::Context;
-use worktrunk::git::{ErrorExt, IntegrationTargets, LineDiff, RefSnapshot, Repository};
+use worktrunk::git::{
+ ErrorExt, IntegrationTargets, LineDiff, RefSnapshot, Repository, select_comparison_base,
+};
use super::super::ci_status::{CiBranchName, PrStatus};
use super::super::model::{
@@ -141,14 +143,16 @@ impl TaskContext {
/// through `primary` keeps them consistent with the integration symbol
/// and immune to a stale local default.
///
- /// Falls back to the raw default branch name when integration targets
- /// could not be resolved (snapshot capture failed) so the columns still
- /// render in that degraded mode.
+ /// Resolved via the shared `select_comparison_base` rule — the same one the
+ /// diff/summary preview panes use — so the column number and the pane can't
+ /// drift onto different bases. Falls back to the raw default branch name
+ /// when integration targets could not be resolved (snapshot capture failed)
+ /// so the columns still render in that degraded mode.
pub(super) fn comparison_base(&self) -> Option<&str> {
- self.integration_targets
- .as_ref()
- .map(|t| t.primary.as_str())
- .or(self.default_branch.as_deref())
+ select_comparison_base(
+ self.integration_targets.as_ref(),
+ self.default_branch.as_deref(),
+ )
}
/// Get the integration targets resolved for this list invocation.
diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rs
index 562cf8093..7ba5f7560 100644
--- a/src/commands/picker/items.rs
+++ b/src/commands/picker/items.rs
@@ -604,13 +604,9 @@ pub(super) struct LocalContent {
/// against the **upstream-aware** comparison base
/// (`TaskContext::comparison_base` — the upstream ref when the local default
/// lags it), so a stale fork default doesn't inflate it. The branch-diff and
- /// summary panes instead diff the **local** default (`default_branch_sha()`,
- /// `compute_combined_diff`'s `repo.default_branch()`); the two bases coincide
- /// unless the local default lags upstream, where this can read `ahead = 0`
- /// while the pane (vs the stale local default) still shows a diff — dimming
- /// the number over a non-empty pane. That fork-only skew is shared by the
- /// branch-diff and summary tabs and is purely cosmetic (navigation and the
- /// pane itself are unaffected).
+ /// summary panes diff against the **same** base
+ /// (`Repository::branch_diff_spec`), so the dimmed number and the pane agree
+ /// even on a fork whose local default lags upstream.
branch_diff: Option<bool>,
/// `upstream`: the branch is ahead of or behind its tracking ref. Combined
/// with the synchronous `has_upstream` floor (no tracking ref dims the tab
@@ -670,12 +666,10 @@ impl LocalTabs {
/// synchronous `has_upstream` floor (no tracking ref → dim with no loading
/// window). `summary` requires the process-wide `[commit.generation]` flag
/// *and* something to summarize: its pane is generated from the combined diff
- /// (`crate::summary::compute_combined_diff` = commits ahead of the default +
- /// working-tree changes), so it reuses the `branch_diff` and `working_tree`
- /// signals that gate tabs 3 and 1 — dimming in concert with them once both
- /// are known empty, not only when summaries are disabled. Like tab 3, it
- /// inherits `branch_diff`'s fork-only base skew (see the
- /// [`LocalContent::branch_diff`] field doc).
+ /// (`crate::summary::compute_combined_diff` = commits ahead of the comparison
+ /// base + working-tree changes), so it reuses the `branch_diff` and
+ /// `working_tree` signals that gate tabs 3 and 1 — dimming in concert with
+ /// them once both are known empty, not only when summaries are disabled.
fn worktree(content: LocalContent, has_upstream: bool, summaries_enabled: bool) -> Self {
let working_tree = content.working_tree.unwrap_or(true);
let branch_diff = content.branch_diff.unwrap_or(true);
@@ -1281,54 +1275,47 @@ impl PickerRow {
)
}
- /// Compute Tab 3: Branch diff preview (line diffs in commits ahead of default branch)
+ /// Compute Tab 3: Branch diff preview (line diffs vs the comparison base)
///
/// Independent of `item.counts` — `compute_diff_preview`'s empty-diff
/// fallback covers the ahead=0 case, so the preview is correct even
/// before the list-row pipeline has populated counts.
///
- /// The default branch's SHA comes from [`Repository::default_branch_sha`],
- /// which sources it from the already-warmed local-branch inventory. N
- /// parallel preview tasks all share one inventory scan instead of each
- /// forking `git rev-parse`. The SHA also keeps the disk cache invariant
- /// across `git fetch` (which moves the *ref* but not the captured SHA).
- /// When the SHA isn't available (no default branch, or stale config
- /// pointing at a deleted branch), we fall through to the uncached path
- /// with the branch name in the diff range — same git behavior as
- /// before, just no cache read/write.
+ /// The base comes from [`Repository::branch_diff_spec`], which measures
+ /// against the **upstream-aware comparison base** — the same ref the
+ /// ahead/behind and branch-diff columns use — so a stale fork default
+ /// can't show upstream commits as this branch's changes. Its resolved SHA
+ /// keys the disk cache (stable across `git fetch`, which moves the *ref*
+ /// but not the captured SHA), and orphan branches diff their full content
+ /// against the empty tree.
fn compute_branch_diff_preview(repo: &Repository, item: &ListItem, width: usize) -> String {
let branch = item.branch_name();
let reset = Reset;
- let Some(default_branch) = repo.default_branch() else {
+ let Some(spec) = repo.branch_diff_spec(item.head()) else {
return cformat!(
"{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no commits ahead of main\n"
);
};
- let base_sha = repo.default_branch_sha();
-
- if let Some(ref base) = base_sha
- && let Some(cached) = preview_cache::read_branch_diff(repo, base, item.head(), width)
+ if let Some(cached) =
+ preview_cache::read_branch_diff(repo, &spec.cache_sha, item.head(), width)
{
return cached;
}
- // Use the resolved SHA in the diff range when available so the
- // cache key and the diff agree on which commit was the base.
- let base_ref = base_sha.as_deref().unwrap_or(&default_branch);
- let merge_base = format!("{base_ref}...{}", item.head());
+ let mut diff_args = vec!["diff"];
+ diff_args.extend(spec.revs.iter().map(String::as_str));
+ let base_name = &spec.base_name;
let result = compute_diff_preview(
repo,
- &["diff", &merge_base],
+ &diff_args,
&cformat!(
- "{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no file changes vs <bold>{default_branch}</>{reset}"
+ "{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no file changes vs <bold>{base_name}</>{reset}"
),
width,
);
- if let Some(ref base) = base_sha {
- preview_cache::write_branch_diff(repo, base, item.head(), width, &result);
- }
+ preview_cache::write_branch_diff(repo, &spec.cache_sha, item.head(), width, &result);
result
}
@@ -2629,6 +2616,62 @@ mod tests {
);
}
+ #[test]
+ fn branch_diff_orphan_shows_full_content() {
+ // An orphan branch shares no history with the comparison base, so its
+ // three-dot diff has no merge base. The pane must fall back to the
+ // orphan's full content (vs the empty tree) rather than "no file
+ // changes" — matching the dim signal, which keeps tab 3 available for
+ // orphans.
+ let (t, repo) = repo_with_main();
+ repo.run_command(&["checkout", "--orphan", "orphan-feature"])
+ .unwrap();
+ repo.run_command(&["rm", "-rf", "."]).unwrap();
+ std::fs::write(t.path().join("orphan.txt"), "orphan\n").unwrap();
+ repo.run_command(&["add", "orphan.txt"]).unwrap();
+ repo.run_command(&["commit", "-m", "orphan root"]).unwrap();
+ let item = item_at(&repo, "orphan-feature");
+ let output = PickerRow::compute_branch_diff_preview(&repo, &item, 80);
+ assert!(
+ output.contains("orphan.txt"),
+ "orphan pane should show full content, got: {output:?}"
+ );
+ }
+
+ #[test]
+ fn branch_diff_uses_upstream_aware_base() {
+ // When the local default lags its upstream, the pane must diff against
+ // the upstream tip (the comparison base), not the stale local default —
+ // otherwise it shows upstream commits as this branch's own changes.
+ let (t, repo) = repo_with_main();
+ // origin-main: one commit ahead of main, with main's tracking ref
+ // pointed at it so local main lags by that commit.
+ repo.run_command(&["branch", "origin-main"]).unwrap();
+ repo.run_command(&["checkout", "origin-main"]).unwrap();
+ std::fs::write(t.path().join("upstream.txt"), "from upstream\n").unwrap();
+ repo.run_command(&["add", "upstream.txt"]).unwrap();
+ repo.run_command(&["commit", "-m", "upstream commit"])
+ .unwrap();
+ // feature branches off the upstream tip and adds its own commit.
+ repo.run_command(&["checkout", "-b", "feature"]).unwrap();
+ std::fs::write(t.path().join("feature.txt"), "feature work\n").unwrap();
+ repo.run_command(&["add", "feature.txt"]).unwrap();
+ repo.run_command(&["commit", "-m", "feature commit"])
+ .unwrap();
+ repo.run_command(&["branch", "--set-upstream-to=origin-main", "main"])
+ .unwrap();
+ let item = item_at(&repo, "feature");
+ let output = PickerRow::compute_branch_diff_preview(&repo, &item, 80);
+ assert!(
+ output.contains("feature.txt"),
+ "expected feature.txt, got: {output:?}"
+ );
+ assert!(
+ !output.contains("upstream.txt"),
+ "must diff vs the upstream-aware base, not the stale local default; got: {output:?}"
+ );
+ }
+
#[test]
fn branch_diff_cache_short_circuits_recompute() {
// Pre-populate the disk cache with a sentinel value, then call
diff --git a/src/commands/picker/preview_orchestrator.rs b/src/commands/picker/preview_orchestrator.rs
index fbef09e56..996390ab3 100644
--- a/src/commands/picker/preview_orchestrator.rs
+++ b/src/commands/picker/preview_orchestrator.rs
@@ -164,10 +164,10 @@ pub(super) struct PreviewOrchestrator {
/// process CWD.
///
/// Cloned into each spawned task so they share the underlying
- /// `Arc<RepoCache>` — including the local-branch inventory that
- /// [`Repository::default_branch_sha`] reads from. That's how the
- /// BranchDiff preview avoids forking `git rev-parse` per item:
- /// the inventory's single `for-each-ref` scan serves every task.
+ /// `Arc<RepoCache>` — including the memoized comparison base that
+ /// [`Repository::branch_diff_spec`] resolves from a single `for-each-ref`
+ /// scan. That shared cache is how the BranchDiff preview avoids
+ /// re-scanning refs per item.
repo: Repository,
}
diff --git a/src/commands/picker/summary.rs b/src/commands/picker/summary.rs
index fb33ae6ae..15e119bae 100644
--- a/src/commands/picker/summary.rs
+++ b/src/commands/picker/summary.rs
@@ -543,6 +543,91 @@ mod tests {
assert!(combined.diff.contains("wip.txt"));
}
+ #[test]
+ fn test_compute_combined_diff_orphan_branch_shows_full_content() {
+ use crate::summary::compute_combined_diff;
+ // An orphan branch shares no history with the default, so a three-dot
+ // diff has no merge base — the branch diff must fall back to the
+ // orphan's full content (vs the empty tree) instead of summarizing
+ // nothing.
+ let (t, _repo, _) = temp_repo_configured();
+ t.run_git(&["checkout", "--orphan", "orphan-feature"]);
+ t.run_git(&["rm", "-rf", "."]);
+ fs::write(t.path().join("orphan.txt"), "orphan content\n").unwrap();
+ t.repo.run_command(&["add", "orphan.txt"]).unwrap();
+ t.repo
+ .run_command(&["commit", "-m", "orphan root"])
+ .unwrap();
+ let head = t
+ .repo
+ .run_command(&["rev-parse", "HEAD"])
+ .unwrap()
+ .trim()
+ .to_string();
+ let repo = Repository::at(t.path()).unwrap();
+
+ let result = compute_combined_diff("orphan-feature", &head, Some(t.path()), &repo);
+ let combined = result.expect("orphan branch with content must summarize");
+ assert!(
+ combined.diff.contains("orphan.txt"),
+ "diff: {}",
+ combined.diff
+ );
+ assert!(
+ combined.stat.contains("orphan.txt"),
+ "stat: {}",
+ combined.stat
+ );
+ }
+
+ #[test]
+ fn test_compute_combined_diff_uses_upstream_aware_base() {
+ use crate::summary::compute_combined_diff;
+ // When the local default branch lags its upstream, the summary must
+ // diff against the upstream tip (the comparison base), not the stale
+ // local default — otherwise it describes upstream commits as this
+ // branch's own changes.
+ let (t, _repo, _) = temp_repo_configured(); // main at C1
+ // A local "upstream" branch one commit ahead of main, with main's
+ // tracking ref pointed at it so local main lags by that commit.
+ t.run_git(&["branch", "origin-main"]);
+ t.run_git(&["checkout", "origin-main"]);
+ fs::write(t.path().join("upstream.txt"), "from upstream\n").unwrap();
+ t.repo.run_command(&["add", "upstream.txt"]).unwrap();
+ t.repo
+ .run_command(&["commit", "-m", "upstream commit"])
+ .unwrap(); // C2
+ // feature branches off the upstream tip (C2) and adds its own commit.
+ t.run_git(&["checkout", "-b", "feature"]);
+ fs::write(t.path().join("feature.txt"), "feature work\n").unwrap();
+ t.repo.run_command(&["add", "feature.txt"]).unwrap();
+ t.repo
+ .run_command(&["commit", "-m", "feature commit"])
+ .unwrap();
+ // main stays at C1 but tracks origin-main (now C2) → main lags upstream.
+ t.run_git(&["branch", "--set-upstream-to=origin-main", "main"]);
+ let head = t
+ .repo
+ .run_command(&["rev-parse", "feature"])
+ .unwrap()
+ .trim()
+ .to_string();
+ let repo = Repository::at(t.path()).unwrap();
+
+ let combined = compute_combined_diff("feature", &head, Some(t.path()), &repo)
+ .expect("feature has changes to summarize");
+ assert!(
+ combined.diff.contains("feature.txt"),
+ "diff: {}",
+ combined.diff
+ );
+ assert!(
+ !combined.diff.contains("upstream.txt"),
+ "must diff vs the upstream-aware base, not the stale local default; diff: {}",
+ combined.diff
+ );
+ }
+
#[test]
fn test_generate_summary_calls_llm() {
let (t, repo, head) = temp_repo_with_feature();
diff --git a/src/git/mod.rs b/src/git/mod.rs
index df75f6339..ab035fcd8 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -76,8 +76,8 @@ pub use remove::{
};
pub use repository::sha_cache;
pub use repository::{
- Branch, CommitMessageDetail, IntegrationTargets, RefSnapshot, Repository, ResolvedWorktree,
- TempIndex, WorkingTree, set_base_path,
+ Branch, BranchDiffSpec, CommitMessageDetail, IntegrationTargets, RefSnapshot, Repository,
+ ResolvedWorktree, TempIndex, WorkingTree, select_comparison_base, set_base_path,
};
pub use url::parse_owner_repo;
pub use url::{GitRemoteUrl, GitRepoInfo, GitRepoProvider};
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rs
index bece8531f..dcea759f2 100644
--- a/src/git/repository/integration.rs
+++ b/src/git/repository/integration.rs
@@ -24,6 +24,65 @@ pub struct IntegrationTargets {
pub secondary: Option<String>,
}
+/// Select the comparison-base name from resolved integration targets: the
+/// primary target ([`IntegrationTargets::primary`]), falling back to the raw
+/// default branch name when targets couldn't be resolved (snapshot capture
+/// failed / no upstream relationship known).
+///
+/// The single home for the "primary-else-default" rule shared by the `wt list`
+/// comparison columns (the list collector's `comparison_base`) and the
+/// diff/summary preview panes ([`Repository::branch_diff_spec`]) — so the
+/// dimmed column number and the pane can't drift onto different bases.
+pub fn select_comparison_base<'a>(
+ targets: Option<&'a IntegrationTargets>,
+ default_branch: Option<&'a str>,
+) -> Option<&'a str> {
+ 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";
+
+/// The upstream-aware base a branch's content is measured against in the
+/// diff/summary preview panes — [`IntegrationTargets::primary`], resolved once
+/// per repo. Carries both the display name (for "no file changes vs X"
+/// messages) and its resolved SHA (for disk-cache keying).
+#[derive(Debug, Clone)]
+pub(in crate::git) struct ComparisonBase {
+ /// Display name of the base (e.g. `main`, or `origin/main` when the local
+ /// default lags its upstream).
+ pub name: String,
+ /// The base's resolved commit SHA. `resolve_comparison_base` returns `None`
+ /// rather than a base whose SHA won't resolve, so this is always present.
+ pub sha: String,
+}
+
+/// How a branch's content is diffed against the mainline for the diff and
+/// summary preview panes.
+///
+/// The base is the **upstream-aware comparison base** — the same ref the
+/// ahead/behind and branch-diff columns measure against — so a stale fork
+/// default can't make the panes describe upstream commits as the
+/// branch's own changes. Orphan branches (no merge base with the base) fall
+/// back to a full diff against the empty tree, so a root-style branch shows its
+/// content instead of "no file changes". Built by
+/// [`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>,
+ /// 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
+ /// SHA, or the empty-tree SHA for an orphan.
+ pub cache_sha: String,
+}
+
/// Result of the combined merge-tree + patch-id integration probe.
///
/// Encapsulates the two-step sequence: first try `merge-tree --write-tree` to
@@ -520,6 +579,67 @@ impl Repository {
Some(IntegrationTargets { primary, secondary })
}
+ /// The upstream-aware comparison base for the diff/summary preview panes,
+ /// resolved once and memoized (the base is repo-wide, like the default
+ /// branch). Returns `None` when no default branch can be determined.
+ ///
+ /// Selects the base via the shared [`select_comparison_base`] rule
+ /// ([`IntegrationTargets::primary`] else the raw local default), so the
+ /// preview panes and the `wt list` columns can't pick different bases.
+ /// Captures a [`RefSnapshot`] on first call; safe in the read-only preview
+ /// contexts that use it (wt doesn't move refs there). Fully local — no
+ /// network.
+ fn comparison_base(&self) -> Option<&ComparisonBase> {
+ self.cache
+ .comparison_base
+ .get_or_init(|| self.resolve_comparison_base())
+ .as_ref()
+ }
+
+ fn resolve_comparison_base(&self) -> Option<ComparisonBase> {
+ // No default branch → no comparison base; skip the ref scan entirely.
+ self.default_branch()?;
+ let snapshot = self.capture_refs().ok()?;
+ let targets = self.integration_targets(&snapshot);
+ let default_branch = self.default_branch();
+ let name = select_comparison_base(targets.as_ref(), default_branch.as_deref())?.to_string();
+ // No usable base if the name won't resolve (a stale
+ // `worktrunk.default-branch` pointing at a deleted branch) — return
+ // `None` so the panes skip the branch diff rather than render a
+ // guaranteed-empty range against a missing ref.
+ let sha = snapshot_resolve(self, &snapshot, &name).ok()?;
+ Some(ComparisonBase { name, sha })
+ }
+
+ /// 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
+ /// default branch, or its ref won't resolve).
+ pub fn branch_diff_spec(&self, head: &str) -> Option<BranchDiffSpec> {
+ 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, cache_sha) = if matches!(self.merge_base_by_sha(base_sha, head), Ok(None)) {
+ (
+ vec![EMPTY_TREE_SHA.to_string(), head.to_string()],
+ EMPTY_TREE_SHA.to_string(),
+ )
+ } else {
+ (vec![format!("{base_sha}...{head}")], base_sha.to_string())
+ };
+
+ Some(BranchDiffSpec {
+ revs,
+ base_name: base.name.clone(),
+ cache_sha,
+ })
+ }
+
/// Resolve a tree spec (e.g. `"refs/heads/main^{tree}"`) to its tree SHA.
/// Uncached — tree resolution is cheap (~1 ms) and stale-prone if memoized
/// against a moving ref name. When the input is a commit SHA, prefer
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 83e3ef0ef..79384d0b2 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -139,7 +139,7 @@ mod worktrees;
// Re-export WorkingTree, Branch, IntegrationTargets, and RefSnapshot
pub use branch::Branch;
pub use diff::CommitMessageDetail;
-pub use integration::IntegrationTargets;
+pub use integration::{BranchDiffSpec, IntegrationTargets, select_comparison_base};
pub use ref_snapshot::RefSnapshot;
pub(super) use working_tree::path_to_logging_context;
pub use working_tree::{TempIndex, WorkingTree};
@@ -215,6 +215,11 @@ pub(super) struct RepoCache {
pub(super) repo_path: OnceCell<PathBuf>,
/// Default branch (main, master, etc.)
pub(super) default_branch: OnceCell<Option<String>>,
+ /// Upstream-aware comparison base for the diff/summary preview panes —
+ /// [`integration::IntegrationTargets::primary`], resolved once. Repo-wide
+ /// like `default_branch`; captures a [`RefSnapshot`] on first access via
+ /// [`Repository::branch_diff_spec`]. `None` when no default branch resolves.
+ pub(super) comparison_base: OnceCell<Option<integration::ComparisonBase>>,
/// Project identifier derived from remote URL
pub(super) project_identifier: OnceCell<String>,
/// Project config (loaded from .config/wt.toml in main worktree)
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index 79486a863..04448ce12 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -951,8 +951,7 @@ fn build_worktree_config_bare_layout() -> (tempfile::TempDir, std::path::PathBuf
"commit-tree",
"-m",
"init",
- // Empty tree SHA.
- "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
+ super::integration::EMPTY_TREE_SHA,
])
.run()
.unwrap();
diff --git a/src/summary.rs b/src/summary.rs
index 010b2ef0e..c440c6481 100644
--- a/src/summary.rs
+++ b/src/summary.rs
@@ -218,33 +218,39 @@ pub(crate) fn hash_diff(diff: &str) -> String {
/// Compute the combined diff for a branch (branch diff + working tree diff).
///
-/// Returns None if there's nothing to summarize (default branch with no changes,
-/// or no default branch known and no working tree diff available).
+/// The branch diff measures against the upstream-aware comparison base (see
+/// [`Repository::branch_diff_spec`]) — the same ref the `wt list` columns use,
+/// not the raw local default — so a stale fork default can't describe upstream
+/// commits as the branch's own changes; orphan branches contribute their full
+/// content rather than nothing. Returns `None` if there's nothing to summarize
+/// (default branch with no changes, or no comparison base and no working tree
+/// diff).
pub(crate) fn compute_combined_diff(
branch: &str,
head: &str,
worktree_path: Option<&Path>,
repo: &Repository,
) -> Option<CombinedDiff> {
- let default_branch = repo.default_branch();
-
let mut diff = String::new();
let mut stat = String::new();
- // Branch diff: what's ahead of default branch (skipped if default branch unknown)
- if let Some(ref default_branch) = default_branch {
- let is_default_branch = branch == *default_branch;
- if !is_default_branch {
- let merge_base = format!("{}...{}", default_branch, head);
- if let Ok(branch_stat) =
- repo.run_command(&["diff", "--stat", "--end-of-options", &merge_base])
- {
- stat.push_str(&branch_stat);
- }
- if let Ok(branch_diff) = repo.run_command(&["diff", "--end-of-options", &merge_base]) {
- diff.push_str(&branch_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.
+ let run_branch_diff = |opts: &[&str], out: &mut String| {
+ let mut args = vec!["diff"];
+ args.extend_from_slice(opts);
+ args.push("--end-of-options");
+ args.extend(spec.revs.iter().map(String::as_str));
+ if let Ok(text) = repo.run_command(&args) {
+ out.push_str(&text);
}
- }
+ };
+ run_branch_diff(&["--stat"], &mut stat);
+ run_branch_diff(&[], &mut diff);
}
// Working tree diff: uncommitted changes