Skip to content

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

refactor: simplify Repository caching to use Arc-based sharing (#521)

Maximilian Roos3bc243d76f93
diff --git a/.claude/rules/caching-strategy.md b/.claude/rules/caching-strategy.md
index 4206f331a..1661003b4 100644
--- a/.claude/rules/caching-strategy.md
+++ b/.claude/rules/caching-strategy.md
@@ -12,19 +12,18 @@ Everything else (remote URLs, project config, branch metadata) is read-only.
## Caching Implementation
-`Repository` uses a global cache keyed by `git_common_dir`. The cache is
-shared across all `Repository` instances within a process.
+`Repository` holds its cache directly via `Arc<RepoCache>`. Cloning a Repository
+shares the cache — all clones see the same cached values.
-**Architecture note:** Using a HashMap keyed by `git_common_dir` is slightly
-wasteful since every `Repository` instance must compute `git rev-parse
---git-common-dir` to look up the cache. However, tests require isolation (each
-test creates different repos that need their own cached values), and the
-HashMap approach is the simplest way to achieve this. Alternative approaches
-(test-only cache clearing with RwLock instead of OnceCell) have their own
-trade-offs.
+**Key patterns:**
+
+- **Command entry points** create Repository via `Repository::current()` or `Repository::at(path)`
+- **Parallel tasks** (e.g., `wt list`) clone the Repository, sharing the cache
+- **Tests** naturally get isolation since each test creates its own Repository
**Currently cached:**
-- `git_common_dir()` — cached per-instance (also used as HashMap key)
+
+- `git_common_dir` — computed at construction, stored on struct
- `worktree_root()` — per-worktree, keyed by path
- `worktree_base()` — derived from git_common_dir and is_bare
- `is_bare()` — git config, doesn't change
@@ -34,46 +33,35 @@ trade-offs.
- `default_branch()` — from git config or detection, doesn't change
- `merge_base()` — keyed by (commit1, commit2) pair
- `ahead_behind` — keyed by (base_ref, branch_name), populated by `batch_ahead_behind()`
+- `project_config` — loaded from .config/wt.toml
**Not cached (intentionally):**
+
- `is_dirty()` — changes as we stage/commit
- `list_worktrees()` — changes as we create/remove worktrees
**Adding new cached methods:**
1. Add field to `RepoCache` struct: `field_name: OnceCell<T>`
-2. Use `with_cache()` helper to access the shared cache
+2. Access via `self.cache.field_name`
3. Return owned values (String, PathBuf, bool)
```rust
-// For repo-wide values (same for all worktrees)
+// For repo-wide values (same for all clones)
pub fn cached_value(&self) -> anyhow::Result<String> {
- self.with_cache(|cache| {
- cache
- .field_name
- .get_or_init(|| { /* compute value */ })
- .clone()
- })
+ self.cache
+ .field_name
+ .get_or_init(|| { /* compute value */ })
+ .clone()
}
// For per-worktree values (different per worktree path)
-pub fn cached_per_worktree(&self) -> anyhow::Result<String> {
- let worktree_key = self.path.clone();
-
- self.with_cache(|cache| {
- // Check cache first
- if let Ok(map) = cache.field_name.read()
- && let Some(cached) = map.get(&worktree_key)
- {
- return cached.clone();
- }
-
- // Cache miss - compute and store
- let result = /* compute value */;
- if let Ok(mut map) = cache.field_name.write() {
- map.insert(worktree_key, result.clone());
- }
- result
- })
+// Use DashMap for concurrent access
+pub fn cached_per_worktree(&self, path: &Path) -> String {
+ self.cache
+ .field_name
+ .entry(path.to_path_buf())
+ .or_insert_with(|| { /* compute value */ })
+ .clone()
}
```
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
index 84422e657..7fe3006f1 100644
--- a/src/commands/list/collect.rs
+++ b/src/commands/list/collect.rs
@@ -262,10 +262,10 @@ impl TaskKind {
}
/// Detect if a worktree is in the middle of a git operation (rebase/merge).
-pub(super) fn detect_git_operation(repo: &Repository) -> GitOperationState {
- if repo.current_worktree().is_rebasing().unwrap_or(false) {
+pub(super) fn detect_git_operation(wt: &worktrunk::git::WorktreeView<'_>) -> GitOperationState {
+ if wt.is_rebasing().unwrap_or(false) {
GitOperationState::Rebase
- } else if repo.current_worktree().is_merging().unwrap_or(false) {
+ } else if wt.is_merging().unwrap_or(false) {
GitOperationState::Merge
} else {
GitOperationState::None
@@ -1026,8 +1026,9 @@ pub fn collect(
let default_branch_clone = default_branch.clone();
let target_clone = integration_target.clone();
let expected_results_clone = expected_results.clone();
- // Move options into the worker thread (not cloned - contains stale_branches set)
- let main_path = main_worktree.path.clone();
+
+ // Clone repo for the worker thread (shares cache via Arc)
+ let repo_clone = repo.clone();
// Prepare branch data if needed (before moving into closure)
let branch_data: Vec<(usize, String, String)> = if show_branches || show_remotes {
@@ -1063,6 +1064,7 @@ pub fn collect(
// Worktree work items
for (idx, wt) in sorted_worktrees_clone.iter().enumerate() {
all_work_items.extend(work_items_for_worktree(
+ &repo_clone,
wt,
idx,
&default_branch_clone,
@@ -1076,9 +1078,9 @@ pub fn collect(
// Branch work items (local + remote)
for (item_idx, branch_name, commit_sha) in &branch_data {
all_work_items.extend(work_items_for_branch(
+ &repo_clone,
branch_name,
commit_sha,
- &main_path,
*item_idx,
&default_branch_clone,
&target_clone,
@@ -1407,12 +1409,14 @@ pub fn build_worktree_item(
/// with: commit details, ahead/behind, diffs, upstream, CI, etc.
///
/// # Parameters
+/// - `repo`: Repository handle (cloned into background thread, shares cache via Arc)
/// - `default_branch`: Local default branch for informational stats (ahead/behind, branch diff)
/// - `target`: Effective target for integration checks (may be upstream if ahead)
///
/// This is the blocking version used by statusline. For progressive rendering
/// with callbacks, see the `collect()` function.
pub fn populate_item(
+ repo: &Repository,
item: &mut ListItem,
default_branch: &str,
target: &str,
@@ -1444,6 +1448,7 @@ pub fn populate_item(
locked: None,
prunable: None,
};
+ let repo_clone = repo.clone();
let default_branch_clone = default_branch.to_string();
let target_clone = target.to_string();
let expected_results_clone = expected_results.clone();
@@ -1454,6 +1459,7 @@ pub fn populate_item(
// Generate work items for this single worktree
let mut work_items = work_items_for_worktree(
+ &repo_clone,
&wt,
0, // Single item, always index 0
&default_branch_clone,
diff --git a/src/commands/list/collect_progressive_impl.rs b/src/commands/list/collect_progressive_impl.rs
index 4f5201a9a..c14b51fcf 100644
--- a/src/commands/list/collect_progressive_impl.rs
+++ b/src/commands/list/collect_progressive_impl.rs
@@ -75,10 +75,23 @@ pub struct CollectOptions {
/// Context for task computation. Cloned and moved into spawned threads.
///
-/// Contains all data needed by any task.
+/// Contains all data needed by any task. The `repo` field shares its cache
+/// across all clones via `Arc<RepoCache>`, so parallel tasks benefit from
+/// cached merge-base results, ahead/behind counts, etc.
#[derive(Clone)]
pub struct TaskContext {
- pub repo_path: PathBuf,
+ /// Shared repository handle. All clones share the same cache via Arc.
+ pub repo: Repository,
+ /// Path to the specific worktree this task operates on.
+ ///
+ /// For worktree-specific operations, use `self.worktree()` which calls
+ /// `repo.worktree_at(&worktree_path)`.
+ ///
+ /// **Important:** For branch-only items (branches without worktrees), this
+ /// is an empty `PathBuf`. Tasks that require worktree-specific operations
+ /// (e.g., `WorkingTreeDiffTask`) are only spawned for items with worktrees,
+ /// so the empty path case never reaches those tasks.
+ pub worktree_path: PathBuf,
pub commit_sha: String,
pub branch: Option<String>,
/// Local default branch for informational stats (ahead/behind, branch diff).
@@ -94,10 +107,11 @@ pub struct TaskContext {
}
impl TaskContext {
- fn repo(&self, kind: TaskKind) -> Result<Repository, TaskError> {
- // Background tasks need Repository discovered from their specific worktree path,
- // not from base_path(). Each task operates on a potentially different worktree.
- Repository::at(&self.repo_path).map_err(|e| self.error(kind, e))
+ /// Get a worktree view for this task's worktree path.
+ ///
+ /// Use this for worktree-specific operations (git status, working tree diff).
+ fn worktree(&self) -> worktrunk::git::WorktreeView<'_> {
+ self.repo.worktree_at(&self.worktree_path)
}
fn error(&self, kind: TaskKind, message: impl Display) -> TaskError {
@@ -202,7 +216,11 @@ const EXPENSIVE_TASKS: &[TaskKind] = &[
/// Returns a list of work items representing all tasks that should run for this
/// worktree. Expected results are registered internally as each work item is added.
/// The caller is responsible for executing the work items.
+///
+/// The `repo` parameter is cloned into each TaskContext, sharing its cache via Arc.
+#[allow(clippy::too_many_arguments)]
pub fn work_items_for_worktree(
+ repo: &Repository,
wt: &Worktree,
item_idx: usize,
default_branch: &str,
@@ -239,7 +257,8 @@ pub fn work_items_for_worktree(
}
let ctx = TaskContext {
- repo_path: wt.path.clone(),
+ repo: repo.clone(),
+ worktree_path: wt.path.clone(),
commit_sha: wt.head.clone(),
branch: wt.branch.clone(),
default_branch: Some(default_branch.to_string()),
@@ -309,11 +328,13 @@ pub fn work_items_for_worktree(
///
/// Returns a list of work items representing all tasks that should run for this
/// branch. Branches have fewer tasks than worktrees (no working tree operations).
+///
+/// The `repo` parameter is cloned into each TaskContext, sharing its cache via Arc.
#[allow(clippy::too_many_arguments)]
pub fn work_items_for_branch(
+ repo: &Repository,
branch_name: &str,
commit_sha: &str,
- repo_path: &std::path::Path,
item_idx: usize,
default_branch: &str,
target: &str,
@@ -323,7 +344,8 @@ pub fn work_items_for_branch(
let skip = &options.skip_tasks;
let ctx = TaskContext {
- repo_path: repo_path.to_path_buf(),
+ repo: repo.clone(),
+ worktree_path: PathBuf::new(), // Branches without worktrees use empty path
commit_sha: commit_sha.to_string(),
branch: Some(branch_name.to_string()),
default_branch: Some(default_branch.to_string()),
@@ -382,7 +404,7 @@ impl Task for CommitDetailsTask {
const KIND: TaskKind = TaskKind::CommitDetails;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let repo = ctx.repo(Self::KIND)?;
+ let repo = &ctx.repo;
let timestamp = repo
.commit_timestamp(&ctx.commit_sha)
.map_err(|e| ctx.error(Self::KIND, e))?;
@@ -407,7 +429,7 @@ impl Task for AheadBehindTask {
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
let base = ctx.require_default_branch(Self::KIND)?;
- let repo = ctx.repo(Self::KIND)?;
+ let repo = &ctx.repo;
// Check cache first (populated by batch_ahead_behind if it ran).
// Cache lookup has minor overhead (rev-parse for cache key + allocations),
@@ -441,7 +463,7 @@ impl Task for CommittedTreesMatchTask {
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
let base = ctx.require_target(Self::KIND)?;
- let repo = ctx.repo(Self::KIND)?;
+ let repo = &ctx.repo;
// Use ctx.commit_sha (the item's commit) instead of HEAD,
// since for branches without worktrees, HEAD is the main worktree's HEAD
let committed_trees_match = repo
@@ -479,7 +501,7 @@ impl Task for HasFileChangesTask {
});
};
let target = ctx.require_target(Self::KIND)?;
- let repo = ctx.repo(Self::KIND)?;
+ let repo = &ctx.repo;
let has_file_changes = repo
.has_added_changes(branch, target)
.map_err(|e| ctx.error(Self::KIND, e))?;
@@ -516,7 +538,7 @@ impl Task for WouldMergeAddTask {
});
};
let base = ctx.require_target(Self::KIND)?;
- let repo = ctx.repo(Self::KIND)?;
+ let repo = &ctx.repo;
let would_merge_add = repo
.would_merge_add_to_target(branch, base)
.map_err(|e| ctx.error(Self::KIND, e))?;
@@ -542,7 +564,7 @@ impl Task for IsAncestorTask {
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
let base = ctx.require_target(Self::KIND)?;
- let repo = ctx.repo(Self::KIND)?;
+ let repo = &ctx.repo;
let is_ancestor = repo
.is_ancestor(&ctx.commit_sha, base)
.map_err(|e| ctx.error(Self::KIND, e))?;
@@ -562,7 +584,7 @@ impl Task for BranchDiffTask {
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
let base = ctx.require_default_branch(Self::KIND)?;
- let repo = ctx.repo(Self::KIND)?;
+ let repo = &ctx.repo;
let diff = repo
.branch_diff_stats(base, &ctx.commit_sha)
.map_err(|e| ctx.error(Self::KIND, e))?;
@@ -581,10 +603,10 @@ impl Task for WorkingTreeDiffTask {
const KIND: TaskKind = TaskKind::WorkingTreeDiff;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let repo = ctx.repo(Self::KIND)?;
+ let wt = ctx.worktree();
// Use --no-optional-locks to avoid index lock contention with WorkingTreeConflictsTask's
// `git stash create` which needs the index lock.
- let status_output = repo
+ let status_output = wt
.run_command(&["--no-optional-locks", "status", "--porcelain"])
.map_err(|e| ctx.error(Self::KIND, e))?;
@@ -592,14 +614,14 @@ impl Task for WorkingTreeDiffTask {
parse_working_tree_status(&status_output);
let working_tree_diff = if is_dirty {
- repo.working_tree_diff_stats()
+ wt.working_tree_diff_stats()
.map_err(|e| ctx.error(Self::KIND, e))?
} else {
LineDiff::default()
};
// Use default_branch (local default branch) for informational display
- let working_tree_diff_with_main = repo
+ let working_tree_diff_with_main = wt
.working_tree_diff_with_base(ctx.default_branch.as_deref(), is_dirty)
.map_err(|e| ctx.error(Self::KIND, e))?;
@@ -624,7 +646,7 @@ impl Task for MergeTreeConflictsTask {
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
let base = ctx.require_default_branch(Self::KIND)?;
- let repo = ctx.repo(Self::KIND)?;
+ let repo = &ctx.repo;
let has_merge_tree_conflicts = repo
.has_merge_conflicts(base, &ctx.commit_sha)
.map_err(|e| ctx.error(Self::KIND, e))?;
@@ -647,11 +669,11 @@ impl Task for WorkingTreeConflictsTask {
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
let base = ctx.require_default_branch(Self::KIND)?;
- let repo = ctx.repo(Self::KIND)?;
+ let wt = ctx.worktree();
// Use --no-optional-locks to avoid index lock contention with WorkingTreeDiffTask.
// Both tasks run in parallel, and `git stash create` below needs the index lock.
- let status_output = repo
+ let status_output = wt
.run_command(&["--no-optional-locks", "status", "--porcelain"])
.map_err(|e| ctx.error(Self::KIND, e))?;
@@ -670,7 +692,7 @@ impl Task for WorkingTreeConflictsTask {
//
// Note: stash create fails when there are unmerged files (merge conflict in progress).
// In that case, fall back to the commit-based check.
- let stash_result = repo.run_command(&["stash", "create"]);
+ let stash_result = wt.run_command(&["stash", "create"]);
let stash_sha = match stash_result {
Ok(sha) => sha,
@@ -694,8 +716,9 @@ impl Task for WorkingTreeConflictsTask {
});
}
- // Run merge-tree with the stash commit
- let has_conflicts = repo
+ // Run merge-tree with the stash commit (repo-wide operation, doesn't need worktree)
+ let has_conflicts = ctx
+ .repo
.has_merge_conflicts(base, stash_sha)
.map_err(|e| ctx.error(Self::KIND, e))?;
@@ -713,8 +736,8 @@ impl Task for GitOperationTask {
const KIND: TaskKind = TaskKind::GitOperation;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let repo = ctx.repo(Self::KIND)?;
- let git_operation = detect_git_operation(&repo);
+ let wt = ctx.worktree();
+ let git_operation = detect_git_operation(&wt);
Ok(TaskResult::GitOperation {
item_idx: ctx.item_idx,
git_operation,
@@ -729,7 +752,7 @@ impl Task for UserMarkerTask {
const KIND: TaskKind = TaskKind::UserMarker;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let repo = ctx.repo(Self::KIND)?;
+ let repo = &ctx.repo;
let user_marker = repo.user_marker(ctx.branch.as_deref());
Ok(TaskResult::UserMarker {
item_idx: ctx.item_idx,
@@ -745,7 +768,7 @@ impl Task for UpstreamTask {
const KIND: TaskKind = TaskKind::Upstream;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let repo = ctx.repo(Self::KIND)?;
+ let repo = &ctx.repo;
// No branch means no upstream
let Some(branch) = ctx.branch.as_deref() else {
@@ -793,10 +816,10 @@ impl Task for CiStatusTask {
const KIND: TaskKind = TaskKind::CiStatus;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let repo = ctx.repo(Self::KIND)?;
+ let repo = &ctx.repo;
let pr_status = ctx.branch.as_deref().and_then(|branch| {
let has_upstream = repo.upstream_branch(branch).ok().flatten().is_some();
- PrStatus::detect(&repo, branch, &ctx.commit_sha, has_upstream)
+ PrStatus::detect(repo, branch, &ctx.commit_sha, has_upstream)
});
Ok(TaskResult::CiStatus {
diff --git a/src/commands/statusline.rs b/src/commands/statusline.rs
index da8a15929..41b5cacf4 100644
--- a/src/commands/statusline.rs
+++ b/src/commands/statusline.rs
@@ -306,7 +306,13 @@ fn get_git_status_segments(
// Compute everything (same as --full) for complete status symbols
// Pass default_branch for stable informational stats,
// and integration_target for integration status checks.
- list::populate_item(&mut item, &default_branch, &integration_target, options)?;
+ list::populate_item(
+ repo,
+ &mut item,
+ &default_branch,
+ &integration_target,
+ options,
+ )?;
// Get prioritized segments
let segments = item.format_statusline_segments(include_links);
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 9a473ab6e..ebfeb5c75 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -1,10 +1,9 @@
-use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Command;
-use std::sync::{Arc, OnceLock, RwLock};
+use std::sync::{Arc, OnceLock};
use dashmap::DashMap;
-use once_cell::sync::{Lazy, OnceCell};
+use once_cell::sync::OnceCell;
use anyhow::{Context, bail};
use normalize_path::NormalizePath;
@@ -20,41 +19,9 @@ use super::{
};
// ============================================================================
-// Global Cache
+// Repository Cache
// ============================================================================
-/// Global cache keyed by `git_common_dir`.
-///
-/// NOTE: Using a HashMap is slightly wasteful since every Repository instance
-/// must compute `git rev-parse --git-common-dir` to look up the cache. However,
-/// tests require isolation (each test creates different repos that need their
-/// own cached values), and the HashMap approach is the simplest way to achieve
-/// this. Alternative approaches (test-only cache clearing with RwLock instead
-/// of OnceCell) have their own trade-offs.
-static REPO_CACHE: Lazy<RwLock<HashMap<PathBuf, Arc<RepoCache>>>> = Lazy::new(Default::default);
-
-/// Get the shared cache for a repository, creating it if needed.
-///
-/// Returns an Arc to the cache, allowing the caller to release the HashMap
-/// lock before accessing cached values. This prevents deadlocks when cached
-/// methods call each other.
-fn get_cache(key: PathBuf) -> Arc<RepoCache> {
- // Try read-only first
- {
- let caches = REPO_CACHE.read().unwrap();
- if let Some(cache) = caches.get(&key) {
- return Arc::clone(cache);
- }
- }
-
- // Cache miss - need write lock to insert
- let mut caches = REPO_CACHE.write().unwrap();
- let cache = caches
- .entry(key)
- .or_insert_with(|| Arc::new(RepoCache::default()));
- Arc::clone(cache)
-}
-
/// Cached data for a single repository.
///
/// Contains:
@@ -159,8 +126,9 @@ pub struct Repository {
/// For repo-wide operations, any path within the repo works.
discovery_path: PathBuf,
/// The shared .git directory, computed at construction time.
- /// Used as key for global cache lookup.
git_common_dir: PathBuf,
+ /// Cached data for this repository. Shared across clones via Arc.
+ cache: Arc<RepoCache>,
}
/// A view into a specific worktree within a repository.
@@ -245,11 +213,11 @@ impl<'a> WorktreeView<'a> {
/// Get the branch checked out in this worktree, or None if in detached HEAD state.
///
- /// Result is cached in the global shared cache (keyed by worktree path).
+ /// Result is cached in the repository's shared cache (keyed by worktree path).
pub fn branch(&self) -> anyhow::Result<Option<String>> {
- let cache = get_cache(self.repo.git_common_dir.clone());
-
- Ok(cache
+ Ok(self
+ .repo
+ .cache
.current_branches
.entry(self.path.clone())
.or_insert_with(|| {
@@ -277,11 +245,11 @@ impl<'a> WorktreeView<'a> {
///
/// Returns the canonicalized absolute path to the top-level directory.
/// This could be the main worktree or a linked worktree.
- /// Result is cached in the global shared cache (keyed by worktree path).
+ /// Result is cached in the repository's shared cache (keyed by worktree path).
pub fn root(&self) -> anyhow::Result<PathBuf> {
- let cache = get_cache(self.repo.git_common_dir.clone());
-
- Ok(cache
+ Ok(self
+ .repo
+ .cache
.worktree_roots
.entry(self.path.clone())
.or_insert_with(|| {
@@ -352,6 +320,59 @@ impl<'a> WorktreeView<'a> {
}
Ok(())
}
+
+ /// Get line diff statistics for working tree changes (unstaged + staged).
+ pub fn working_tree_diff_stats(&self) -> anyhow::Result<LineDiff> {
+ let stdout = self.run_command(&["diff", "--numstat", "HEAD"])?;
+ LineDiff::from_numstat(&stdout)
+ }
+
+ /// Get line diff statistics between working tree and a specific ref.
+ pub fn working_tree_diff_vs_ref(&self, ref_name: &str) -> anyhow::Result<LineDiff> {
+ let stdout = self.run_command(&["diff", "--numstat", ref_name])?;
+ LineDiff::from_numstat(&stdout)
+ }
+
+ /// Get working tree diff stats vs a base branch, if trees differ.
+ ///
+ /// When `base_branch` is `None` (main worktree), returns `Some(LineDiff::default())`.
+ /// If the base branch tree matches HEAD and the working tree is dirty, computes
+ /// the precise diff; otherwise returns zero to indicate trees match.
+ /// When trees differ, returns `None` so callers can skip expensive comparisons.
+ pub fn working_tree_diff_with_base(
+ &self,
+ base_branch: Option<&str>,
+ working_tree_dirty: bool,
+ ) -> anyhow::Result<Option<LineDiff>> {
+ let Some(branch) = base_branch else {
+ // Main worktree has no base to compare against
+ return Ok(Some(LineDiff::default()));
+ };
+
+ // Check if branch exists
+ if self
+ .run_command(&["rev-parse", "--verify", branch])
+ .is_err()
+ {
+ return Ok(None);
+ }
+
+ // Check if trees match
+ let trees_match = self
+ .run_command(&["diff-tree", "--quiet", "HEAD", branch])
+ .is_ok();
+
+ if trees_match {
+ // Trees identical - if working tree is dirty, compute the diff
+ if working_tree_dirty {
+ Ok(Some(self.working_tree_diff_vs_ref(branch)?))
+ } else {
+ Ok(Some(LineDiff::default()))
+ }
+ } else {
+ Ok(None)
+ }
+ }
}
impl Repository {
@@ -368,24 +389,36 @@ impl Repository {
/// Discover the repository from the specified path.
///
- /// **For background tasks and tests only.** Inline production code should use
- /// [`Repository::current()`] combined with [`Repository::worktree_at()`] for
- /// worktree-specific operations.
+ /// Creates a new Repository with its own cache. For sharing cache across
+ /// operations (e.g., parallel tasks in `wt list`), clone an existing
+ /// Repository instead of calling `at()` multiple times.
///
/// Use cases:
- /// - **Background tasks**: Tasks spawned to operate on specific worktrees
- /// (e.g., `wt list` tasks that analyze each worktree in parallel)
- /// - **Tests**: Tests run from the project directory but need to operate on
- /// test repositories in temporary directories
+ /// - **Command entry points**: Starting a new command that needs a Repository
+ /// - **Tests**: Tests that need to operate on test repositories
+ ///
+ /// For worktree-specific operations within an existing Repository context,
+ /// use [`Repository::worktree_at()`] instead.
pub fn at(path: impl Into<PathBuf>) -> anyhow::Result<Self> {
let discovery_path = path.into();
let git_common_dir = Self::resolve_git_common_dir(&discovery_path)?;
Ok(Self {
discovery_path,
git_common_dir,
+ cache: Arc::new(RepoCache::default()),
})
}
+ /// Check if this repository shares its cache with another.
+ ///
+ /// Returns true if both repositories point to the same underlying cache.
+ /// This is primarily useful for testing that cloned repositories share
+ /// cached data.
+ #[doc(hidden)]
+ pub fn shares_cache_with(&self, other: &Repository) -> bool {
+ Arc::ptr_eq(&self.cache, &other.cache)
+ }
+
/// Resolve the git common directory for a path.
// TODO: Consolidate the "Failed to execute: git ..." context pattern.
// Currently duplicated in WorktreeView::run_command, Repository::run_command, and here.
@@ -453,8 +486,7 @@ impl Repository {
///
/// [1]: https://git-scm.com/docs/git-config#Documentation/git-config.txt-checkoutdefaultRemote
pub fn primary_remote(&self) -> anyhow::Result<String> {
- let cache = get_cache(self.git_common_dir.clone());
- cache
+ self.cache
.primary_remote
.get_or_init(|| {
// Check git's checkout.defaultRemote config
@@ -778,8 +810,7 @@ impl Repository {
/// Detection results are cached to `worktrunk.default-branch` for future calls.
/// Result is cached in the shared repo cache (shared across all worktrees).
pub fn default_branch(&self) -> anyhow::Result<String> {
- let cache = get_cache(self.git_common_dir.clone());
- cache
+ self.cache
.default_branch
.get_or_try_init(|| {
// Fast path: check worktrunk's persistent cache (git config)
@@ -927,10 +958,9 @@ impl Repository {
/// For bare repositories: the bare repository directory itself.
///
/// This is the path that should be used when constructing worktree paths.
- /// Result is cached in the global shared cache (same for all worktrees in a repo).
+ /// Result is cached in the repository's shared cache (same for all clones).
pub fn worktree_base(&self) -> anyhow::Result<PathBuf> {
- let cache = get_cache(self.git_common_dir.clone());
- cache
+ self.cache
.worktree_base
.get_or_try_init(|| {
let git_common_dir =
@@ -978,10 +1008,9 @@ impl Repository {
///
/// Bare repositories have no main worktree — all worktrees are linked
/// worktrees at templated paths, including the default branch.
- /// Result is cached in the shared repo cache (shared across all worktrees).
+ /// Result is cached in the repository's shared cache (same for all clones).
pub fn is_bare(&self) -> anyhow::Result<bool> {
- let cache = get_cache(self.git_common_dir.clone());
- cache
+ self.cache
.is_bare
.get_or_try_init(|| {
let output = self.run_command(&["config", "--bool", "core.bare"])?;
@@ -1320,9 +1349,6 @@ impl Repository {
}
};
- // Get cache keyed by git_common_dir
- let cache = Some(get_cache(self.git_common_dir().to_path_buf()));
-
let results: std::collections::HashMap<String, (usize, usize)> = output
.lines()
.filter_map(|line| {
@@ -1332,11 +1358,9 @@ impl Repository {
let ahead: usize = parts.next()?.parse().ok()?;
let branch = parts.next()?.to_string();
// Cache each result for later lookup
- if let Some(ref cache) = cache {
- cache
- .ahead_behind
- .insert((base.to_string(), branch.clone()), (ahead, behind));
- }
+ self.cache
+ .ahead_behind
+ .insert((base.to_string(), branch.clone()), (ahead, behind));
Some((branch, (ahead, behind)))
})
.collect();
@@ -1349,8 +1373,7 @@ impl Repository {
/// 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 get_cached_ahead_behind(&self, base: &str, branch: &str) -> Option<(usize, usize)> {
- let cache = get_cache(self.git_common_dir().to_path_buf());
- cache
+ self.cache
.ahead_behind
.get(&(base.to_string(), branch.to_string()))
.map(|r| *r)
@@ -1753,9 +1776,8 @@ impl Repository {
(commit2.to_string(), commit1.to_string())
};
- let cache = get_cache(self.git_common_dir.clone());
-
- Ok(cache
+ Ok(self
+ .cache
.merge_base
.entry(key)
.or_insert_with(|| {
@@ -2028,10 +2050,9 @@ impl Repository {
/// This identifier is used to track which commands have been approved
/// for execution in this project.
///
- /// Result is cached in the shared repo cache (shared across all worktrees).
+ /// Result is cached in the repository's shared cache (same for all clones).
pub fn project_identifier(&self) -> anyhow::Result<String> {
- let cache = get_cache(self.git_common_dir.clone());
- cache
+ self.cache
.project_identifier
.get_or_try_init(|| {
// Try to get the remote URL first
@@ -2076,11 +2097,10 @@ impl Repository {
/// Load the project configuration (.config/wt.toml) if it exists.
///
- /// Result is cached in the global shared cache (same config for all worktrees).
+ /// Result is cached in the repository's shared cache (same for all clones).
/// Returns `None` if not in a worktree or if no config file exists.
pub fn load_project_config(&self) -> anyhow::Result<Option<ProjectConfig>> {
- let cache = get_cache(self.git_common_dir.clone());
- cache
+ self.cache
.project_config
.get_or_try_init(|| {
match self.current_worktree().root() {
diff --git a/tests/integration_tests/cache_sharing.rs b/tests/integration_tests/cache_sharing.rs
new file mode 100644
index 000000000..750e0889b
--- /dev/null
+++ b/tests/integration_tests/cache_sharing.rs
@@ -0,0 +1,117 @@
+//! Tests for Repository cache sharing.
+//!
+//! These tests verify that when Repository is cloned, the cache is shared
+//! across clones via Arc. This is important for performance in `wt list`
+//! where parallel tasks share cached git data.
+
+use rstest::rstest;
+use worktrunk::git::Repository;
+
+mod common {
+ pub use crate::common::*;
+}
+use common::{TestRepo, repo};
+
+/// Test that cloning a Repository shares the same cache via Arc.
+#[rstest]
+fn test_repository_clone_shares_cache(repo: TestRepo) {
+ let repo1 = Repository::at(repo.root_path()).unwrap();
+ let repo2 = repo1.clone();
+
+ // Both should point to the same cache (Arc pointer equality)
+ assert!(
+ repo1.shares_cache_with(&repo2),
+ "Cloned repositories should share the same cache"
+ );
+}
+
+/// Test that cached values computed by one clone are visible to another.
+#[rstest]
+fn test_cache_shared_between_clones(repo: TestRepo) {
+ let repo1 = Repository::at(repo.root_path()).unwrap();
+ let repo2 = repo1.clone();
+
+ // Call default_branch() on repo1 - this caches the result
+ let default1 = repo1.default_branch().unwrap();
+
+ // Call default_branch() on repo2 - should return cached value
+ let default2 = repo2.default_branch().unwrap();
+
+ assert_eq!(default1, default2);
+ assert_eq!(default1, "main"); // TestRepo uses main as default branch
+}
+
+/// Test that merge_base cache is shared across clones.
+#[rstest]
+fn test_merge_base_cache_shared(mut repo: TestRepo) {
+ // Create a branch with a commit
+ repo.add_worktree("feature");
+ let feature_path = repo.worktree_path("feature");
+ repo.commit_in_worktree(feature_path, "feature.txt", "content", "feature commit");
+
+ let repo1 = Repository::at(repo.root_path()).unwrap();
+ let repo2 = repo1.clone();
+
+ // Get HEAD commits
+ let main_head = repo.head_sha();
+ let feature_head = repo.head_sha_in(feature_path);
+
+ // Call merge_base on repo1 - caches the result
+ let base1 = repo1.merge_base(&main_head, &feature_head).unwrap();
+
+ // Call merge_base on repo2 - should use cached value
+ let base2 = repo2.merge_base(&main_head, &feature_head).unwrap();
+
+ assert_eq!(base1, base2);
+ // The merge base should be main's HEAD since feature branched from there
+ assert_eq!(base1, main_head);
+}
+
+/// Test that parallel tasks share the cache when cloning Repository.
+#[rstest]
+fn test_parallel_tasks_share_cache(mut repo: TestRepo) {
+ use std::thread;
+
+ // Create multiple worktrees
+ repo.add_worktree("feature-a");
+ repo.add_worktree("feature-b");
+
+ let repo1 = Repository::at(repo.root_path()).unwrap();
+
+ // Spawn threads that clone the repo and access cached values
+ let handles: Vec<_> = (0..4)
+ .map(|i| {
+ let repo_clone = repo1.clone();
+ thread::spawn(move || {
+ // Each thread accesses the same cached default_branch
+ let default = repo_clone.default_branch().unwrap();
+ (i, default)
+ })
+ })
+ .collect();
+
+ // All threads should get the same cached value
+ let results: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();
+ for (_, branch) in &results {
+ assert_eq!(branch, "main");
+ }
+}
+
+/// Test that separate Repository instances (not clones) have separate caches.
+#[rstest]
+fn test_separate_repositories_have_separate_caches(repo: TestRepo) {
+ // Create two separate Repository instances (not clones)
+ let repo1 = Repository::at(repo.root_path()).unwrap();
+ let repo2 = Repository::at(repo.root_path()).unwrap();
+
+ // They should NOT share the same cache
+ assert!(
+ !repo1.shares_cache_with(&repo2),
+ "Separately created repositories should have independent caches"
+ );
+
+ // But they should compute the same values
+ let default1 = repo1.default_branch().unwrap();
+ let default2 = repo2.default_branch().unwrap();
+ assert_eq!(default1, default2);
+}
diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rs
index 4ef3fcf70..bb7bcf0ca 100644
--- a/tests/integration_tests/mod.rs
+++ b/tests/integration_tests/mod.rs
@@ -12,6 +12,7 @@ pub mod approval_save;
pub mod approval_ui;
pub mod approvals;
pub mod bare_repository;
+pub mod cache_sharing;
pub mod ci_status;
pub mod column_alignment_verification;
pub mod completion;