Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(repo): collapse ahead_behind into get-or-insert (#2347)
Maximilian Roos416497796090
diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rsindex d24d09ec7..b28d2d7a9 100644--- a/src/commands/list/collect/tasks.rs+++ b/src/commands/list/collect/tasks.rs@@ -173,27 +173,20 @@ impl Task for AheadBehindTask {});}- // Check cache first (populated by batch_ahead_behind if it ran).- // Cache lookup has minor overhead (rev-parse for cache key + allocations),- // but saves the expensive ahead_behind computation on cache hit.- //// When the ref has a branch name, compute counts against the branch — not// the worktree's current HEAD sha. During rebase/merge conflicts, HEAD is// transiently at a different commit than the branch tip, so using the sha// would report misleading counts (e.g., `0/0 same_commit` when the branch// is actually diverged). The batch path already uses branch names, so this// keeps both paths consistent.- let (ahead, behind) = if let Some(branch) = ctx.branch_ref.branch.as_deref() {- if let Some(counts) = repo.cached_ahead_behind(&base, branch) {- counts- } else {- repo.ahead_behind(&base, branch)- .map_err(|e| ctx.error(Self::KIND, &e))?- }- } else {- repo.ahead_behind(&base, &ctx.branch_ref.commit_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?- };+ let head = ctx+ .branch_ref+ .branch+ .as_deref()+ .unwrap_or(&ctx.branch_ref.commit_sha);+ let (ahead, behind) = repo+ .ahead_behind(&base, head)+ .map_err(|e| ctx.error(Self::KIND, &e))?;Ok(TaskResult::AheadBehind {item_idx: ctx.item_idx,diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rsindex 622c2daaf..d279efeda 100644--- a/src/git/repository/diff.rs+++ b/src/git/repository/diff.rs@@ -204,10 +204,22 @@ impl Repository {/// For orphan branches with no common ancestor, returns `(0, 0)`./// Caller should check for orphan status separately via `merge_base()`.///- /// Uses `merge_base()` internally (which is cached) to compute the common- /// ancestor, then counts commits using two-dot syntax. This allows the- /// merge-base result to be reused across multiple operations.+ /// Results are cached in the shared repo cache. `batch_ahead_behind()`+ /// primes the cache for all local branches at once via a single+ /// `for-each-ref`; subsequent calls here hit the cache. On a miss, falls+ /// back to `merge_base()` + `rev-list --count`, also cached on insert.pub fn ahead_behind(&self, base: &str, head: &str) -> anyhow::Result<(usize, usize)> {+ let key = (base.to_string(), head.to_string());+ match self.cache.ahead_behind.entry(key) {+ Entry::Occupied(e) => Ok(*e.get()),+ Entry::Vacant(e) => {+ let counts = self.compute_ahead_behind(base, head)?;+ Ok(*e.insert(counts))+ }+ }+ }++ fn compute_ahead_behind(&self, base: &str, head: &str) -> anyhow::Result<(usize, usize)> {// Get merge-base (cached in shared repo cache)let Some(merge_base) = self.merge_base(base, head)? else {// Orphan branch - no common ancestor@@ -244,13 +256,12 @@ impl Repository {/// Batch-fetch ahead/behind counts for all local branches vs a base ref.///- /// Uses `git for-each-ref --format='%(ahead-behind:BASE)'` (git 2.36+) to get- /// all counts in a single command. Returns a map from branch name to (ahead, behind).+ /// Uses `git for-each-ref --format='%(ahead-behind:BASE)'` (git 2.36+) to+ /// get all counts in a single command, priming `cache.ahead_behind` so+ /// subsequent `ahead_behind()` calls hit the cache.///- /// Results are cached so subsequent lookups via `cached_ahead_behind()` avoid- /// running individual git commands (though cache access still has minor overhead).- ///- /// On git < 2.36 or if the command fails, returns an empty map.+ /// On git < 2.36 or if the command fails, returns an empty map (and+ /// `ahead_behind()` falls back to per-branch computation).pub fn batch_ahead_behind(&self, base: &str) -> HashMap<String, (usize, usize)> {let format = format!("%(refname:lstrip=2) %(ahead-behind:{})", base);let output = match self.run_command(&[@@ -285,17 +296,6 @@ impl Repository {results}- /// Get cached ahead/behind counts for a branch.- ///- /// Returns cached results from a prior `batch_ahead_behind()` call, or None- /// if the branch wasn't in the batch or batch wasn't run.- pub fn cached_ahead_behind(&self, base: &str, branch: &str) -> Option<(usize, usize)> {- self.cache- .ahead_behind- .get(&(base.to_string(), branch.to_string()))- .map(|r| *r)- }-/// Get line diff statistics between two refs.////// Uses merge-base (cached) to find common ancestor, then two-dot diffdiff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 667759a4c..d444a0127 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -231,8 +231,10 @@ pub(super) struct RepoCache {pub(super) sparse_checkout_paths: OnceCell<Vec<String>>,/// Merge-base cache: (commit1, commit2) -> merge_base_sha (None = no common ancestor)pub(super) merge_base: DashMap<(String, String), Option<String>>,- /// Batch ahead/behind cache: (base_ref, branch_name) -> (ahead, behind)- /// Populated by batch_ahead_behind(), used by cached_ahead_behind()+ /// Ahead/behind cache: (base_ref, head) -> (ahead, behind).+ /// Primed in bulk by `batch_ahead_behind()`; populated on demand by+ /// `ahead_behind()` for keys the batch didn't cover (e.g., HEAD SHAs+ /// during rebase/merge, or git < 2.36 where the batch returns empty).pub(super) ahead_behind: DashMap<(String, String), (usize, usize)>,/// Effective remote URLs: remote_name -> effective URL (with `url.insteadOf` applied)./// Separate from `all_config` because `git remote get-url` applies