Skip to content

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

perf(list): cache push-remote URL and share local-branch scan with capture_refs (#2673)

Worktrunk Bot2905534f99c7
diff --git a/src/git/repository/branch.rs b/src/git/repository/branch.rs
index 76c519055..b07282efd 100644
--- a/src/git/repository/branch.rs
+++ b/src/git/repository/branch.rs
@@ -141,27 +141,38 @@ impl<'a> Branch<'a> {
/// (`gh pr checkout` sets pushremote to a URL rather than a remote name).
/// For remote names, uses `effective_remote_url` to apply `url.insteadOf` rewrites.
/// Returns `None` if no push remote is configured or the remote has no URL.
+ ///
+ /// Result is cached on `RepoCache.push_remote_urls`. The CI-status detector
+ /// calls `github_push_url` from both `detect_github` (PR-based) and
+ /// `detect_github_commit_checks` (branch fallback), so without the cache the
+ /// `for-each-ref` runs twice for the same branch on the no-PR path.
fn push_remote_url(&self) -> Option<String> {
- // %(push:remotename) returns either a remote name or URL directly
- // Unlike @{push}, this doesn't fail when pushremote is a URL
- let push_remote = self
- .repo
- .run_command(&[
- "for-each-ref",
- "--format=%(push:remotename)",
- &format!("refs/heads/{}", self.name),
- ])
- .ok()
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty())?;
+ self.repo
+ .cache
+ .push_remote_urls
+ .entry(self.name.clone())
+ .or_insert_with(|| {
+ // %(push:remotename) returns either a remote name or URL
+ // directly. Unlike @{push}, this doesn't fail when pushremote
+ // is a URL.
+ let push_remote = self
+ .repo
+ .run_command(&[
+ "for-each-ref",
+ "--format=%(push:remotename)",
+ &format!("refs/heads/{}", self.name),
+ ])
+ .ok()
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())?;
- // If it's already a URL, return it directly
- if push_remote.contains("://") || push_remote.starts_with("git@") {
- Some(push_remote)
- } else {
- // It's a remote name — use effective URL (handles insteadOf)
- self.repo.effective_remote_url(&push_remote)
- }
+ if push_remote.contains("://") || push_remote.starts_with("git@") {
+ Some(push_remote)
+ } else {
+ self.repo.effective_remote_url(&push_remote)
+ }
+ })
+ .clone()
}
/// Get the GitHub URL for this branch's push remote, if it's a GitHub URL.
diff --git a/src/git/repository/branches.rs b/src/git/repository/branches.rs
index ae7d067de..8b0c77226 100644
--- a/src/git/repository/branches.rs
+++ b/src/git/repository/branches.rs
@@ -44,7 +44,7 @@ pub(in crate::git) struct LocalBranchInventory {
}
impl LocalBranchInventory {
- fn new(entries: Vec<LocalBranch>) -> Self {
+ pub(super) fn new(entries: Vec<LocalBranch>) -> Self {
let by_name = entries
.iter()
.enumerate()
@@ -53,7 +53,7 @@ impl LocalBranchInventory {
Self { entries, by_name }
}
- fn entries(&self) -> &[LocalBranch] {
+ pub(super) fn entries(&self) -> &[LocalBranch] {
&self.entries
}
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 20a7d45b9..ccadc606e 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -268,6 +268,14 @@ pub(super) struct RepoCache {
/// Separate from `all_config` because `git remote get-url` applies
/// `url.insteadOf` rewrites that aren't visible in raw config.
pub(super) effective_remote_urls: DashMap<String, Option<String>>,
+ /// Per-branch effective push URL: branch_name -> push URL (or None if
+ /// no push remote is configured). One `for-each-ref %(push:remotename)`
+ /// per branch, then `effective_remote_url` for the resolved remote name.
+ /// `wt list`'s CI-status detection calls `github_push_url` from both
+ /// `detect_github` (PR-based) and `detect_github_commit_checks` (commit
+ /// fallback), so the same branch is queried twice on the no-PR path —
+ /// this cache collapses that to one subprocess.
+ pub(super) push_remote_urls: DashMap<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
diff --git a/src/git/repository/ref_snapshot.rs b/src/git/repository/ref_snapshot.rs
index 946dd5038..56e6f9225 100644
--- a/src/git/repository/ref_snapshot.rs
+++ b/src/git/repository/ref_snapshot.rs
@@ -156,6 +156,21 @@ fn scan_locals(repo: &Repository) -> anyhow::Result<Vec<LocalBranch>> {
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));
+
+ // Populate the local-branch inventory cache as a side-effect so that
+ // subsequent `repo.local_branches()` callers (e.g., `Branch::upstream`
+ // running on a worker thread during `wt list`) hit memory instead of
+ // re-running the same `for-each-ref refs/heads/` scan. `set()` is a
+ // no-op when the cache is already populated, preserving the
+ // first-scan-wins contract documented on `RepoCache.local_branches` —
+ // every later `capture_refs` call still scans fresh, so mutating
+ // commands that need post-update SHAs (e.g. `wt merge`'s post-merge
+ // `capture_refs` in `worktree::finish`) are unaffected.
+ let _ = repo
+ .cache
+ .local_branches
+ .set(super::branches::LocalBranchInventory::new(branches.clone()));
+
Ok(branches)
}
@@ -313,6 +328,88 @@ mod tests {
}
}
+ #[test]
+ fn capture_refs_populates_local_branch_cache() {
+ // The local-branch inventory cache is populated as a side-effect
+ // of `capture_refs`, so a subsequent `local_branches()` call on
+ // the same `Repository` reads from memory instead of re-running
+ // `for-each-ref refs/heads/`. The statusline render hits both
+ // entry points: the main thread captures a `RefSnapshot`, then a
+ // worker thread reads `Branch::upstream` (which goes through the
+ // local-branch inventory) — without this side-effect the same
+ // scan ran twice (worktrunk#2672).
+ let test = TestRepo::with_initial_commit();
+ let repo = Repository::at(test.root_path()).unwrap();
+
+ // Cache is empty before capture.
+ assert!(repo.cache.local_branches.get().is_none());
+
+ let _snap = repo.capture_refs().unwrap();
+
+ // Capture populates the inventory cache.
+ let inventory = repo
+ .cache
+ .local_branches
+ .get()
+ .expect("capture_refs should populate the local-branch cache");
+ assert!(inventory.entries().iter().any(|b| b.name == "main"));
+
+ // Mutating refs after capture must NOT change what the cache
+ // returns — `local_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 main_after = test.git_output(&["rev-parse", "main"]);
+
+ let cached_main = repo
+ .local_branches()
+ .unwrap()
+ .iter()
+ .find(|b| b.name == "main")
+ .expect("main is cached")
+ .commit_sha
+ .clone();
+ assert_ne!(
+ cached_main, main_after,
+ "test setup: ref must have moved between capture and read"
+ );
+ }
+
+ #[test]
+ fn capture_refs_scans_fresh_when_cache_already_populated() {
+ // Mutation paths (e.g., `wt merge`) call `capture_refs` AFTER
+ // moving a ref, expecting the post-mutation SHA. If the inventory
+ // cache had been populated earlier with the pre-mutation SHA, the
+ // snapshot still has to scan fresh — `set()` is a no-op on the
+ // already-populated cell, but the snapshot itself reflects the
+ // current ref state.
+ let test = TestRepo::with_initial_commit();
+ let repo = Repository::at(test.root_path()).unwrap();
+
+ // Populate the inventory cache by calling local_branches first.
+ let main_before = repo
+ .local_branches()
+ .unwrap()
+ .iter()
+ .find(|b| b.name == "main")
+ .unwrap()
+ .commit_sha
+ .clone();
+
+ // Move main forward.
+ 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 main_after = test.git_output(&["rev-parse", "main"]);
+ assert_ne!(main_before, main_after);
+
+ // capture_refs sees post-move SHA even though the inventory cache
+ // still holds the pre-move value.
+ let snap = repo.capture_refs().unwrap();
+ assert_eq!(snap.resolve("main"), Some(main_after.as_str()));
+ }
+
#[test]
fn upstream_of_reads_from_local_inventory() {
let test = TestRepo::with_initial_commit();
diff --git a/tests/integration_tests/default_branch.rs b/tests/integration_tests/default_branch.rs
index 9e09cdbbc..4bffd00f7 100644
--- a/tests/integration_tests/default_branch.rs
+++ b/tests/integration_tests/default_branch.rs
@@ -574,6 +574,38 @@ fn test_github_push_url_non_github_forge_returns_none(repo: TestRepo) {
assert!(git_repo.branch("main").github_push_url().is_none());
}
+/// Test github_push_url: result is cached on the Repository.
+///
+/// `wt list`'s CI-status detection calls `github_push_url` from both
+/// `detect_github` (PR-based) and `detect_github_commit_checks` (branch
+/// fallback) — without caching the underlying `for-each-ref %(push:remotename)`
+/// runs twice for the same branch on the no-PR path (worktrunk#2672).
+/// Mutating the branch's push tracking after the first call must not
+/// change the cached value.
+#[rstest]
+fn test_github_push_url_is_cached(repo: TestRepo) {
+ repo.run_git(&["config", "remote.origin.url", "[email protected]:org/repo.git"]);
+ setup_push_tracking(&repo, "main", "origin");
+
+ let git_repo = Repository::at(repo.root_path()).unwrap();
+ let first = git_repo
+ .branch("main")
+ .github_push_url()
+ .expect("first call resolves to a GitHub URL");
+
+ // Remove the push tracking config. A fresh `for-each-ref
+ // %(push:remotename)` would now return empty, so a non-cached
+ // implementation would yield None on the second call.
+ repo.run_git(&["config", "--unset", "branch.main.remote"]);
+ repo.run_git(&["config", "--unset", "branch.main.merge"]);
+
+ let second = git_repo
+ .branch("main")
+ .github_push_url()
+ .expect("second call returns the cached URL");
+ assert_eq!(first, second);
+}
+
/// Test github_push_url: returns None when insteadOf resolves to GitLab (not GitHub).
#[rstest]
fn test_github_push_url_unknown_host_non_github_insteadof(repo: TestRepo) {