Skip to content

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

refactor(repo): consolidate branch-enumeration scans into a single inventory (#2368)

Maximilian Roos5fe93934a2c9
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 6a7e6f900..61345ef49 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -211,7 +211,7 @@ pub fn build_hook_context(
map.insert("remote_url".into(), url);
}
if let Some(branch) = ctx.branch
- && let Ok(Some(upstream)) = ctx.repo.branch(branch).upstream_single()
+ && let Ok(Some(upstream)) = ctx.repo.branch(branch).upstream()
{
map.insert("upstream".into(), upstream);
}
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index 771d5c568..c119294ef 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -217,7 +217,7 @@ use crossbeam_channel as chan;
use dunce::canonicalize;
use once_cell::sync::OnceCell;
use rayon::prelude::*;
-use worktrunk::git::{Repository, WorktreeInfo};
+use worktrunk::git::{LocalBranch, Repository, WorktreeInfo};
use worktrunk::styling::{
INFO_SYMBOL, eprintln, format_with_gutter, hint_message, warning_message,
};
@@ -505,15 +505,15 @@ pub fn collect(
// - url_template: independent (loads project config via show-toplevel)
// - project_identifier: independent (git config for remote URL; warms cache
// for is_worktree_at_expected_path and config resolution)
- // - local_branches: independent (for-each-ref, but filtering needs worktrees)
- // - remote_branches: independent (for-each-ref)
+ // - local_branches: independent (one `for-each-ref refs/heads/`; cached on
+ // `RepoCache` so later consumers read it without re-scanning)
+ // - remote_branches: independent (one `for-each-ref refs/remotes/`; cached
+ // on `RepoCache`)
//
// After this scope completes, we have all raw data and can do CPU-only work.
let worktrees_cell: OnceCell<anyhow::Result<Vec<WorktreeInfo>>> = OnceCell::new();
let default_branch_cell: OnceCell<Option<String>> = OnceCell::new();
let url_template_cell: OnceCell<Option<String>> = OnceCell::new();
- let local_branches_cell: OnceCell<anyhow::Result<Vec<(String, String)>>> = OnceCell::new();
- let remote_branches_cell: OnceCell<anyhow::Result<Vec<(String, String)>>> = OnceCell::new();
rayon::scope(|s| {
s.spawn(|_| {
@@ -537,12 +537,15 @@ pub fn collect(
});
s.spawn(|_| {
if fetch_branches {
- let _ = local_branches_cell.set(repo.list_local_branches());
+ // Prime the local-branch inventory on `RepoCache`; consumers
+ // below read it through `repo.local_branches()`.
+ let _ = repo.local_branches();
}
});
s.spawn(|_| {
if fetch_remotes {
- let _ = remote_branches_cell.set(repo.list_untracked_remote_branches());
+ // Prime the remote-branch inventory on `RepoCache`.
+ let _ = repo.remote_branches();
}
});
});
@@ -629,37 +632,33 @@ pub fn collect(
// the persisted value, now trusted without validation on the hot path.
// Cross-check against the enumerated branch set and surface a warning
// if it's been deleted externally. When `show_branches` is off but a
- // persisted default is set and isn't a worktree branch, fetch the
- // local branch list anyway (one `for-each-ref` fork) so the warning
- // fires on plain `wt list` too — otherwise downstream tasks resolve
- // against the stale ref and emit a cascade of "ambiguous argument"
- // noise instead of one clean warning.
+ // persisted default is set and isn't a worktree branch, scan the local
+ // branch inventory anyway (one `for-each-ref` fork, cached afterwards)
+ // so the warning fires on plain `wt list` too — otherwise downstream
+ // tasks resolve against the stale ref and emit a cascade of "ambiguous
+ // argument" noise instead of one clean warning.
let worktree_branches = worktree_branch_set(&worktrees);
let needs_stale_check = default_branch
.as_deref()
.is_some_and(|b| !worktree_branches.contains(b));
- let fetched_local: Option<Vec<(String, String)>> = if show_branches {
- Some(match local_branches_cell.into_inner() {
- Some(result) => result?,
- None => repo.list_local_branches()?,
- })
- } else if needs_stale_check {
- Some(repo.list_local_branches()?)
+ let fetched_local: Option<&[LocalBranch]> = if show_branches || needs_stale_check {
+ Some(repo.local_branches()?)
} else {
None
};
let warn_stale_default = needs_stale_check
- && fetched_local.as_ref().is_some_and(|all| {
+ && fetched_local.is_some_and(|all| {
!all.iter()
- .any(|(n, _)| Some(n.as_str()) == default_branch.as_deref())
+ .any(|b| Some(b.name.as_str()) == default_branch.as_deref())
});
// Filter local branches to those without worktrees (CPU-only, no git commands)
let branches_without_worktrees: Vec<(String, String)> = if show_branches {
- let all_local = fetched_local.unwrap_or_default();
- all_local
- .into_iter()
- .filter(|(name, _)| !worktree_branches.contains(name.as_str()))
+ fetched_local
+ .unwrap_or(&[])
+ .iter()
+ .filter(|b| !worktree_branches.contains(b.name.as_str()))
+ .map(|b| (b.name.clone(), b.commit_sha.clone()))
.collect()
} else {
Vec::new()
@@ -690,13 +689,19 @@ pub fn collect(
} else {
default_branch
};
- let remote_branches = if show_remotes {
- if let Some(result) = remote_branches_cell.into_inner() {
- result?
- } else {
- // Config-triggered (not fetched speculatively) — fetch now
- repo.list_untracked_remote_branches()?
- }
+ // Remote branches that aren't tracked by any local branch. Filtering
+ // happens over the cached inventories — no extra subprocess.
+ let remote_branches: Vec<(String, String)> = if show_remotes {
+ let tracked: HashSet<&str> = repo
+ .local_branches()?
+ .iter()
+ .filter_map(|b| b.upstream_short.as_deref())
+ .collect();
+ repo.remote_branches()?
+ .iter()
+ .filter(|r| !tracked.contains(r.short_name.as_str()))
+ .map(|r| (r.short_name.clone(), r.commit_sha.clone()))
+ .collect()
} else {
Vec::new()
};
@@ -1052,10 +1057,9 @@ 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`.
+ // Note: `resolved_refs`, `commit_shas`, and upstream tracking info are
+ // already primed by `local_branches()` (called during pre-skeleton
+ // phase), so `Branch::upstream()` is an in-memory lookup from here on.
//
// On git < 2.36 (no `%(ahead-behind:)` support) or if default_branch is
// unknown, skip the batch — individual tasks fall back to direct calls.
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index 2b76aa956..e15c613dc 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -26,7 +26,7 @@
//! `git diff HEAD` for the current worktree on the preview pool. That bg
//! work overlaps with everything below.
//! 4. Computes `num_items_estimate` — `list_worktrees` plus (conditionally)
-//! `list_local_branches` / `list_remote_branches`, capped at
+//! `local_branches` / `remote_branches`, capped at
//! `MAX_VISIBLE_ITEMS`. Only used to size skim's `preview_window`.
//! 5. Builds `SkimOptions` (immutable after this — which is why steps 1-4 have
//! to run first).
@@ -80,9 +80,12 @@
//!
//! # TODO(picker-perf): dedupe git calls
//!
-//! `num_items_estimate` and `collect::collect` each call `list_worktrees` and
-//! `list_local_branches`. Pre-seed collect's OnceCells from the main-thread
-//! fetch to save one of each on the bg thread's critical path toward skeleton.
+//! `num_items_estimate` and `collect::collect` each call `list_worktrees`.
+//! Pre-seed collect's OnceCells from the main-thread fetch to save one
+//! `git worktree list` on the bg thread's critical path toward skeleton.
+//! (The branch inventory is already shared via `Repository::cache`, so
+//! calling `local_branches()` / `remote_branches()` from both the main
+//! and bg threads runs the scan at most once.)
mod items;
mod log_formatter;
@@ -452,11 +455,11 @@ pub fn handle_picker(
// Local branches are a superset of worktree branches (each
// linked worktree normally has one), so take the max rather
// than summing.
- let local = repo.list_local_branches().map(|b| b.len()).unwrap_or(cap);
+ let local = repo.local_branches().map(|b| b.len()).unwrap_or(cap);
estimate = estimate.max(local);
}
if estimate < cap && show_remotes {
- let remotes = repo.list_remote_branches().map(|b| b.len()).unwrap_or(0);
+ let remotes = repo.remote_branches().map(|b| b.len()).unwrap_or(0);
estimate = estimate.saturating_add(remotes);
}
estimate
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 9dd5cc13c..ad58c2a36 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -820,7 +820,7 @@ pub fn execute_switch(
// Report tracking info when the branch was auto-created from a remote
let from_remote = if !create_branch && !local_branch_existed {
- branch_handle.upstream_single()?
+ branch_handle.upstream()?
} else {
None
};
diff --git a/src/git/mod.rs b/src/git/mod.rs
index ce9feb887..8c12cb2a9 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -289,6 +289,43 @@ pub struct CompletionBranch {
pub category: BranchCategory,
}
+/// A single local branch entry from the branch inventory.
+///
+/// Populated by one `git for-each-ref refs/heads/` scan per Repository lifetime
+/// (see [`Repository::local_branches`]). Sorted by most recent commit first.
+#[derive(Debug, Clone)]
+pub struct LocalBranch {
+ /// Short branch name, e.g., "feature" (not "refs/heads/feature").
+ pub name: String,
+ /// Commit SHA this branch points at.
+ pub commit_sha: String,
+ /// Unix timestamp of the commit.
+ pub committer_ts: i64,
+ /// Upstream tracking ref (e.g., "origin/main"), if configured and present.
+ /// `None` when no upstream is set, or when the configured upstream is gone
+ /// (git reports `[gone]` via `%(upstream:track)`).
+ pub upstream_short: Option<String>,
+}
+
+/// A single remote-tracking branch entry from the branch inventory.
+///
+/// Populated by one `git for-each-ref refs/remotes/` scan per Repository
+/// lifetime (see [`Repository::remote_branches`]). `<remote>/HEAD` symrefs are
+/// excluded. Sorted by most recent commit first.
+#[derive(Debug, Clone)]
+pub struct RemoteBranch {
+ /// Remote-qualified name, e.g., "origin/feature".
+ pub short_name: String,
+ /// Commit SHA this remote ref points at.
+ pub commit_sha: String,
+ /// Unix timestamp of the commit.
+ pub committer_ts: i64,
+ /// Remote name, e.g., "origin".
+ pub remote_name: String,
+ /// Branch name without the remote prefix, e.g., "feature".
+ pub local_name: String,
+}
+
// Re-export parsing helpers for internal use
pub(crate) use parse::DefaultBranchName;
diff --git a/src/git/repository/branch.rs b/src/git/repository/branch.rs
index 357d7fc28..629021a61 100644
--- a/src/git/repository/branch.rs
+++ b/src/git/repository/branch.rs
@@ -90,55 +90,22 @@ impl<'a> Branch<'a> {
Ok(remotes)
}
- /// Get the upstream tracking branch for this branch. Use this when the
- /// caller (or its caller) will query many branches; use
- /// [`upstream_single`] when exactly one branch is looked up.
+ /// Get the upstream tracking branch for this branch.
///
- /// First call in a process triggers `fetch_all_upstreams` — one
- /// `git for-each-ref` over every local branch, cached for subsequent
- /// calls. That bulk scan amortizes well across the per-worktree tasks
- /// in `wt list`, where every row needs an upstream. On a single-branch
- /// path (alias/hook template expansion, one-shot lookups during
- /// switch/merge) the scan is O(branches) overhead with nothing to
- /// amortize against — reach for [`upstream_single`] instead.
+ /// Reads from the repository's local-branch inventory (see
+ /// [`Repository::local_branches`]). The first call within a command
+ /// triggers the `refs/heads/` scan that populates the inventory;
+ /// subsequent lookups are O(1). Returns `None` when no upstream is
+ /// configured, when no local branch by this name exists, or when the
+ /// configured upstream is gone from its remote (git's `[gone]` track
+ /// state).
///
- /// [`upstream_single`]: Self::upstream_single
+ /// [`Repository::local_branches`]: super::Repository::local_branches
pub fn upstream(&self) -> anyhow::Result<Option<String>> {
- let upstreams = self
+ Ok(self
.repo
- .cache
- .upstreams
- .get_or_try_init(|| self.repo.fetch_all_upstreams())?;
- Ok(upstreams.get(&self.name).cloned().unwrap_or(None))
- }
-
- /// Get this branch's upstream without the bulk scan used by
- /// [`upstream`]. Prefer this when exactly one branch is being looked
- /// up; prefer [`upstream`] when the caller (or its caller) will query
- /// many branches. Runs one `git for-each-ref` scoped to this branch's
- /// ref — O(1) in local branch count.
- ///
- /// Handles the `[gone]` track state the same way as the bulk path:
- /// a configured-but-missing upstream reads as `None`.
- ///
- /// [`upstream`]: Self::upstream
- pub fn upstream_single(&self) -> anyhow::Result<Option<String>> {
- let output = self.repo.run_command(&[
- "for-each-ref",
- "--format=%(upstream:short)\t%(upstream:track)",
- &format!("refs/heads/{}", self.name),
- ])?;
- let Some(line) = output.lines().next() else {
- return Ok(None);
- };
- let (upstream, track) = line
- .split_once('\t')
- .expect("for-each-ref emits a tab between the two format fields");
- if upstream.is_empty() || track == "[gone]" {
- Ok(None)
- } else {
- Ok(Some(upstream.to_string()))
- }
+ .local_branch(&self.name)?
+ .and_then(|b| b.upstream_short.clone()))
}
/// Unset the upstream tracking branch for this branch.
diff --git a/src/git/repository/branches.rs b/src/git/repository/branches.rs
index 68e07be30..3e9951b6e 100644
--- a/src/git/repository/branches.rs
+++ b/src/git/repository/branches.rs
@@ -2,10 +2,87 @@
//!
//! For single-branch operations, see [`super::Branch`].
//! This module contains multi-branch operations (listing, filtering, etc.).
+//!
+//! # Branch inventory
+//!
+//! Every multi-branch operation in this file reads from one of two
+//! inventories — [`Repository::local_branches`] and
+//! [`Repository::remote_branches`]. Each is populated by a single
+//! `git for-each-ref` scan that's cached on `RepoCache` for the lifetime of
+//! this `Repository` instance (shared across clones via `Arc`):
+//!
+//! - `refs/heads/` scan fetches name, SHA, committer timestamp, and upstream
+//! tracking info — enough to satisfy every local-branch accessor (name
+//! listing, SHA priming, upstream resolution, completion ordering). The
+//! inventory also carries a name → index map so single-branch lookups
+//! (e.g. [`super::Branch::upstream`]) are O(1) without a separate scan.
+//! - `refs/remotes/` scan fetches the same fields for remote-tracking refs.
+//!
+//! Repeated accessors within a single command share the cached data. This
+//! consolidation replaces what used to be five overlapping `for-each-ref`
+//! calls (one per accessor) with at most two.
+//!
+//! Both scans are idempotent: their results depend only on the repository's
+//! ref state at the moment of the first call. Branches created mid-command
+//! by wt itself (e.g., after `git worktree add -b ...`) will not appear —
+//! but no caller needs to observe its own mutations through these accessors.
use std::collections::{HashMap, HashSet};
-use super::{BranchCategory, CompletionBranch, Repository};
+use super::{BranchCategory, CompletionBranch, LocalBranch, RemoteBranch, Repository};
+
+/// Local-branch inventory: an ordered `Vec<LocalBranch>` plus a `HashMap`
+/// for O(1) single-branch lookups.
+///
+/// Populated once per `Repository` by [`Repository::scan_local_branches`]
+/// and stored on `RepoCache`. Iteration order is the scan's own sort —
+/// committer timestamp, most recent first.
+#[derive(Debug, Default)]
+pub(in crate::git) struct LocalBranchInventory {
+ entries: Vec<LocalBranch>,
+ by_name: HashMap<String, usize>,
+}
+
+impl LocalBranchInventory {
+ fn new(entries: Vec<LocalBranch>) -> Self {
+ let by_name = entries
+ .iter()
+ .enumerate()
+ .map(|(i, b)| (b.name.clone(), i))
+ .collect();
+ Self { entries, by_name }
+ }
+
+ fn entries(&self) -> &[LocalBranch] {
+ &self.entries
+ }
+
+ fn get(&self, name: &str) -> Option<&LocalBranch> {
+ self.by_name.get(name).map(|&i| &self.entries[i])
+ }
+}
+
+/// Field separator emitted by our `for-each-ref` format strings.
+///
+/// Use `%00` (git's format escape for a NUL byte) rather than a literal NUL
+/// in the Rust string: Rust's `Command::arg` rejects arguments containing
+/// interior NUL bytes (they can't survive the `CString` conversion to
+/// `execve`), so passing `\0` through `args()` would error before git runs.
+const FIELD_SEP: char = '\0';
+
+/// Format string for the local-branch scan.
+///
+/// Fields, in order: short name, object SHA, committer Unix timestamp,
+/// upstream short name (empty if none), upstream track (`[gone]` if the
+/// configured upstream no longer exists on the remote).
+const LOCAL_BRANCH_FORMAT: &str = "--format=%(refname:lstrip=2)%00%(objectname)%00%(committerdate:unix)%00%(upstream:short)%00%(upstream:track)";
+
+/// Format string for the remote-branch scan.
+///
+/// Fields, in order: remote-qualified short name (e.g. `origin/feature`),
+/// object SHA, committer Unix timestamp.
+const REMOTE_BRANCH_FORMAT: &str =
+ "--format=%(refname:lstrip=2)%00%(objectname)%00%(committerdate:unix)";
impl Repository {
/// Check if a git reference exists (branch, tag, commit SHA, HEAD, etc.).
@@ -24,160 +101,106 @@ impl Repository {
.is_ok())
}
- /// List all local branch names, sorted by most recent commit first.
- pub fn all_branches(&self) -> anyhow::Result<Vec<String>> {
- let stdout = self.run_command(&[
- "for-each-ref",
- "--sort=-committerdate",
- "--format=%(refname:lstrip=2)",
- "refs/heads/",
- ])?;
- Ok(stdout
- .lines()
- .map(|s| s.trim())
- .filter(|s| !s.is_empty())
- .map(str::to_owned)
- .collect())
+ /// Access the local-branch inventory, scanning on first call.
+ ///
+ /// Returns every local branch (under `refs/heads/`) sorted by committer
+ /// timestamp, most recent first. Result is cached for the lifetime of
+ /// this `Repository` instance (shared across clones via `Arc`).
+ ///
+ /// The initial scan also primes `resolved_refs` (`name` →
+ /// `refs/heads/name`) and `commit_shas` (both keys → commit SHA) so
+ /// later `resolve_preferring_branch()` and `rev_parse_commit()` calls
+ /// hit memory instead of spawning per-branch `git rev-parse`.
+ pub fn local_branches(&self) -> anyhow::Result<&[LocalBranch]> {
+ Ok(self.local_branch_inventory()?.entries())
}
- /// List all local branches with their HEAD commit SHA.
- /// Returns a vector of (branch_name, commit_sha) tuples.
+ /// O(1) lookup of a single local branch by name.
///
- /// 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",
- "--format=%(refname:lstrip=2) %(objectname)",
- "refs/heads/",
- ])?;
-
- let branches: Vec<(String, String)> = output
- .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();
+ /// Returns `None` if no branch with that exact name exists. First call
+ /// triggers the `refs/heads/` scan the same way
+ /// [`local_branches`](Self::local_branches) would.
+ pub(super) fn local_branch(&self, name: &str) -> anyhow::Result<Option<&LocalBranch>> {
+ Ok(self.local_branch_inventory()?.get(name))
+ }
- Ok(branches)
+ /// Access the local-branch inventory (entries + name index).
+ fn local_branch_inventory(&self) -> anyhow::Result<&LocalBranchInventory> {
+ self.cache
+ .local_branches
+ .get_or_try_init(|| self.scan_local_branches())
}
- /// List remote branches from all remotes, excluding HEAD refs.
+ /// Access the remote-tracking branch inventory, scanning on first call.
///
- /// Returns (branch_name, commit_sha) pairs for remote branches.
- /// Branch names are in the form "origin/feature", not "feature".
- pub fn list_remote_branches(&self) -> anyhow::Result<Vec<(String, String)>> {
- let output = self.run_command(&[
- "for-each-ref",
- "--format=%(refname:lstrip=2) %(objectname)",
- "refs/remotes/",
- ])?;
-
- let branches: Vec<(String, String)> = output
- .lines()
- .filter_map(|line| {
- let (branch_name, sha) = line.split_once(' ')?;
- // Skip <remote>/HEAD (symref)
- if branch_name.ends_with("/HEAD") {
- None
- } else {
- Some((branch_name.to_string(), sha.to_string()))
- }
- })
- .collect();
+ /// Returns every remote-tracking branch (under `refs/remotes/`) sorted
+ /// by committer timestamp, most recent first. `<remote>/HEAD` symrefs
+ /// are excluded. Result is cached for the lifetime of this `Repository`
+ /// instance.
+ pub fn remote_branches(&self) -> anyhow::Result<&[RemoteBranch]> {
+ self.cache
+ .remote_branches
+ .get_or_try_init(|| self.scan_remote_branches())
+ .map(Vec::as_slice)
+ }
- Ok(branches)
+ /// Run the local-branch scan and prime SHA/ref caches.
+ fn scan_local_branches(&self) -> anyhow::Result<LocalBranchInventory> {
+ let output = self.run_command(&["for-each-ref", LOCAL_BRANCH_FORMAT, "refs/heads/"])?;
+
+ let mut branches: Vec<LocalBranch> =
+ output.lines().filter_map(parse_local_branch_line).collect();
+ branches.sort_by_key(|b| std::cmp::Reverse(b.committer_ts));
+
+ for branch in &branches {
+ let qualified = format!("refs/heads/{}", branch.name);
+ self.cache
+ .resolved_refs
+ .insert(branch.name.clone(), qualified.clone());
+ self.cache
+ .commit_shas
+ .insert(qualified, branch.commit_sha.clone());
+ self.cache
+ .commit_shas
+ .insert(branch.name.clone(), branch.commit_sha.clone());
+ }
+
+ Ok(LocalBranchInventory::new(branches))
}
- /// List all upstream tracking refs that local branches are tracking.
- ///
- /// Returns a set of upstream refs like "origin/main", "origin/feature".
- /// Useful for filtering remote branches to only show those not tracked locally.
- pub fn list_tracked_upstreams(&self) -> anyhow::Result<HashSet<String>> {
- let output =
- self.run_command(&["for-each-ref", "--format=%(upstream:short)", "refs/heads/"])?;
+ /// Run the remote-tracking-branch scan.
+ fn scan_remote_branches(&self) -> anyhow::Result<Vec<RemoteBranch>> {
+ let output = self.run_command(&["for-each-ref", REMOTE_BRANCH_FORMAT, "refs/remotes/"])?;
- let upstreams: HashSet<String> = output
+ let mut branches: Vec<RemoteBranch> = output
.lines()
- .filter(|line| !line.is_empty())
- .map(|line| line.to_string())
+ .filter_map(parse_remote_branch_line)
.collect();
-
- Ok(upstreams)
+ branches.sort_by_key(|b| std::cmp::Reverse(b.committer_ts));
+ Ok(branches)
}
- /// 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, or if the configured upstream ref no longer
- /// exists on the remote — git reports that as `[gone]` via
- /// `%(upstream:track)`). 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)\t%(upstream:track)",
- "refs/heads/",
- ])?;
-
- Ok(output
- .lines()
- .filter_map(|line| {
- let mut parts = line.splitn(3, '\t');
- let branch = parts.next()?;
- let upstream = parts.next()?;
- let track = parts.next()?;
- let value = if upstream.is_empty() || track == "[gone]" {
- None
- } else {
- Some(upstream.to_string())
- };
- Some((branch.to_string(), value))
- })
+ /// List all local branch names, sorted by most recent commit first.
+ pub fn all_branches(&self) -> anyhow::Result<Vec<String>> {
+ Ok(self
+ .local_branches()?
+ .iter()
+ .map(|b| b.name.clone())
.collect())
}
- /// List remote branches that aren't tracked by any local branch.
- ///
- /// Returns (branch_name, commit_sha) pairs for remote branches that have no
- /// corresponding local tracking branch.
- pub fn list_untracked_remote_branches(&self) -> anyhow::Result<Vec<(String, String)>> {
- let all_remote_branches = self.list_remote_branches()?;
- let tracked_upstreams = self.list_tracked_upstreams()?;
-
- let remote_branches: Vec<_> = all_remote_branches
- .into_iter()
- .filter(|(remote_branch_name, _)| !tracked_upstreams.contains(remote_branch_name))
- .collect();
-
- Ok(remote_branches)
- }
-
/// Get branches that don't have worktrees (available for switch).
pub fn available_branches(&self) -> anyhow::Result<Vec<String>> {
- let all_branches = self.all_branches()?;
let worktrees = self.list_worktrees()?;
-
- // Collect branches that have worktrees
let branches_with_worktrees: HashSet<String> = worktrees
.iter()
.filter_map(|wt| wt.branch.clone())
.collect();
-
- // Filter out branches with worktrees
- Ok(all_branches
- .into_iter()
- .filter(|branch| !branches_with_worktrees.contains(branch))
+ Ok(self
+ .local_branches()?
+ .iter()
+ .filter(|b| !branches_with_worktrees.contains(&b.name))
+ .map(|b| b.name.clone())
.collect())
}
@@ -193,117 +216,69 @@ impl Repository {
/// For remote branches, returns the local name (e.g., "fix" not "origin/fix")
/// since `git worktree add path fix` auto-creates a tracking branch.
pub fn branches_for_completion(&self) -> anyhow::Result<Vec<CompletionBranch>> {
- // Get worktree branches
let worktrees = self.list_worktrees()?;
let worktree_branches: HashSet<String> = worktrees
.iter()
.filter_map(|wt| wt.branch.clone())
.collect();
- // Get local branches with timestamps
- let local_output = self.run_command(&[
- "for-each-ref",
- "--sort=-committerdate",
- "--format=%(refname:lstrip=2)\t%(committerdate:unix)",
- "refs/heads/",
- ])?;
+ let locals = self.local_branches()?;
+ let local_names: HashSet<&str> = locals.iter().map(|b| b.name.as_str()).collect();
- let local_branches: Vec<(String, i64)> = local_output
- .lines()
- .filter_map(|line| {
- let (name, timestamp_str) = line.split_once('\t')?;
- let timestamp = timestamp_str.parse().unwrap_or(0);
- Some((name.to_string(), timestamp))
- })
- .collect();
-
- let local_branch_names: HashSet<String> =
- local_branches.iter().map(|(n, _)| n.clone()).collect();
-
- // Get remote branches with timestamps from all remotes
- // Matches git's behavior: searches all remotes for branch names
- let remote_output = self.run_command(&[
- "for-each-ref",
- "--sort=-committerdate",
- "--format=%(refname:lstrip=2)\t%(committerdate:unix)",
- "refs/remotes/",
- ])?;
-
- // Group by branch name, collecting all remotes that have each branch.
- // Uses HashMap for grouping, then sorts by timestamp to preserve recency order.
+ // Group remote branches by local name, collecting all remotes that
+ // have each branch. Skip remotes that have a same-named local branch
+ // (users should use the local one). Keeps the most recent timestamp
+ // across remotes to preserve recency ordering.
let mut branch_remotes: HashMap<String, (Vec<String>, i64)> = HashMap::new();
-
- for line in remote_output.lines() {
- // Format: "<remote>/<branch>\t<timestamp>"
- let Some((full_name, timestamp_str)) = line.split_once('\t') else {
- continue;
- };
-
- // Parse <remote>/<branch> - find first slash to split
- let Some((remote_name, local_name)) = full_name.split_once('/') else {
- continue;
- };
-
- // Skip <remote>/HEAD
- if local_name == "HEAD" {
- continue;
- }
- // Skip if local branch exists (user should use local)
- if local_branch_names.contains(local_name) {
+ for remote in self.remote_branches()? {
+ if local_names.contains(remote.local_name.as_str()) {
continue;
}
-
- let timestamp = timestamp_str.parse().unwrap_or(0);
-
- // Add remote to this branch's list, keeping the most recent timestamp
branch_remotes
- .entry(local_name.to_string())
- .and_modify(|(remotes, existing_ts)| {
- remotes.push(remote_name.to_string());
- *existing_ts = (*existing_ts).max(timestamp);
+ .entry(remote.local_name.clone())
+ .and_modify(|(remotes, ts)| {
+ remotes.push(remote.remote_name.clone());
+ *ts = (*ts).max(remote.committer_ts);
})
- .or_insert_with(|| (vec![remote_name.to_string()], timestamp));
+ .or_insert_with(|| (vec![remote.remote_name.clone()], remote.committer_ts));
}
-
- // Convert to vec and sort by timestamp (descending = most recent first)
- let mut remote_branches: Vec<(String, Vec<String>, i64)> = branch_remotes
+ let mut remote_only: Vec<(String, Vec<String>, i64)> = branch_remotes
.into_iter()
- .map(|(name, (mut remotes, timestamp))| {
+ .map(|(name, (mut remotes, ts))| {
remotes.sort(); // Deterministic remote ordering within each branch
- (name, remotes, timestamp)
+ (name, remotes, ts)
})
.collect();
- remote_branches.sort_by_key(|b| std::cmp::Reverse(b.2));
+ remote_only.sort_by_key(|b| std::cmp::Reverse(b.2));
- // Build result: worktrees first, then local, then remote
- let mut result = Vec::new();
+ let mut result = Vec::with_capacity(locals.len() + remote_only.len());
- // Worktree branches (sorted by recency from local_branches order)
- for (name, timestamp) in &local_branches {
- if worktree_branches.contains(name) {
+ // Worktree branches (already sorted by recency via locals order).
+ for branch in locals {
+ if worktree_branches.contains(&branch.name) {
result.push(CompletionBranch {
- name: name.clone(),
- timestamp: *timestamp,
+ name: branch.name.clone(),
+ timestamp: branch.committer_ts,
category: BranchCategory::Worktree,
});
}
}
- // Local branches without worktrees
- for (name, timestamp) in &local_branches {
- if !worktree_branches.contains(name) {
+ // Local branches without worktrees.
+ for branch in locals {
+ if !worktree_branches.contains(&branch.name) {
result.push(CompletionBranch {
- name: name.clone(),
- timestamp: *timestamp,
+ name: branch.name.clone(),
+ timestamp: branch.committer_ts,
category: BranchCategory::Local,
});
}
}
- // Remote-only branches
- for (local_name, remotes, timestamp) in remote_branches {
+ // Remote-only branches.
+ for (name, remotes, timestamp) in remote_only {
result.push(CompletionBranch {
- name: local_name,
+ name,
timestamp,
category: BranchCategory::Remote(remotes),
});
@@ -312,3 +287,53 @@ impl Repository {
Ok(result)
}
}
+
+/// Parse one record from the local-branch scan.
+///
+/// Returns `None` for malformed lines — e.g. a future git format change or
+/// a control character snuck through. Callers skip those entries rather
+/// than fail the whole scan.
+fn parse_local_branch_line(line: &str) -> Option<LocalBranch> {
+ let mut parts = line.split(FIELD_SEP);
+ let name = parts.next()?.to_string();
+ let commit_sha = parts.next()?.to_string();
+ let committer_ts: i64 = parts.next()?.parse().ok()?;
+ let upstream_short_raw = parts.next()?;
+ let upstream_track = parts.next()?;
+ let upstream_short = if upstream_short_raw.is_empty() || upstream_track == "[gone]" {
+ None
+ } else {
+ Some(upstream_short_raw.to_string())
+ };
+ Some(LocalBranch {
+ name,
+ commit_sha,
+ committer_ts,
+ upstream_short,
+ })
+}
+
+/// Parse one record from the remote-branch scan.
+///
+/// Skips `<remote>/HEAD` symrefs — they duplicate another ref and would
+/// confuse callers that key by local name.
+fn parse_remote_branch_line(line: &str) -> Option<RemoteBranch> {
+ let mut parts = line.split(FIELD_SEP);
+ let short_name = parts.next()?;
+ let commit_sha = parts.next()?.to_string();
+ let committer_ts: i64 = parts.next()?.parse().ok()?;
+
+ // `<remote>/HEAD` is a symref to the remote's default branch; skip it.
+ let (remote_name, local_name) = short_name.split_once('/')?;
+ if local_name == "HEAD" {
+ return None;
+ }
+
+ Some(RemoteBranch {
+ short_name: short_name.to_string(),
+ commit_sha,
+ committer_ts,
+ remote_name: remote_name.to_string(),
+ local_name: local_name.to_string(),
+ })
+}
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rs
index dfd9d5bd0..7d491db80 100644
--- a/src/git/repository/integration.rs
+++ b/src/git/repository/integration.rs
@@ -433,10 +433,11 @@ impl Repository {
.effective_integration_targets
.entry(local_target.to_string())
.or_insert_with(|| {
- // Get the upstream ref for the local target (e.g., origin/main for main).
- // Single-branch lookup — cached per-target in `effective_integration_targets`,
- // so the bulk scan `upstream()` would run is pure overhead here.
- let upstream = match self.branch(local_target).upstream_single() {
+ // Resolve the upstream via the cached branch inventory
+ // (`Repository::local_branches`). On the first call the
+ // inventory scan primes this and every subsequent upstream
+ // lookup; on repeat calls it's a map lookup.
+ let upstream = match self.branch(local_target).upstream() {
Ok(Some(upstream)) => upstream,
_ => return local_target.to_string(),
};
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index a2667d50a..06ff09b70 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -62,7 +62,6 @@
//! 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;
@@ -87,7 +86,9 @@ use crate::config::{LoadError, ProjectConfig, ResolvedConfig, UserConfig};
use super::{DefaultBranchName, GitError, IntegrationReason, LineDiff, WorktreeInfo};
// Re-export types needed by submodules
-pub(super) use super::{BranchCategory, CompletionBranch, DiffStats, GitRemoteUrl};
+pub(super) use super::{
+ BranchCategory, CompletionBranch, DiffStats, GitRemoteUrl, LocalBranch, RemoteBranch,
+};
// Submodules with impl blocks
mod branch;
@@ -263,10 +264,19 @@ 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>>>,
+ /// Local branch inventory: one `git for-each-ref refs/heads/` scan, cached
+ /// for the lifetime of the repository. Entries are sorted by most recent
+ /// commit first; the inventory also holds a name → index map for O(1)
+ /// single-branch lookups. Populated lazily via
+ /// [`Repository::local_branches`] — the first call runs the scan and
+ /// primes `resolved_refs`/`commit_shas` so subsequent ref resolution and
+ /// SHA lookups hit memory.
+ pub(super) local_branches: OnceCell<branches::LocalBranchInventory>,
+ /// Remote-tracking branch inventory: one `git for-each-ref refs/remotes/`
+ /// scan, cached for the lifetime of the repository. Sorted by most recent
+ /// commit first. Populated lazily via [`Repository::remote_branches`].
+ /// Excludes `<remote>/HEAD` symrefs.
+ pub(super) remote_branches: OnceCell<Vec<RemoteBranch>>,
/// 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.