Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: leverage Repository caching to simplify worktree path functions (#526)
Maximilian Roos946fea53b6eb
diff --git a/.claude/rules/caching-strategy.md b/.claude/rules/caching-strategy.mdindex 4db590f7b..3986f1c82 100644--- a/.claude/rules/caching-strategy.md+++ b/.claude/rules/caching-strategy.md@@ -30,6 +30,7 @@ shares the cache — all clones see the same cached values.- `current_branch()` — per-worktree, keyed by path- `project_identifier()` — derived from remote URL- `primary_remote()` — git config, doesn't change+- `primary_remote_url()` — derived from primary_remote, doesn't change- `default_branch()` — from git config or detection, doesn't change- `integration_target()` — effective target for integration checks (local default or upstream if ahead)- `merge_base()` — keyed by (commit1, commit2) pairdiff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rsindex 26a7dcfb9..117da87a3 100644--- a/src/commands/list/collect.rs+++ b/src/commands/list/collect.rs@@ -78,7 +78,7 @@ use rayon_join_macro::join;use worktrunk::git::{LineDiff, Repository, WorktreeInfo};use worktrunk::styling::{INFO_SYMBOL, format_with_gutter, warning_message};-use crate::commands::is_worktree_at_expected_path_with;+use crate::commands::is_worktree_at_expected_path;use super::ci_status::PrStatus;use super::model::{@@ -713,12 +713,11 @@ pub fn collect(// Phase 2: Parallel fetch of independent git data// These operations don't depend on each other, only on worktree list.// Running them in parallel reduces pre-skeleton time (e.g., ~46ms to ~28ms).- let (default_branch, is_bare, branches_without_worktrees, remote_branches) = join!(+ let (default_branch, branches_without_worktrees, remote_branches) = join!(|| {repo.default_branch().context("Failed to determine default branch")},- || repo.is_bare().unwrap_or(false),|| {if show_branches {get_branches_without_worktrees(repo, &worktrees)@@ -812,9 +811,7 @@ pub fn collect(let is_previous = false;// Check if worktree is at its expected path based on config template- // Use optimized variant with pre-computed default_branch and is_bare- let branch_worktree_mismatch =- !is_worktree_at_expected_path_with(wt, repo, config, &default_branch, is_bare);+ let branch_worktree_mismatch = !is_worktree_at_expected_path(wt, repo, config);let mut worktree_data =WorktreeData::from_worktree(wt, is_main, is_current, is_previous);@@ -954,7 +951,8 @@ pub fn collect(// Effective target for integration checks: upstream if ahead of local, else local.// This handles the case where a branch was merged remotely but user hasn't pulled yet.// Deferred until after skeleton to avoid blocking initial render.- let integration_target = repo.effective_integration_target(&default_branch);+ // Uses cached integration_target() which computes the same value from default_branch().+ let integration_target = repo.integration_target()?;// Batch-fetch ahead/behind counts to identify branches that are far behind.// This allows skipping expensive merge-base operations for diverged branches, dramaticallydiff --git a/src/commands/mod.rs b/src/commands/mod.rsindex bdb3489ee..7d7bbe071 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -41,7 +41,7 @@ pub use step_commands::{};pub use worktree::{ResolutionContext, compute_worktree_path, handle_remove, handle_remove_current, handle_switch,- is_worktree_at_expected_path_with, resolve_worktree_arg, worktree_display_name,+ is_worktree_at_expected_path, resolve_worktree_arg, worktree_display_name,};// Re-export Shell from the canonical locationdiff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 10ee48172..b8664706f 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -188,14 +188,39 @@ pub fn resolve_worktree_arg(////// For the default branch, returns the repo root (main worktree location)./// For other branches, applies the `worktree-path` template from config.+///+/// Uses cached values from Repository for `default_branch` and `is_bare`.pub fn compute_worktree_path(repo: &Repository,branch: &str,config: &WorktrunkConfig,) -> anyhow::Result<PathBuf> {+ let repo_root = repo.worktree_base()?;let default_branch = repo.default_branch().unwrap_or_default();let is_bare = repo.is_bare()?;- compute_worktree_path_with(repo, branch, config, &default_branch, is_bare)++ // Default branch lives at repo root (main worktree), not a templated path.+ // Exception: bare repos have no main worktree, so all branches use templated paths.+ if !is_bare && branch == default_branch {+ return Ok(repo_root);+ }++ let repo_name = repo_root+ .file_name()+ .ok_or_else(|| anyhow::anyhow!("Repository path has no filename: {}", repo_root.display()))?+ .to_str()+ .ok_or_else(|| {+ anyhow::anyhow!(+ "Repository path contains invalid UTF-8: {}",+ repo_root.display()+ )+ })?;++ let relative_path = config+ .format_path(repo_name, branch)+ .map_err(|e| anyhow::anyhow!("Failed to format worktree path: {e}"))?;++ Ok(repo_root.join(relative_path).normalize())}/// Check if a worktree is at its expected path based on config template.@@ -204,18 +229,18 @@ pub fn compute_worktree_path(/// would generate for its branch. Detached HEAD always returns false (no expected path).////// Uses canonicalization to handle symlinks and relative paths correctly.-///-/// Note: For hot paths where default_branch and is_bare are already known,-/// use `is_worktree_at_expected_path_with` to avoid redundant git calls.-fn is_worktree_at_expected_path(+/// Uses cached values from Repository for `default_branch` and `is_bare`.+pub fn is_worktree_at_expected_path(wt: &worktrunk::git::WorktreeInfo,repo: &Repository,config: &WorktrunkConfig,) -> bool {- // Compute default_branch and is_bare once, then delegate to the optimized variant- let default_branch = repo.default_branch().unwrap_or_default();- let is_bare = repo.is_bare().unwrap_or(false);- is_worktree_at_expected_path_with(wt, repo, config, &default_branch, is_bare)+ match &wt.branch {+ Some(branch) => compute_worktree_path(repo, branch, config)+ .map(|expected| paths_match(&wt.path, &expected))+ .unwrap_or(false),+ None => false,+ }}/// Compare two paths for equality, canonicalizing to handle symlinks and relative paths.@@ -228,25 +253,6 @@ fn paths_match(a: &std::path::Path, b: &std::path::Path) -> bool {a_canonical == b_canonical}-/// Check if a worktree is at its expected path, with pre-computed values.-///-/// Use this when `default_branch` and `is_bare` are already known (e.g., in list command)-/// to avoid redundant git calls.-pub fn is_worktree_at_expected_path_with(- wt: &worktrunk::git::WorktreeInfo,- repo: &Repository,- config: &WorktrunkConfig,- default_branch: &str,- is_bare: bool,-) -> bool {- match &wt.branch {- Some(branch) => compute_worktree_path_with(repo, branch, config, default_branch, is_bare)- .map(|expected| paths_match(&wt.path, &expected))- .unwrap_or(false),- None => false,- }-}-/// Returns the expected path if `actual_path` differs from the template-computed path.////// Returns `Some(expected_path)` when there's a mismatch, `None` when paths match.@@ -262,43 +268,6 @@ pub fn get_path_mismatch(.filter(|expected| !paths_match(actual_path, expected))}-/// Optimized variant of `compute_worktree_path` that accepts pre-computed values.-///-/// Use this when `default_branch` and `is_bare` are already known to avoid-/// redundant git calls.-fn compute_worktree_path_with(- repo: &Repository,- branch: &str,- config: &WorktrunkConfig,- default_branch: &str,- is_bare: bool,-) -> anyhow::Result<PathBuf> {- let repo_root = repo.worktree_base()?;-- // Default branch lives at repo root (main worktree), not a templated path.- // Exception: bare repos have no main worktree, so all branches use templated paths.- if !is_bare && branch == default_branch {- return Ok(repo_root);- }-- let repo_name = repo_root- .file_name()- .ok_or_else(|| anyhow::anyhow!("Repository path has no filename: {}", repo_root.display()))?- .to_str()- .ok_or_else(|| {- anyhow::anyhow!(- "Repository path contains invalid UTF-8: {}",- repo_root.display()- )- })?;-- let relative_path = config- .format_path(repo_name, branch)- .map_err(|e| anyhow::anyhow!("Failed to format worktree path: {e}"))?;-- Ok(repo_root.join(relative_path).normalize())-}-/// Compute a user-facing display name for a worktree.////// Returns styled content with branch names bolded:diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 12668792b..f4b3c640c 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -41,6 +41,8 @@ struct RepoCache {integration_target: OnceCell<String>,/// Primary remote name (None if no remotes configured)primary_remote: OnceCell<Option<String>>,+ /// Primary remote URL (None if no remotes configured or no URL)+ primary_remote_url: OnceCell<Option<String>>,/// Project identifier derived from remote URLproject_identifier: OnceCell<String>,/// Base path for worktrees (repo root for normal repos, bare repo path for bare)@@ -538,10 +540,17 @@ impl Repository {}/// Get the URL for the primary remote, if configured.+ ///+ /// Result is cached in the repository's shared cache (same for all clones).pub fn primary_remote_url(&self) -> Option<String> {- self.primary_remote()- .ok()- .and_then(|remote| self.remote_url(&remote))+ self.cache+ .primary_remote_url+ .get_or_init(|| {+ self.primary_remote()+ .ok()+ .and_then(|remote| self.remote_url(&remote))+ })+ .clone()}/// Check if a local git branch exists.@@ -2075,10 +2084,8 @@ impl Repository {self.cache.project_identifier.get_or_try_init(|| {- // Try to get the remote URL first- if let Ok(remote) = self.primary_remote()- && let Some(url) = self.remote_url(&remote)- {+ // Try to get the remote URL first (cached)+ if let Some(url) = self.primary_remote_url() {if let Some(parsed) = GitRemoteUrl::parse(url.trim()) {return Ok(parsed.project_identifier());}