Skip to content

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

perf(list): batch upstream lookups and prime ref/SHA caches (#2255)

Maximilian Roos3dde31ad59e8
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index abd978c62..7e1fd63b4 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -168,11 +168,8 @@
//! - `AheadBehind` — batch-optimized via single `git for-each-ref %(ahead-behind:main)`
//! (~11ms for all branches); per-branch tasks read the in-memory cache
//! - `CommittedTreesMatch` — single `git rev-parse` resolving both tree SHAs (~1ms)
-//!
-//! ### Cacheable but uncached
-//!
-//! - `Upstream` — `ahead_behind()` against the tracking branch; same SHA-pair
-//! pattern as `sha_cache`, just not wired up yet
+//! - `Upstream` — upstream names batch-fetched via single `git for-each-ref
+//! %(upstream:short)`; per-branch tasks read the in-memory cache
//!
//! ### Cached via tree SHA
//!
@@ -989,6 +986,11 @@ pub fn collect(
// `AheadBehindTask` hits the cache instead of spawning its own
// `git rev-list --count`. One git call replaces N.
//
+ // Note: `resolved_refs` and `commit_shas` are already primed by
+ // `list_local_branches()` (called during pre-skeleton phase).
+ // Upstream tracking branches are lazily loaded on first `Branch::upstream()`
+ // call via `OnceCell`.
+ //
// On git < 2.36 (no `%(ahead-behind:)` support) or if default_branch is
// unknown, skip the batch — individual tasks fall back to direct calls.
if let Some(ref db) = default_branch {
diff --git a/src/git/repository/branch.rs b/src/git/repository/branch.rs
index 02c331c46..98e5be75a 100644
--- a/src/git/repository/branch.rs
+++ b/src/git/repository/branch.rs
@@ -96,17 +96,12 @@ impl<'a> Branch<'a> {
///
/// [1]: https://git-scm.com/docs/gitrevisions#Documentation/gitrevisions.txt-emltaboranchgtemuaboranchgtupaboranchgtupstream
pub fn upstream(&self) -> anyhow::Result<Option<String>> {
- let result =
- self.repo
- .run_command(&["rev-parse", "--abbrev-ref", &format!("{}@{{u}}", self.name)]);
-
- match result {
- Ok(upstream) => {
- let trimmed = upstream.trim();
- Ok((!trimmed.is_empty()).then(|| trimmed.to_string()))
- }
- Err(_) => Ok(None), // No upstream configured
- }
+ let upstreams = self
+ .repo
+ .cache
+ .upstreams
+ .get_or_try_init(|| self.repo.fetch_all_upstreams())?;
+ Ok(upstreams.get(&self.name).cloned().unwrap_or(None))
}
/// Unset the upstream tracking branch for this branch.
diff --git a/src/git/repository/branches.rs b/src/git/repository/branches.rs
index 6cd19925e..46ff56e55 100644
--- a/src/git/repository/branches.rs
+++ b/src/git/repository/branches.rs
@@ -42,6 +42,10 @@ impl Repository {
/// List all local branches with their HEAD commit SHA.
/// Returns a vector of (branch_name, commit_sha) tuples.
+ ///
+ /// As a side effect, primes `resolved_refs` and `commit_shas` caches so
+ /// later `resolve_preferring_branch()` and `rev_parse_commit()` calls hit
+ /// the cache instead of spawning per-branch `git rev-parse` commands.
pub fn list_local_branches(&self) -> anyhow::Result<Vec<(String, String)>> {
let output = self.run_command(&[
"for-each-ref",
@@ -53,6 +57,14 @@ impl Repository {
.lines()
.filter_map(|line| {
let (branch, sha) = line.split_once(' ')?;
+ let qualified = format!("refs/heads/{branch}");
+ self.cache
+ .resolved_refs
+ .insert(branch.to_string(), qualified.clone());
+ self.cache.commit_shas.insert(qualified, sha.to_string());
+ self.cache
+ .commit_shas
+ .insert(branch.to_string(), sha.to_string());
Some((branch.to_string(), sha.to_string()))
})
.collect();
@@ -104,6 +116,32 @@ impl Repository {
Ok(upstreams)
}
+ /// Fetch all upstream tracking branches in a single `git for-each-ref` call.
+ ///
+ /// Returns a map from local branch name to upstream ref (or None if no
+ /// upstream is configured). Called lazily via `OnceCell` on first
+ /// `Branch::upstream()` access.
+ pub(super) fn fetch_all_upstreams(&self) -> anyhow::Result<HashMap<String, Option<String>>> {
+ let output = self.run_command(&[
+ "for-each-ref",
+ "--format=%(refname:lstrip=2)\t%(upstream:short)",
+ "refs/heads/",
+ ])?;
+
+ Ok(output
+ .lines()
+ .filter_map(|line| {
+ let (branch, upstream) = line.split_once('\t')?;
+ let value = if upstream.is_empty() {
+ None
+ } else {
+ Some(upstream.to_string())
+ };
+ Some((branch.to_string(), value))
+ })
+ .collect())
+ }
+
/// List remote branches that aren't tracked by any local branch.
///
/// Returns (branch_name, commit_sha) pairs for remote branches that have no
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index d8fd31413..c10865594 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -62,6 +62,7 @@
//! The picker also maintains a `PreviewCache` (`Arc<DashMap>` in `commands/picker/items.rs`)
//! for rendered preview output, scoped to a single picker session.
+use std::collections::HashMap;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::Stdio;
@@ -257,6 +258,10 @@ pub(super) struct RepoCache {
/// Used by `rev_parse_commit()` to key the persistent `sha_cache` by SHA.
pub(super) commit_shas: DashMap<String, String>,
+ /// Upstream tracking branch cache: local branch -> upstream (e.g., "origin/main").
+ /// None means "no upstream configured". Lazily loaded on first access via
+ /// `Branch::upstream()` → `fetch_all_upstreams()`.
+ pub(super) upstreams: OnceCell<HashMap<String, Option<String>>>,
/// Commit details cache: commit SHA -> (timestamp, subject).
/// Multiple items sharing the same HEAD commit (e.g., worktrees on main)
/// would otherwise each spawn a `git log -1` for the same SHA.