Skip to content

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

refactor(branches): share the for-each-ref scan primitive; cache remote inventory from the snapshot path (#2735)

Maximilian Roos4a2085a744ac
diff --git a/src/git/repository/branches.rs b/src/git/repository/branches.rs
index 8b0c77226..077481e38 100644
--- a/src/git/repository/branches.rs
+++ b/src/git/repository/branches.rs
@@ -34,8 +34,8 @@ use super::{BranchCategory, CompletionBranch, LocalBranch, RemoteBranch, Reposit
/// 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 —
+/// Built from [`Repository::scan_local_branch_records`] and stored on
+/// `RepoCache` (first scan wins). Iteration order is the scan's own sort —
/// committer timestamp, most recent first.
#[derive(Debug, Default)]
pub(in crate::git) struct LocalBranchInventory {
@@ -68,20 +68,20 @@ impl LocalBranchInventory {
/// 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.
-pub(super) const FIELD_SEP: char = '\0';
+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).
-pub(super) const LOCAL_BRANCH_FORMAT: &str = "--format=%(refname:lstrip=2)%00%(objectname)%00%(committerdate:unix)%00%(upstream:short)%00%(upstream:track)";
+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.
-pub(super) const REMOTE_BRANCH_FORMAT: &str =
+const REMOTE_BRANCH_FORMAT: &str =
"--format=%(refname:lstrip=2)%00%(objectname)%00%(committerdate:unix)";
impl Repository {
@@ -164,7 +164,7 @@ impl Repository {
fn local_branch_inventory(&self) -> anyhow::Result<&LocalBranchInventory> {
self.cache
.local_branches
- .get_or_try_init(|| self.scan_local_branches())
+ .get_or_try_init(|| Ok(LocalBranchInventory::new(self.scan_local_branch_records()?)))
}
/// Access the remote-tracking branch inventory, scanning on first call.
@@ -176,29 +176,35 @@ impl Repository {
pub fn remote_branches(&self) -> anyhow::Result<&[RemoteBranch]> {
self.cache
.remote_branches
- .get_or_try_init(|| self.scan_remote_branches())
+ .get_or_try_init(|| self.scan_remote_branch_records())
.map(Vec::as_slice)
}
- /// Run the local-branch scan.
+ /// One `for-each-ref refs/heads/` scan, parsed and sorted by committer
+ /// timestamp (most recent first). The shared scan primitive behind both
+ /// the cache accessor ([`local_branches`](Self::local_branches), via
+ /// [`local_branch_inventory`](Self::local_branch_inventory)) and the
+ /// snapshot path ([`crate::git::RefSnapshot`] capture). No cache
+ /// side-effect — each caller decides how to store the result
+ /// (first-scan-wins cell vs. fresh snapshot).
///
- /// The inventory's `commit_sha` fields are a snapshot at scan time —
- /// callers that need a current SHA must resolve through a
- /// [`crate::git::RefSnapshot`] captured at the moment of the read,
- /// not through this inventory.
- fn scan_local_branches(&self) -> anyhow::Result<LocalBranchInventory> {
+ /// `commit_sha` is a snapshot at scan time — callers that need a
+ /// current SHA must resolve through a [`crate::git::RefSnapshot`]
+ /// captured at the moment of the read, not through this list.
+ pub(super) fn scan_local_branch_records(&self) -> anyhow::Result<Vec<LocalBranch>> {
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));
- Ok(LocalBranchInventory::new(branches))
+ Ok(branches)
}
- /// Run the remote-tracking-branch scan.
- fn scan_remote_branches(&self) -> anyhow::Result<Vec<RemoteBranch>> {
+ /// One `for-each-ref refs/remotes/` scan, parsed (excluding
+ /// `<remote>/HEAD` symrefs) and sorted by committer timestamp. The
+ /// shared scan primitive behind both [`remote_branches`](Self::remote_branches)
+ /// and the snapshot path. No cache side-effect.
+ pub(super) fn scan_remote_branch_records(&self) -> anyhow::Result<Vec<RemoteBranch>> {
let output = self.run_command(&["for-each-ref", REMOTE_BRANCH_FORMAT, "refs/remotes/"])?;
-
let mut branches: Vec<RemoteBranch> = output
.lines()
.filter_map(parse_remote_branch_line)
@@ -320,7 +326,7 @@ impl Repository {
/// 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.
-pub(super) fn parse_local_branch_line(line: &str) -> Option<LocalBranch> {
+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();
@@ -344,7 +350,7 @@ pub(super) fn parse_local_branch_line(line: &str) -> Option<LocalBranch> {
///
/// Skips `<remote>/HEAD` symrefs — they duplicate another ref and would
/// confuse callers that key by local name.
-pub(super) fn parse_remote_branch_line(line: &str) -> Option<RemoteBranch> {
+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();
diff --git a/src/git/repository/ref_snapshot.rs b/src/git/repository/ref_snapshot.rs
index 9c5b1ed3c..98d09f377 100644
--- a/src/git/repository/ref_snapshot.rs
+++ b/src/git/repository/ref_snapshot.rs
@@ -39,9 +39,7 @@ use std::collections::HashMap;
use anyhow::bail;
-use super::branches::{
- LOCAL_BRANCH_FORMAT, REMOTE_BRANCH_FORMAT, parse_local_branch_line, parse_remote_branch_line,
-};
+use super::branches::LocalBranchInventory;
use super::{LocalBranch, RemoteBranch, Repository};
/// An immutable snapshot of repository ref state.
@@ -459,10 +457,7 @@ fn resolve_sha_from_scan<'a>(
}
fn scan_locals(repo: &Repository) -> anyhow::Result<Vec<LocalBranch>> {
- let output = repo.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));
+ let branches = repo.scan_local_branch_records()?;
// Populate the local-branch inventory cache as a side-effect so that
// subsequent `repo.local_branches()` callers (e.g., `Branch::upstream`
@@ -476,18 +471,26 @@ fn scan_locals(repo: &Repository) -> anyhow::Result<Vec<LocalBranch>> {
let _ = repo
.cache
.local_branches
- .set(super::branches::LocalBranchInventory::new(branches.clone()));
+ .set(LocalBranchInventory::new(branches.clone()));
Ok(branches)
}
fn scan_remotes(repo: &Repository) -> anyhow::Result<Vec<RemoteBranch>> {
- let output = repo.run_command(&["for-each-ref", REMOTE_BRANCH_FORMAT, "refs/remotes/"])?;
- let mut branches: Vec<RemoteBranch> = output
- .lines()
- .filter_map(parse_remote_branch_line)
- .collect();
- branches.sort_by_key(|b| std::cmp::Reverse(b.committer_ts));
+ let branches = repo.scan_remote_branch_records()?;
+
+ // Populate the remote-branch inventory cache as a side-effect so that
+ // subsequent `repo.remote_branches()` callers (e.g., picker preview
+ // sizing, `Branch::upstream`, `branches_for_completion`) hit memory
+ // instead of re-running the same `for-each-ref refs/remotes/` scan.
+ // Mirrors the side-effect in `scan_locals`: `set()` is a no-op when
+ // the cache is already populated, preserving the first-scan-wins
+ // contract documented on `RepoCache.remote_branches` — every later
+ // `capture_refs` call still scans fresh, so any future ref-mutating
+ // command that touches `refs/remotes/` and then captures a new
+ // snapshot is unaffected.
+ let _ = repo.cache.remote_branches.set(branches.clone());
+
Ok(branches)
}
@@ -942,6 +945,67 @@ mod tests {
assert_eq!(snap.resolve("main"), Some(main_after.as_str()));
}
+ #[test]
+ fn capture_refs_populates_remote_branch_cache() {
+ // Mirrors `capture_refs_populates_local_branch_cache`: the
+ // snapshot's `scan_remotes` populates `cache.remote_branches` as
+ // a side-effect, so a subsequent `Repository::remote_branches()`
+ // call on the same `Repository` reads from memory instead of
+ // re-running `for-each-ref refs/remotes/`.
+ let test = TestRepo::with_initial_commit();
+ let main_sha = test.git_output(&["rev-parse", "main"]);
+ test.run_git(&["update-ref", "refs/remotes/origin/trunk", &main_sha]);
+ let repo = Repository::at(test.root_path()).unwrap();
+
+ // Cache is empty before capture.
+ assert!(repo.cache.remote_branches.get().is_none());
+
+ let _snap = repo.capture_refs().unwrap();
+
+ // Capture populated the inventory cache.
+ let inventory = repo
+ .cache
+ .remote_branches
+ .get()
+ .expect("capture_refs should populate the remote-branch cache");
+ assert!(inventory.iter().any(|r| r.short_name == "origin/trunk"));
+
+ // Mutating refs after capture must NOT change what the cache
+ // returns — `remote_branches()` reads the populated cell, not
+ // the current ref state.
+ std::fs::write(test.root_path().join("a.txt"), "x\n").unwrap();
+ test.run_git(&["add", "a.txt"]);
+ test.run_git(&["commit", "-m", "advance main"]);
+ let advanced = test.git_output(&["rev-parse", "main"]);
+ test.run_git(&["update-ref", "refs/remotes/origin/trunk", &advanced]);
+
+ let cached_trunk = repo
+ .remote_branches()
+ .unwrap()
+ .iter()
+ .find(|r| r.short_name == "origin/trunk")
+ .expect("origin/trunk is cached")
+ .commit_sha
+ .clone();
+ assert_ne!(
+ cached_trunk, advanced,
+ "test setup: remote ref must have moved between capture and read"
+ );
+
+ // A fresh `Repository::at` scans again and sees the new SHA.
+ let repo2 = Repository::at(test.root_path()).unwrap();
+ let _snap2 = repo2.capture_refs().unwrap();
+ let fresh_trunk = repo2
+ .remote_branches()
+ .unwrap()
+ .iter()
+ .find(|r| r.short_name == "origin/trunk")
+ .unwrap()
+ .commit_sha
+ .clone();
+ assert_eq!(fresh_trunk, advanced);
+ }
+
#[test]
fn upstream_of_reads_from_local_inventory() {
let test = TestRepo::with_initial_commit();