Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
perf(repo): cache list_worktrees on RepoCache (#2375)
Maximilian Roos2114fda101d5
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 06ff09b70..b4b65833f 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -33,7 +33,13 @@//! **What is NOT cached.** Values that change during command execution are intentionally//! excluded://! - `WorkingTree::is_dirty()` — changes as we stage and commit-//! - `Repository::list_worktrees()` — changes as we create and remove worktrees+//!+//! [`Repository::list_worktrees`] is cached despite mutating commands adding or+//! removing worktrees. The cache is safe because no caller reads the list+//! through the same `Repository` after its own mutation — mutating paths+//! either read once up front and thread the slice through, or rebuild a+//! fresh `Repository::at(...)` before any post-mutation probe. This mirrors+//! the invariant the branch inventories already rely on.//!//! **Access patterns.** See the [`RepoCache`] doc comment for the two storage patterns//! (repo-wide `OnceCell` vs per-key `DashMap`) and their infallible/fallible variants.@@ -277,6 +283,13 @@ pub(super) struct RepoCache {/// commit first. Populated lazily via [`Repository::remote_branches`]./// Excludes `<remote>/HEAD` symrefs.pub(super) remote_branches: OnceCell<Vec<RemoteBranch>>,+ /// Worktree inventory: one `git worktree list --porcelain` scan, cached+ /// for the lifetime of the repository. Populated lazily via+ /// [`Repository::list_worktrees`]. The picker warms this on the main+ /// thread (for its preview-window sizing estimate) so the background+ /// `collect::collect` pass hits memory instead of respawning the+ /// subprocess on the critical path to skeleton.+ pub(super) worktrees: OnceCell<Vec<WorktreeInfo>>,/// 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.diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rsindex b7938ec86..2593e679e 100644--- a/src/git/repository/worktrees.rs+++ b/src/git/repository/worktrees.rs@@ -19,36 +19,46 @@ impl Repository {/// is the first linked worktree (no semantic "main" exists).////// Returns an empty vec for bare repos with no linked worktrees.+ ///+ /// Cached on `RepoCache` after the first successful call; subsequent+ /// calls clone from the cache. See the module-level `# Caching` docs for+ /// the "no post-mutation reads through the cache" invariant.pub fn list_worktrees(&self) -> anyhow::Result<Vec<WorktreeInfo>> {- let stdout = self.run_command(&["worktree", "list", "--porcelain"])?;- let raw_worktrees = WorktreeInfo::parse_porcelain_list(&stdout)?;- let mut worktrees: Vec<_> = raw_worktrees.into_iter().filter(|wt| !wt.bare).collect();+ self.cache+ .worktrees+ .get_or_try_init(|| {+ let stdout = self.run_command(&["worktree", "list", "--porcelain"])?;+ let raw_worktrees = WorktreeInfo::parse_porcelain_list(&stdout)?;+ let mut worktrees: Vec<_> =+ raw_worktrees.into_iter().filter(|wt| !wt.bare).collect();- // Submodule path correction.- //- // Git's `get_main_worktree()` computes the main worktree path by stripping- // a trailing `/.git` from the common dir. For submodules, the common dir is- // `.git/modules/sub` (no trailing `/.git`), so git leaves it unchanged —- // reporting the git data directory as the "main worktree" path. Git does not- // consult `core.worktree` in this code path.- //- // We detect this by checking whether the first worktree's path equals- // git_common_dir (which never holds for normal repos, where git_common_dir- // is `.git` inside the worktree). When matched, we correct it using- // repo_path(), which reads `core.worktree` from the bulk config map.- //- // We fix this here rather than at each call site because list_worktrees()- // is the single point where worktree paths enter the system — all consumers- // (worktree_for_branch, current_worktree_info, resolve_worktree, etc.)- // depend on paths being working directories. If git fixes this upstream,- // the condition stops triggering.- if let Some(first) = worktrees.first_mut()- && canonicalize(&first.path).ok().as_deref() == Some(self.git_common_dir())- {- first.path = self.repo_path()?.to_path_buf();- }+ // Submodule path correction.+ //+ // Git's `get_main_worktree()` computes the main worktree path by stripping+ // a trailing `/.git` from the common dir. For submodules, the common dir is+ // `.git/modules/sub` (no trailing `/.git`), so git leaves it unchanged —+ // reporting the git data directory as the "main worktree" path. Git does not+ // consult `core.worktree` in this code path.+ //+ // We detect this by checking whether the first worktree's path equals+ // git_common_dir (which never holds for normal repos, where git_common_dir+ // is `.git` inside the worktree). When matched, we correct it using+ // repo_path(), which reads `core.worktree` from the bulk config map.+ //+ // We fix this here rather than at each call site because list_worktrees()+ // is the single point where worktree paths enter the system — all consumers+ // (worktree_for_branch, current_worktree_info, resolve_worktree, etc.)+ // depend on paths being working directories. If git fixes this upstream,+ // the condition stops triggering.+ if let Some(first) = worktrees.first_mut()+ && canonicalize(&first.path).ok().as_deref() == Some(self.git_common_dir())+ {+ first.path = self.repo_path()?.to_path_buf();+ }- Ok(worktrees)+ Ok(worktrees)+ })+ .cloned()}/// Get the WorktreeInfo struct for the current worktree, if we're inside one.