Skip to content

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

perf(picker): share default-branch SHA across BranchDiff preview tasks (#2658)

Maximilian Roos58168f4f48d6
diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rs
index c6c75a160..eb50eabc4 100644
--- a/src/commands/picker/items.rs
+++ b/src/commands/picker/items.rs
@@ -304,11 +304,15 @@ impl WorktreeSkimItem {
/// fallback covers the ahead=0 case, so the preview is correct even
/// before the list-row pipeline has populated counts.
///
- /// The default branch is resolved to its SHA so the disk cache stays
- /// invariant across `git fetch` (which moves the *ref* but not the
- /// captured SHA). When resolution fails, we fall through to the
- /// uncached path with the branch name in the diff range — same git
- /// behavior as before, just no cache write.
+ /// 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.
fn compute_branch_diff_preview(repo: &Repository, item: &ListItem, width: usize) -> String {
let branch = item.branch_name();
let reset = Reset;
@@ -318,10 +322,7 @@ impl WorktreeSkimItem {
);
};
- let base_sha = repo
- .run_command(&["rev-parse", &default_branch])
- .ok()
- .map(|s| s.trim().to_string());
+ 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)
@@ -776,11 +777,7 @@ mod tests {
repo.run_command(&["commit", "-m", "real"]).unwrap();
let item = item_at(&repo, "feature");
- let base_sha = repo
- .run_command(&["rev-parse", "main"])
- .unwrap()
- .trim()
- .to_string();
+ let base_sha = repo.default_branch_sha().unwrap();
let sentinel = "SENTINEL_FROM_CACHE";
super::preview_cache::write_branch_diff(&repo, &base_sha, item.head(), 80, sentinel);
@@ -799,11 +796,7 @@ mod tests {
repo.run_command(&["commit", "-m", "wb"]).unwrap();
let item = item_at(&repo, "feature");
- let base_sha = repo
- .run_command(&["rev-parse", "main"])
- .unwrap()
- .trim()
- .to_string();
+ let base_sha = repo.default_branch_sha().unwrap();
assert!(
super::preview_cache::read_branch_diff(&repo, &base_sha, item.head(), 80).is_none()
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index b6b278b44..f02b226ef 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -414,6 +414,13 @@ pub fn handle_picker(
// first-item preview can run in parallel with `collect::collect` below.
// Wrapped in `Arc` because the progressive handler (running on the
// collect background thread) also calls `spawn_preview`.
+ //
+ // BranchDiff previews resolve the default branch's SHA via
+ // `Repository::default_branch_sha`, which sources it from the
+ // local-branch inventory cached on the shared `RepoCache`. N parallel
+ // preview tasks share one inventory scan instead of each forking
+ // `git rev-parse`. Read-only for the picker session — see the
+ // accessor's docstring for the staleness contract.
let orchestrator = Arc::new(PreviewOrchestrator::new(repo.clone()));
let preview_cache: PreviewCache = Arc::clone(&orchestrator.cache);
diff --git a/src/commands/picker/preview_orchestrator.rs b/src/commands/picker/preview_orchestrator.rs
index 090cfcec4..039e59654 100644
--- a/src/commands/picker/preview_orchestrator.rs
+++ b/src/commands/picker/preview_orchestrator.rs
@@ -34,6 +34,12 @@ pub(super) struct PreviewOrchestrator {
/// so background tasks see a stable repo binding, and so unit tests
/// can inject a `TestRepo`-rooted `Repository` instead of relying on
/// 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.
repo: Repository,
}
diff --git a/src/git/repository/branches.rs b/src/git/repository/branches.rs
index 4137845d5..ae7d067de 100644
--- a/src/git/repository/branches.rs
+++ b/src/git/repository/branches.rs
@@ -125,6 +125,41 @@ impl Repository {
Ok(self.local_branch_inventory()?.get(name))
}
+ /// Commit SHA the default branch points at, sourced from the local-branch
+ /// inventory.
+ ///
+ /// Returns `None` when the default branch can't be determined (see
+ /// [`default_branch`](Self::default_branch)) or when the configured
+ /// default branch isn't a local branch (e.g. stale
+ /// `worktrunk.default-branch` config pointing at a deleted branch). On
+ /// first call, populates the inventory cache via the same single
+ /// `for-each-ref refs/heads/` scan that [`local_branches`] would —
+ /// no extra subprocess.
+ ///
+ /// **Snapshot at first scan; do not use in ref-mutating commands.**
+ /// Same staleness contract as [`local_branches`]: the SHA is captured
+ /// when the inventory is first scanned and never refreshed. Code that
+ /// runs after wt itself has updated `refs/heads/<default>` (e.g.
+ /// `wt merge`'s `git update-ref`) must capture a fresh
+ /// [`crate::git::RefSnapshot`] instead — this accessor will keep
+ /// returning the pre-update SHA. Safe in read-only contexts (the
+ /// interactive picker, list rendering) where wt itself doesn't move
+ /// refs.
+ ///
+ /// Intended for cache keying: when many parallel tasks all need to
+ /// answer "what SHA is the default branch at *right now, for this
+ /// command's worth of work*", this lets them share one inventory scan
+ /// instead of each forking `git rev-parse <name>` independently.
+ ///
+ /// [`local_branches`]: Self::local_branches
+ pub fn default_branch_sha(&self) -> Option<String> {
+ let name = self.default_branch()?;
+ self.local_branch(&name)
+ .ok()
+ .flatten()
+ .map(|b| b.commit_sha.clone())
+ }
+
/// Access the local-branch inventory (entries + name index).
fn local_branch_inventory(&self) -> anyhow::Result<&LocalBranchInventory> {
self.cache
@@ -329,3 +364,63 @@ pub(super) fn parse_remote_branch_line(line: &str) -> Option<RemoteBranch> {
local_name: local_name.to_string(),
})
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::testing::TestRepo;
+
+ #[test]
+ fn default_branch_sha_returns_inventory_sha() {
+ // The accessor must return the same SHA `git rev-parse <default>`
+ // would, sourced from the local-branch inventory rather than its
+ // own subprocess.
+ let test = TestRepo::with_initial_commit();
+ let repo = Repository::at(test.root_path()).unwrap();
+
+ let expected = test.git_output(&["rev-parse", "main"]);
+ assert_eq!(repo.default_branch_sha(), Some(expected));
+ }
+
+ #[test]
+ fn default_branch_sha_none_when_branch_missing_from_inventory() {
+ // Stale `worktrunk.default-branch` config points at a branch that
+ // doesn't exist locally — `default_branch()` returns the configured
+ // name, but `local_branch(name)` finds nothing, so the accessor
+ // returns None. Callers (e.g. the picker's BranchDiff preview)
+ // treat None as "fall through to the uncached path."
+ let test = TestRepo::with_initial_commit();
+ test.run_git(&["config", "worktrunk.default-branch", "ghost"]);
+
+ let repo = Repository::at(test.root_path()).unwrap();
+ assert_eq!(repo.default_branch().as_deref(), Some("ghost"));
+ assert_eq!(repo.default_branch_sha(), None);
+ }
+
+ #[test]
+ fn default_branch_sha_is_snapshot_at_first_scan() {
+ // Documenting the staleness contract: the inventory is scanned once
+ // per `Repository` instance, so a SHA captured before a ref-mutating
+ // operation stays put. Callers in mutating commands must capture a
+ // fresh `RefSnapshot` instead of trusting this accessor across the
+ // mutation.
+ let test = TestRepo::with_initial_commit();
+ let repo = Repository::at(test.root_path()).unwrap();
+
+ let before = repo.default_branch_sha().expect("main resolves");
+
+ // Move main forward outside `repo`'s knowledge.
+ std::fs::write(test.root_path().join("after.txt"), "after\n").unwrap();
+ test.run_git(&["add", "after.txt"]);
+ test.run_git(&["commit", "-m", "advance main"]);
+ let real_after = test.git_output(&["rev-parse", "main"]);
+ assert_ne!(before, real_after, "test setup: main should have moved");
+
+ // Same `repo`: the cached inventory still serves the pre-move SHA.
+ assert_eq!(repo.default_branch_sha(), Some(before));
+
+ // A fresh `Repository::at` scans again and sees the new SHA.
+ let repo2 = Repository::at(test.root_path()).unwrap();
+ assert_eq!(repo2.default_branch_sha(), Some(real_after));
+ }
+}