Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
perf: cache remote URLs, commit details, and diff stats in RepoCache (#2252)
Maximilian Rooscb6688ba125a
diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rsindex f4d2282a0..622c2daaf 100644--- a/src/git/repository/diff.rs+++ b/src/git/repository/diff.rs@@ -81,25 +81,35 @@ impl Repository {}/// Get commit timestamp and message in a single git command.+ ///+ /// Results are cached in the shared repo cache by commit SHA, so multiple+ /// items pointing at the same commit (e.g., worktrees on main) only run+ /// `git log -1` once.pub fn commit_details(&self, commit: &str) -> anyhow::Result<(i64, String)> {- // Use space separator - timestamps don't contain spaces, and %s (subject)- // is the first line only (no embedded newlines). Split on first space.- // --no-show-signature suppresses GPG verification output that otherwise- // contaminates stdout when log.showSignature is set.- let stdout = self.run_command(&[- "log",- "-1",- "--no-show-signature",- "--format=%ct %s",- commit,- ])?;- // Only strip trailing newline, not spaces (empty subject = "timestamp ")- let line = stdout.trim_end_matches('\n');- let (timestamp_str, message) = line- .split_once(' ')- .context("Failed to parse commit details")?;- let timestamp = timestamp_str.parse().context("Failed to parse timestamp")?;- Ok((timestamp, message.trim().to_owned()))+ use dashmap::mapref::entry::Entry;+ match self.cache.commit_details.entry(commit.to_string()) {+ Entry::Occupied(e) => Ok(e.get().clone()),+ Entry::Vacant(e) => {+ // Use space separator - timestamps don't contain spaces, and %s (subject)+ // is the first line only (no embedded newlines). Split on first space.+ // --no-show-signature suppresses GPG verification output that otherwise+ // contaminates stdout when log.showSignature is set.+ let stdout = self.run_command(&[+ "log",+ "-1",+ "--no-show-signature",+ "--format=%ct %s",+ commit,+ ])?;+ // Only strip trailing newline, not spaces (empty subject = "timestamp ")+ let line = stdout.trim_end_matches('\n');+ let (timestamp_str, message) = line+ .split_once(' ')+ .context("Failed to parse commit details")?;+ let timestamp = timestamp_str.parse().context("Failed to parse timestamp")?;+ Ok(e.insert((timestamp, message.trim().to_owned())).clone())+ }+ }}/// Get commit subjects (first line of commit message) from a range.@@ -294,17 +304,46 @@ impl Repository {////// For orphan branches with no common ancestor, returns zeros.pub fn branch_diff_stats(&self, base: &str, head: &str) -> anyhow::Result<LineDiff> {+ use dashmap::mapref::entry::Entry;+let base_sha = self.rev_parse_commit(base)?;let head_sha = self.rev_parse_commit(head)?;// Sparse checkout filters the diff by path, making the result- // environment-dependent rather than purely SHA-determined. Skip the- // persistent cache when sparse checkout is active.+ // environment-dependent rather than purely SHA-determined. Skip+ // caches when sparse checkout is active.let sparse_paths = self.sparse_checkout_paths();let use_cache = sparse_paths.is_empty();- if use_cache && let Some(cached) = super::sha_cache::diff_stats(self, &base_sha, &head_sha)- {+ if use_cache {+ // In-memory entry lock prevents parallel tasks from racing through+ // the file-based cache for the same SHA pair.+ match self+ .cache+ .diff_stats+ .entry((base_sha.clone(), head_sha.clone()))+ {+ Entry::Occupied(e) => return Ok(*e.get()),+ Entry::Vacant(e) => {+ let result =+ self.compute_branch_diff_stats(&base_sha, &head_sha, sparse_paths)?;+ return Ok(*e.insert(result));+ }+ }+ }++ self.compute_branch_diff_stats(&base_sha, &head_sha, sparse_paths)+ }++ fn compute_branch_diff_stats(+ &self,+ base_sha: &str,+ head_sha: &str,+ sparse_paths: &[String],+ ) -> anyhow::Result<LineDiff> {+ let use_cache = sparse_paths.is_empty();++ if use_cache && let Some(cached) = super::sha_cache::diff_stats(self, base_sha, head_sha) {return Ok(cached);}@@ -313,9 +352,9 @@ impl Repository {let _guard = super::super::HEAVY_OPS_SEMAPHORE.acquire();// Get merge-base (cached in shared repo cache)- let Some(merge_base) = self.merge_base(&base_sha, &head_sha)? else {+ let Some(merge_base) = self.merge_base(base_sha, head_sha)? else {if use_cache {- super::sha_cache::put_diff_stats(self, &base_sha, &head_sha, LineDiff::default());+ super::sha_cache::put_diff_stats(self, base_sha, head_sha, LineDiff::default());}return Ok(LineDiff::default());};@@ -331,7 +370,7 @@ impl Repository {let stdout = self.run_command(&args)?;let result = LineDiff::from_shortstat(&stdout);if use_cache {- super::sha_cache::put_diff_stats(self, &base_sha, &head_sha, result);+ super::sha_cache::put_diff_stats(self, base_sha, head_sha, result);}Ok(result)}diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex e83605e3e..d8fd31413 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -227,6 +227,10 @@ pub(super) struct RepoCache {/// Batch ahead/behind cache: (base_ref, branch_name) -> (ahead, behind)/// Populated by batch_ahead_behind(), used by cached_ahead_behind()pub(super) ahead_behind: DashMap<(String, String), (usize, usize)>,+ /// Raw remote URLs: remote_name -> URL from `.git/config` (no `url.insteadOf`).+ /// Cached because `primary_remote` validates the URL, then `primary_remote_url`+ /// reads it again — two calls for the same key without this cache.+ pub(super) remote_urls: DashMap<String, Option<String>>,/// Effective remote URLs: remote_name -> effective URL (with `url.insteadOf` applied)./// Cached because forge detection may query the same remote multiple times.pub(super) effective_remote_urls: DashMap<String, Option<String>>,@@ -253,6 +257,15 @@ pub(super) struct RepoCache {/// Used by `rev_parse_commit()` to key the persistent `sha_cache` by SHA.pub(super) commit_shas: DashMap<String, String>,+ /// 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.+ pub(super) commit_details: DashMap<String, (i64, String)>,+ /// In-memory branch diff stats cache: (base_sha, head_sha) -> LineDiff.+ /// Sits in front of the persistent `sha_cache` to prevent parallel tasks+ /// from racing through the file-based cache for the same SHA pair.+ pub(super) diff_stats: DashMap<(String, String), LineDiff>,+// ========== 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)diff --git a/src/git/repository/remotes.rs b/src/git/repository/remotes.rsindex 176721f0b..bffc621b3 100644--- a/src/git/repository/remotes.rs+++ b/src/git/repository/remotes.rs@@ -114,7 +114,7 @@ impl Repository {if let Ok(default_remote) = self.run_command(&["config", "checkout.defaultRemote"]){let default_remote = default_remote.trim();- if !default_remote.is_empty() && self.remote_has_url(default_remote) {+ if !default_remote.is_empty() && self.remote_url(default_remote).is_some() {return Some(default_remote.to_string());}}@@ -143,23 +143,24 @@ impl Repository {.ok_or_else(|| anyhow::anyhow!("No remotes configured"))}- /// Check if a remote has a URL configured.- fn remote_has_url(&self, remote: &str) -> bool {- self.run_command(&["config", &format!("remote.{}.url", remote)])- .map(|url| !url.trim().is_empty())- .unwrap_or(false)- }-/// Get the URL for a remote, if configured.////// Returns the raw value from `.git/config` without applying `url.insteadOf`/// rewrites. Use [`effective_remote_url`](Self::effective_remote_url) when you/// need forge detection to work with `insteadOf` aliases.+ ///+ /// Results are cached per-remote in the shared repo cache.pub fn remote_url(&self, remote: &str) -> Option<String> {- self.run_command(&["config", &format!("remote.{}.url", remote)])- .ok()- .map(|url| url.trim().to_string())- .filter(|url| !url.is_empty())+ self.cache+ .remote_urls+ .entry(remote.to_string())+ .or_insert_with(|| {+ self.run_command(&["config", &format!("remote.{}.url", remote)])+ .ok()+ .map(|url| url.trim().to_string())+ .filter(|url| !url.is_empty())+ })+ .clone()}/// Get the effective URL for a remote, with `url.insteadOf` rewrites applied.