Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
perf: cache git_dir() to eliminate redundant rev-parse calls (#1957)
Maximilian Roosa389b942d345
diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rsindex 4429d8dfb..50006870d 100644--- a/src/git/repository/diff.rs+++ b/src/git/repository/diff.rs@@ -3,6 +3,7 @@use std::collections::HashMap;use anyhow::{Context, bail};+use dashmap::mapref::entry::Entry;use super::{DiffStats, LineDiff, Repository};@@ -154,28 +155,27 @@ impl Repository {(commit2.to_string(), commit1.to_string())};- // Check cache first- if let Some(cached) = self.cache.merge_base.get(&key) {- return Ok(cached.clone());+ match self.cache.merge_base.entry(key) {+ Entry::Occupied(e) => Ok(e.get().clone()),+ Entry::Vacant(e) => {+ // Exit codes: 0 = found, 1 = no common ancestor, 128+ = invalid ref+ let output = self.run_command_output(&["merge-base", commit1, commit2])?;++ let result = if output.status.success() {+ Some(String::from_utf8_lossy(&output.stdout).trim().to_owned())+ } else if output.status.code() == Some(1) {+ None+ } else {+ let stderr = String::from_utf8_lossy(&output.stderr);+ bail!(+ "git merge-base failed for {commit1} {commit2}: {}",+ stderr.trim()+ );+ };++ Ok(e.insert(result).clone())+ }}-- // Exit codes: 0 = found, 1 = no common ancestor, 128+ = invalid ref- let output = self.run_command_output(&["merge-base", commit1, commit2])?;-- let result = if output.status.success() {- Some(String::from_utf8_lossy(&output.stdout).trim().to_owned())- } else if output.status.code() == Some(1) {- None- } else {- let stderr = String::from_utf8_lossy(&output.stderr);- bail!(- "git merge-base failed for {commit1} {commit2}: {}",- stderr.trim()- );- };-- self.cache.merge_base.insert(key, result.clone());- Ok(result)}/// Calculate commits ahead and behind between two refs.diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 4365880f7..6740a3f83 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -115,6 +115,26 @@ fn stream_exit_result(////// Wrapped in Arc to allow releasing the outer HashMap lock before accessing/// cached values, avoiding deadlocks when cached methods call each other.+///+/// # Cache access patterns+///+/// Repo-wide values use `OnceCell::get_or_init` / `get_or_try_init` — single+/// initialization, no key.+///+/// Per-worktree and keyed values use `DashMap` with explicit `Entry` matching:+///+/// ```rust,ignore+/// match self.cache.some_map.entry(key) {+/// Entry::Occupied(e) => Ok(e.get().clone()),+/// Entry::Vacant(e) => {+/// let value = compute()?; // errors propagate naturally+/// Ok(e.insert(value).clone())+/// }+/// }+/// ```+///+/// This holds the shard lock across check-and-insert (no TOCTOU gap) and+/// propagates errors via `?` without swallowing them into fallbacks.#[derive(Debug, Default)]pub(super) struct RepoCache {// ========== Repo-wide values (same for all worktrees) ==========@@ -158,6 +178,9 @@ pub(super) struct RepoCache {pub(super) resolved_refs: DashMap<String, String>,// ========== Per-worktree values (keyed by path) ==========+ /// Per-worktree git directory: worktree_path -> canonicalized git dir+ /// (e.g., `.git/worktrees/<name>` for linked worktrees, `.git` for main)+ pub(super) git_dirs: DashMap<PathBuf, PathBuf>,/// Worktree root paths: worktree_path -> canonicalized rootpub(super) worktree_roots: DashMap<PathBuf, PathBuf>,/// Current branch per worktree: worktree_path -> branch name (None = detached HEAD)diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex fc3865497..e5db1661d 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -3,6 +3,7 @@use std::path::{Path, PathBuf};use anyhow::{Context, bail};+use dashmap::mapref::entry::Entry;use crate::shell_exec::Cmd;use dunce::canonicalize;@@ -119,30 +120,24 @@ impl<'a> WorkingTree<'a> {/// Result is cached in the repository's shared cache (keyed by worktree path)./// Errors (e.g., permission denied, corrupted `.git`) are propagated, not swallowed.pub fn branch(&self) -> anyhow::Result<Option<String>> {- // Check cache first- if let Some(cached) = self.repo.cache.current_branches.get(&self.path) {- return Ok(cached.clone());+ match self.repo.cache.current_branches.entry(self.path.clone()) {+ Entry::Occupied(e) => Ok(e.get().clone()),+ Entry::Vacant(e) => {+ // rev-parse --symbolic-full-name returns "refs/heads/<branch>" on a branch,+ // or "HEAD" when detached. Fails on unborn branches (no commits yet),+ // so fall back to symbolic-ref which works in all cases except detached HEAD.+ let result = match self.run_command(&["rev-parse", "--symbolic-full-name", "HEAD"])+ {+ Ok(stdout) => stdout.trim().strip_prefix("refs/heads/").map(str::to_owned),+ Err(_) => self+ .run_command(&["symbolic-ref", "--short", "HEAD"])+ .ok()+ .map(|s| s.trim().to_owned()),+ };++ Ok(e.insert(result).clone())+ }}-- // Not cached - use plumbing command to get current branch.- // rev-parse --symbolic-full-name returns "refs/heads/<branch>" on a branch,- // or "HEAD" when detached. Fails on unborn branches (no commits yet),- // so fall back to symbolic-ref which works in all cases except detached HEAD.- let result = match self.run_command(&["rev-parse", "--symbolic-full-name", "HEAD"]) {- Ok(stdout) => stdout.trim().strip_prefix("refs/heads/").map(str::to_owned),- Err(_) => self- .run_command(&["symbolic-ref", "--short", "HEAD"])- .ok()- .map(|s| s.trim().to_owned()),- };-- // Cache the successful result- self.repo- .cache- .current_branches- .insert(self.path.clone(), result.clone());-- Ok(result)}/// Check if the working tree has uncommitted changes.@@ -164,36 +159,45 @@ impl<'a> WorkingTree<'a> {/// This could be the main worktree or a linked worktree./// Result is cached in the repository's shared cache (keyed by worktree path).pub fn root(&self) -> anyhow::Result<PathBuf> {- Ok(self- .repo- .cache- .worktree_roots- .entry(self.path.clone())- .or_insert_with(|| {- self.run_command(&["rev-parse", "--show-toplevel"])+ match self.repo.cache.worktree_roots.entry(self.path.clone()) {+ Entry::Occupied(e) => Ok(e.get().clone()),+ Entry::Vacant(e) => {+ let root = self+ .run_command(&["rev-parse", "--show-toplevel"]).ok().map(|s| PathBuf::from(s.trim())).and_then(|p| canonicalize(&p).ok())- .unwrap_or_else(|| self.path.clone())- })- .clone())+ .unwrap_or_else(|| self.path.clone());++ Ok(e.insert(root).clone())+ }+ }}/// Get the git directory (may be different from common-dir in worktrees).////// Always returns a canonicalized absolute path, resolving symlinks./// This ensures consistent comparison with `git_common_dir()`.+ /// Result is cached in the repository's shared cache (keyed by worktree path).pub fn git_dir(&self) -> anyhow::Result<PathBuf> {- let stdout = self.run_command(&["rev-parse", "--git-dir"])?;- let path = PathBuf::from(stdout.trim());-- // Always canonicalize to resolve symlinks (e.g., /var -> /private/var on macOS)- let absolute_path = if path.is_relative() {- self.path.join(&path)- } else {- path- };- canonicalize(&absolute_path).context("Failed to resolve git directory")+ match self.repo.cache.git_dirs.entry(self.path.clone()) {+ Entry::Occupied(e) => Ok(e.get().clone()),+ Entry::Vacant(e) => {+ let stdout = self.run_command(&["rev-parse", "--git-dir"])?;+ let path = PathBuf::from(stdout.trim());++ // Always canonicalize to resolve symlinks (e.g., /var -> /private/var on macOS)+ let absolute_path = if path.is_relative() {+ self.path.join(&path)+ } else {+ path+ };+ let resolved =+ canonicalize(&absolute_path).context("Failed to resolve git directory")?;++ Ok(e.insert(resolved).clone())+ }+ }}/// Check if a rebase is in progress.