Skip to content

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

Add Repository caching to reduce git subprocess spawns (#287)

Maximilian Roos6c8e37052590
diff --git a/.claude/rules/caching-strategy.md b/.claude/rules/caching-strategy.md
new file mode 100644
index 000000000..c924724be
--- /dev/null
+++ b/.claude/rules/caching-strategy.md
@@ -0,0 +1,52 @@
+# Repository Caching Strategy
+
+## What Changes During Execution?
+
+Most data is stable for the duration of a command. The only things worktrunk modifies are:
+
+- **Worktree list** — `wt switch --create`, `wt remove` create/remove worktrees
+- **Working tree state** — `wt merge` commits, stages files
+- **Git config** — `wt config` modifies settings
+
+Everything else (remote URLs, project config, branch metadata) is read-only.
+
+## Caching Implementation
+
+`Repository` uses `OnceCell` for per-instance caching. Since instances are short-lived (command duration), we can cache aggressively:
+
+**Currently cached:**
+- `git_common_dir()` — never changes
+- `worktree_root()` — never changes
+- `worktree_base()` — derived from git_common_dir and is_bare
+- `is_bare()` — git config, doesn't change
+- `current_branch()` — we don't switch branches within a worktree
+- `project_identifier()` — derived from remote URL
+- `primary_remote()` — git config, doesn't change
+
+**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 `get_or_try_init()` pattern for fallible initialization
+3. Return `&T` (for references) or `.copied()`/`.cloned()` (for values)
+
+```rust
+// Return reference (avoids allocation)
+pub fn cached_ref(&self) -> anyhow::Result<&str> {
+ self.cache
+ .field_name
+ .get_or_try_init(|| { /* compute String */ })
+ .map(String::as_str)
+}
+
+// Return owned value (when caller needs ownership)
+pub fn cached_value(&self) -> anyhow::Result<bool> {
+ self.cache
+ .field_name
+ .get_or_try_init(|| { /* compute bool */ })
+ .copied()
+}
+```
diff --git a/Cargo.lock b/Cargo.lock
index 89bbabd93..e695d268c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3096,6 +3096,7 @@ dependencies = [
"minijinja",
"nix 0.30.1",
"normalize-path",
+ "once_cell",
"osc8",
"pathdiff",
"portable-pty",
diff --git a/Cargo.toml b/Cargo.toml
index 5a65c0cf4..22bfecc39 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -96,6 +96,7 @@ unicode-width = "0.2"
wrap-ansi = "0.1"
osc8 = "0.1.0"
home = "0.5.12"
+once_cell = "1.21"
dirs = "6.0"
normalize-path = "0.2.1"
pathdiff = "0.2"
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rs
index f5aea406b..c9ddc4e25 100644
--- a/src/commands/command_approval.rs
+++ b/src/commands/command_approval.rs
@@ -201,5 +201,5 @@ pub fn approve_hooks_filtered(
}
let project_id = ctx.repo.project_identifier()?;
- approve_command_batch(&commands, &project_id, ctx.config, ctx.force, false)
+ approve_command_batch(&commands, project_id, ctx.config, ctx.force, false)
}
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 7b39d830e..292cb1ef3 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -95,9 +95,9 @@ pub fn build_hook_context(
}
if let Ok(remote) = ctx.repo.primary_remote() {
- map.insert("remote".into(), remote.clone());
+ map.insert("remote".into(), remote.to_string());
// Add remote URL for conditional hook execution (e.g., GitLab vs GitHub)
- if let Ok(url) = ctx.repo.run_command(&["remote", "get-url", &remote]) {
+ if let Ok(url) = ctx.repo.run_command(&["remote", "get-url", remote]) {
map.insert("remote_url".into(), url.trim().into());
}
if let Some(branch) = ctx.branch
diff --git a/src/commands/config.rs b/src/commands/config.rs
index 28e847931..33524ff01 100644
--- a/src/commands/config.rs
+++ b/src/commands/config.rs
@@ -720,7 +720,7 @@ pub fn handle_state_get(key: &str, refresh: bool, branch: Option<String>) -> any
}
let has_upstream = repo.upstream_branch(&branch_name).ok().flatten().is_some();
- let ci_status = PrStatus::detect(&branch_name, &head, &repo_root, has_upstream)
+ let ci_status = PrStatus::detect(&branch_name, &head, repo_root, has_upstream)
.map_or(super::list::ci_status::CiStatus::NoCI, |s| s.ci_status);
let status_str: &'static str = ci_status.into();
crate::output::data(status_str)?;
diff --git a/src/commands/context.rs b/src/commands/context.rs
index 3b72b516f..99c4a44f1 100644
--- a/src/commands/context.rs
+++ b/src/commands/context.rs
@@ -57,7 +57,8 @@ impl CommandEnv {
// Propagate git errors (broken repo, missing git) but allow None for detached HEAD
let branch = repo
.current_branch()
- .context("Failed to determine current branch")?;
+ .context("Failed to determine current branch")?
+ .map(str::to_string);
let config = WorktrunkConfig::load().context("Failed to load config")?;
let repo_root = repo
.worktree_base()
diff --git a/src/commands/list/collect_progressive_impl.rs b/src/commands/list/collect_progressive_impl.rs
index 8487aa317..7ca5870dd 100644
--- a/src/commands/list/collect_progressive_impl.rs
+++ b/src/commands/list/collect_progressive_impl.rs
@@ -15,7 +15,7 @@
use crossbeam_channel::Sender;
use std::fmt::Display;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::sync::Arc;
use worktrunk::git::{LineDiff, Repository, Worktree};
@@ -525,6 +525,7 @@ impl Task for CiStatusTask {
let repo_path = repo
.worktree_root()
.ok()
+ .map(Path::to_path_buf)
.unwrap_or_else(|| ctx.repo_path.clone());
let pr_status = ctx.branch.as_deref().and_then(|branch| {
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index f23807c87..32da5d586 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -55,7 +55,7 @@ impl<'a> MergeCommandCollector<'a> {
let mut all_commands = Vec::new();
let project_config = match self.repo.load_project_config()? {
Some(cfg) => cfg,
- None => return Ok((all_commands, self.repo.project_identifier()?)),
+ None => return Ok((all_commands, self.repo.project_identifier()?.to_string())),
};
// Collect original commands (not expanded) for approval
@@ -79,7 +79,7 @@ impl<'a> MergeCommandCollector<'a> {
all_commands.extend(collect_commands_for_hooks(&project_config, &hooks));
- let project_id = self.repo.project_identifier()?;
+ let project_id = self.repo.project_identifier()?.to_string();
Ok((all_commands, project_id))
}
}
@@ -231,7 +231,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
repo.ensure_clean_working_tree(Some("remove worktree after merge"), Some(&current_branch))?;
// STEP 2: Remove worktree via shared remove output handler so final message matches wt remove
- let worktree_root = repo.worktree_root()?;
+ let worktree_root = repo.worktree_root()?.to_path_buf();
// After a successful merge, compute integration reason from main_path
let main_repo = worktrunk::git::Repository::at(&destination_path);
let effective_target = main_repo.effective_integration_target(&target_branch);
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index f1b46f8d9..ed32b2aef 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -61,14 +61,14 @@ pub trait RepositoryCliExt {
impl RepositoryCliExt for Repository {
fn load_project_config(&self) -> anyhow::Result<Option<ProjectConfig>> {
let repo_root = self.worktree_root()?;
- load_project_config_at(&repo_root)
+ load_project_config_at(repo_root)
}
fn require_project_config(&self) -> anyhow::Result<ProjectConfig> {
let repo_root = self.worktree_root()?;
let config_path = repo_root.join(".config").join("wt.toml");
- match load_project_config_at(&repo_root)? {
+ match load_project_config_at(repo_root)? {
Some(cfg) => Ok(cfg),
None => Err(GitError::ProjectConfigNotFound { config_path }.into()),
}
@@ -124,7 +124,7 @@ impl RepositoryCliExt for Repository {
let target_repo = Repository::at(&worktree_path);
target_repo.ensure_clean_working_tree(Some("remove worktree"), Some(branch_name))?;
- let current_worktree = self.worktree_root()?;
+ let current_worktree = self.worktree_root()?.to_path_buf();
let removing_current = current_worktree == worktree_path;
// Cannot remove the main working tree (only linked worktrees can be removed)
@@ -185,7 +185,7 @@ impl RepositoryCliExt for Repository {
}
// Get current worktree path
- let current_path = self.worktree_root()?;
+ let current_path = self.worktree_root()?.to_path_buf();
// Find this worktree in the list to get its metadata
let worktrees = self.list_worktrees()?;
diff --git a/src/commands/standalone.rs b/src/commands/standalone.rs
index b91153e2d..67b8db6d2 100644
--- a/src/commands/standalone.rs
+++ b/src/commands/standalone.rs
@@ -434,7 +434,7 @@ pub fn step_show_squash_prompt(
let target_branch = repo.resolve_target_branch(target)?;
// Get current branch
- let current_branch = repo.current_branch()?.unwrap_or_else(|| "HEAD".to_string());
+ let current_branch = repo.current_branch()?.unwrap_or("HEAD");
// Get merge base with target branch
let merge_base = repo.merge_base("HEAD", &target_branch)?;
@@ -454,7 +454,7 @@ pub fn step_show_squash_prompt(
&target_branch,
&merge_base,
&subjects,
- &current_branch,
+ current_branch,
repo_name,
config,
)?;
@@ -573,7 +573,7 @@ pub fn add_approvals(show_all: bool) -> anyhow::Result<()> {
let commands_to_approve = if !show_all {
let unapproved: Vec<_> = commands
.into_iter()
- .filter(|cmd| !config.is_command_approved(&project_id, &cmd.template))
+ .filter(|cmd| !config.is_command_approved(project_id, &cmd.template))
.collect();
if unapproved.is_empty() {
@@ -590,7 +590,7 @@ pub fn add_approvals(show_all: bool) -> anyhow::Result<()> {
// When show_all=true, we've already included all commands in commands_to_approve
// When show_all=false, we've already filtered to unapproved commands
// So we pass skip_approval_filter=true to prevent double-filtering
- let approved = approve_command_batch(&commands_to_approve, &project_id, &config, false, true)?;
+ let approved = approve_command_batch(&commands_to_approve, project_id, &config, false, true)?;
// Show result
if approved {
@@ -630,7 +630,7 @@ pub fn clear_approvals(global: bool) -> anyhow::Result<()> {
let project_id = repo.project_identifier()?;
// Check if project has any approvals
- let had_approvals = config.projects.contains_key(&project_id);
+ let had_approvals = config.projects.contains_key(project_id);
if !had_approvals {
crate::output::print(info_message("No approvals to clear for this project"))?;
@@ -640,12 +640,12 @@ pub fn clear_approvals(global: bool) -> anyhow::Result<()> {
// Count approvals before removing
let approval_count = config
.projects
- .get(&project_id)
+ .get(project_id)
.map(|p| p.approved_commands.len())
.unwrap_or(0);
config
- .revoke_project(&project_id)
+ .revoke_project(project_id)
.context("Failed to clear project approvals")?;
crate::output::print(success_message(format!(
@@ -700,7 +700,7 @@ pub fn handle_hook_show(hook_type_filter: Option<&str>, expanded: bool) -> anyho
&repo,
project_config.as_ref(),
&config,
- project_id.as_deref(),
+ project_id,
filter,
ctx.as_ref(),
)?;
diff --git a/src/commands/statusline.rs b/src/commands/statusline.rs
index 262252456..eb71bdc43 100644
--- a/src/commands/statusline.rs
+++ b/src/commands/statusline.rs
@@ -218,7 +218,7 @@ fn get_git_status(repo: &Repository, cwd: &Path) -> Result<Option<String>> {
let Some(wt) = current_worktree else {
// Not in a worktree - just show branch name
if let Ok(Some(branch)) = repo.current_branch() {
- return Ok(Some(branch));
+ return Ok(Some(branch.to_string()));
}
return Ok(None);
};
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 5a30dc822..9efeb8143 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -151,7 +151,7 @@ pub fn resolve_worktree_arg(
match name {
"@" => {
// Current worktree by path - works even in detached HEAD
- let path = repo.worktree_root()?;
+ let path = repo.worktree_root()?.to_path_buf();
let worktrees = repo.list_worktrees()?;
let branch = worktrees
.worktrees
@@ -557,7 +557,7 @@ pub fn handle_switch(
// Branch-first lookup: check if branch has a worktree anywhere
match repo.worktree_for_branch(&resolved_branch)? {
Some(existing_path) if existing_path.exists() => {
- let _ = repo.record_switch_previous(new_previous.as_deref());
+ let _ = repo.record_switch_previous(new_previous);
return Ok(switch_to_existing(existing_path));
}
Some(_) => {
@@ -720,7 +720,7 @@ pub fn handle_switch(
// (see main.rs switch handler for temporal locality)
// Record successful switch in history for `wt switch -` support
- let _ = repo.record_switch_previous(new_previous.as_deref());
+ let _ = repo.record_switch_previous(new_previous);
Ok((
SwitchResult::Created {
@@ -808,7 +808,8 @@ pub fn handle_remove_by_path(
// We're not in this worktree, so no directory change needed
let current_path = repo
.worktree_root()
- .context("Failed to determine current worktree")?;
+ .context("Failed to determine current worktree")?
+ .to_path_buf();
Ok(RemoveResult::RemovedWorktree {
main_path: current_path,
diff --git a/src/completion.rs b/src/completion.rs
index 51841bf68..c169d0f62 100644
--- a/src/completion.rs
+++ b/src/completion.rs
@@ -243,7 +243,7 @@ fn complete_hook_commands() -> Vec<CompletionCandidate> {
// Load project config and add project hook names
let repo = Repository::current();
if let Ok(repo_root) = repo.worktree_root()
- && let Ok(Some(project_config)) = ProjectConfig::load(&repo_root)
+ && let Ok(Some(project_config)) = ProjectConfig::load(repo_root)
{
let project_command_config = match hook_type {
"post-create" => &project_config.post_create,
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 3f0fc234f..df981e1e2 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -2,6 +2,8 @@ use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;
+use once_cell::sync::OnceCell;
+
use anyhow::{Context, bail};
use normalize_path::NormalizePath;
@@ -53,15 +55,22 @@ fn base_path() -> &'static PathBuf {
.unwrap_or_else(|| DEFAULT.get_or_init(|| PathBuf::from(".")))
}
-/// Internal layout information for a repository.
+/// Cached values for expensive git queries.
///
-/// Cached to avoid repeated git queries.
-#[derive(Debug, Clone)]
-struct RepositoryLayout {
+/// These values don't change during a process run, so we cache them
+/// after the first lookup to avoid repeated git command spawns.
+/// See `.claude/rules/caching-strategy.md` for what should/shouldn't be cached.
+#[derive(Debug, Default)]
+struct RepoCache {
+ git_common_dir: OnceCell<PathBuf>,
+ worktree_root: OnceCell<PathBuf>,
+ current_branch: OnceCell<Option<String>>,
+ primary_remote: OnceCell<String>,
+ project_identifier: OnceCell<String>,
/// Base path for worktrees (repo root for normal repos, bare repo path for bare repos)
- worktree_base: PathBuf,
+ worktree_base: OnceCell<PathBuf>,
/// Whether this is a bare repository
- is_bare: bool,
+ is_bare: OnceCell<bool>,
}
/// Repository context for git operations.
@@ -82,7 +91,7 @@ struct RepositoryLayout {
#[derive(Debug)]
pub struct Repository {
path: PathBuf,
- layout: OnceLock<RepositoryLayout>,
+ cache: RepoCache,
}
impl Repository {
@@ -90,7 +99,7 @@ impl Repository {
pub fn at(path: impl Into<PathBuf>) -> Self {
Self {
path: path.into(),
- layout: OnceLock::new(),
+ cache: RepoCache::default(),
}
}
@@ -107,91 +116,48 @@ impl Repository {
&self.path
}
- /// Get the repository layout, initializing it if needed.
- fn layout(&self) -> anyhow::Result<&RepositoryLayout> {
- if let Some(layout) = self.layout.get() {
- return Ok(layout);
- }
-
- let git_common_dir =
- canonicalize(&self.git_common_dir()?).context("Failed to canonicalize path")?;
-
- let is_bare = self.is_bare_repo()?;
-
- let worktree_base = if is_bare {
- git_common_dir.clone()
- } else {
- git_common_dir
- .parent()
- .ok_or_else(|| {
- anyhow::Error::from(GitError::Other {
- message: format!(
- "Git directory has no parent: {}",
- git_common_dir.display()
- ),
- })
- })?
- .to_path_buf()
- };
-
- let layout = RepositoryLayout {
- worktree_base,
- is_bare,
- };
-
- // set() returns Err if already set, but we checked above, so ignore the result
- let _ = self.layout.set(layout);
-
- // Now get() will succeed
- Ok(self.layout.get().unwrap())
- }
-
- /// Check if this is a bare repository (no working tree).
- fn is_bare_repo(&self) -> anyhow::Result<bool> {
- let output = self.run_command(&["config", "--bool", "core.bare"])?;
- Ok(output.trim() == "true")
- }
-
/// Get the primary remote name for this repository.
///
+ /// Returns a consistent value across all worktrees (not branch-specific).
+ ///
/// Uses the following strategy:
- /// 1. If the current branch has an upstream, use its remote
- /// (Note: Detached HEAD falls through to step 2)
- /// 2. Use git's `checkout.defaultRemote` config if set and has a URL
- /// 3. Otherwise, get the first remote with a configured URL
- /// 4. Fall back to "origin" if no remotes exist
- pub fn primary_remote(&self) -> anyhow::Result<String> {
- // Try to get the remote from HEAD's upstream (single command)
- // @{u} refers to the upstream of the current branch
- if let Ok(upstream) = self.run_command(&["rev-parse", "--abbrev-ref", "@{u}"])
- && let Some((remote, _)) = upstream.trim().split_once('/')
- {
- return Ok(remote.to_string());
- }
-
- // Check git's checkout.defaultRemote config
- 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) {
- return Ok(default_remote.to_string());
- }
- }
+ /// 1. Use git's [`checkout.defaultRemote`][1] config if set and has a URL
+ /// 2. Otherwise, get the first remote with a configured URL
+ /// 3. Fall back to "origin" if no remotes exist
+ ///
+ /// Result is cached for the lifetime of this Repository instance.
+ ///
+ /// [1]: https://git-scm.com/docs/git-config#Documentation/git-config.txt-checkoutdefaultRemote
+ pub fn primary_remote(&self) -> anyhow::Result<&str> {
+ self.cache
+ .primary_remote
+ .get_or_try_init(|| {
+ // Check git's checkout.defaultRemote config
+ 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) {
+ return Ok(default_remote.to_string());
+ }
+ }
- // Fall back to first remote with a configured URL
- // Use git config to find remotes with URLs, filtering out phantom remotes
- // from global config (e.g., `remote.origin.prunetags=true` without a URL)
- let output = self
- .run_command(&["config", "--get-regexp", r"remote\..+\.url"])
- .unwrap_or_default();
- let first_remote = output.lines().next().and_then(|line| {
- // Parse "remote.<name>.url <value>" format
- // Use ".url " as delimiter to handle remote names with dots (e.g., "my.remote")
- line.strip_prefix("remote.")
- .and_then(|s| s.split_once(".url "))
- .map(|(name, _)| name)
- });
+ // Fall back to first remote with a configured URL
+ // Use git config to find remotes with URLs, filtering out phantom remotes
+ // from global config (e.g., `remote.origin.prunetags=true` without a URL)
+ let output = self
+ .run_command(&["config", "--get-regexp", r"remote\..+\.url"])
+ .unwrap_or_default();
+ let first_remote = output.lines().next().and_then(|line| {
+ // Parse "remote.<name>.url <value>" format
+ // Use ".url " as delimiter to handle remote names with dots (e.g., "my.remote")
+ line.strip_prefix("remote.")
+ .and_then(|s| s.split_once(".url "))
+ .map(|(name, _)| name)
+ });
- Ok(first_remote.unwrap_or("origin").to_string())
+ Ok(first_remote.unwrap_or("origin").to_string())
+ })
+ .map(String::as_str)
}
/// Check if a remote has a URL configured.
@@ -254,22 +220,27 @@ impl Repository {
}
/// Get the current branch name, or None if in detached HEAD state.
- pub fn current_branch(&self) -> anyhow::Result<Option<String>> {
- let stdout = self.run_command(&["branch", "--show-current"])?;
- let branch = stdout.trim();
-
- if branch.is_empty() {
- Ok(None) // Detached HEAD
- } else {
- Ok(Some(branch.to_string()))
- }
+ /// Result is cached for the lifetime of this Repository instance.
+ pub fn current_branch(&self) -> anyhow::Result<Option<&str>> {
+ self.cache
+ .current_branch
+ .get_or_try_init(|| {
+ let stdout = self.run_command(&["branch", "--show-current"])?;
+ let branch = stdout.trim();
+ Ok(if branch.is_empty() {
+ None // Detached HEAD
+ } else {
+ Some(branch.to_string())
+ })
+ })
+ .map(|opt| opt.as_deref())
}
/// Get the current branch name, or error if in detached HEAD state.
///
/// `action` describes what requires being on a branch (e.g., "merge").
pub fn require_current_branch(&self, action: &str) -> anyhow::Result<String> {
- self.current_branch()?.ok_or_else(|| {
+ self.current_branch()?.map(str::to_string).ok_or_else(|| {
GitError::DetachedHead {
action: Some(action.into()),
}
@@ -341,7 +312,7 @@ impl Repository {
/// - `Err` if "-" but no previous branch in history
pub fn resolve_worktree_name(&self, name: &str) -> anyhow::Result<String> {
match name {
- "@" => self.current_branch()?.ok_or_else(|| {
+ "@" => self.current_branch()?.map(str::to_string).ok_or_else(|| {
GitError::DetachedHead {
action: Some("resolve '@' to current branch".into()),
}
@@ -384,7 +355,7 @@ impl Repository {
match name {
"@" => {
// Current worktree by path - works even in detached HEAD
- let path = self.worktree_root()?;
+ let path = self.worktree_root()?.to_path_buf();
let worktrees = self.list_worktrees()?;
let branch = worktrees
.worktrees
@@ -446,12 +417,12 @@ impl Repository {
// Try to get from the primary remote
if let Ok(remote) = self.primary_remote() {
// Try git's cache for this remote (e.g., origin/HEAD)
- if let Ok(branch) = self.get_local_default_branch(&remote) {
+ if let Ok(branch) = self.get_local_default_branch(remote) {
return Ok(branch);
}
// Query remote (no caching to git's remote HEAD - we only manage worktrunk's cache)
- if let Ok(branch) = self.query_remote_default_branch(&remote) {
+ if let Ok(branch) = self.query_remote_default_branch(remote) {
return Ok(branch);
}
}
@@ -524,17 +495,28 @@ impl Repository {
/// Get the git common directory (the actual .git directory for the repository).
///
+ /// For linked worktrees, this returns the shared `.git` directory in the main
+ /// worktree, not the per-worktree `.git/worktrees/<name>` directory.
+ /// See [`--git-common-dir`][1] for details.
+ ///
/// Always returns an absolute path, resolving any relative paths returned by git.
- pub fn git_common_dir(&self) -> anyhow::Result<PathBuf> {
- let stdout = self.run_command(&["rev-parse", "--git-common-dir"])?;
- let path = PathBuf::from(stdout.trim());
-
- // Resolve relative paths against the repo's directory
- if path.is_relative() {
- canonicalize(self.path.join(&path)).context("Failed to resolve git common directory")
- } else {
- Ok(path)
- }
+ /// Result is cached for the lifetime of this Repository instance.
+ ///
+ /// [1]: https://git-scm.com/docs/git-rev-parse#Documentation/git-rev-parse.txt---git-common-dir
+ pub fn git_common_dir(&self) -> anyhow::Result<&Path> {
+ self.cache
+ .git_common_dir
+ .get_or_try_init(|| {
+ let stdout = self.run_command(&["rev-parse", "--git-common-dir"])?;
+ let path = PathBuf::from(stdout.trim());
+ if path.is_relative() {
+ canonicalize(self.path.join(&path))
+ .context("Failed to resolve git common directory")
+ } else {
+ Ok(path)
+ }
+ })
+ .map(PathBuf::as_path)
}
/// Get the git directory (may be different from common-dir in worktrees).
@@ -558,16 +540,46 @@ 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 for the lifetime of this Repository instance.
pub fn worktree_base(&self) -> anyhow::Result<PathBuf> {
- Ok(self.layout()?.worktree_base.clone())
+ self.cache
+ .worktree_base
+ .get_or_try_init(|| {
+ let git_common_dir =
+ canonicalize(self.git_common_dir()?).context("Failed to canonicalize path")?;
+
+ if self.is_bare()? {
+ Ok(git_common_dir)
+ } else {
+ git_common_dir
+ .parent()
+ .ok_or_else(|| {
+ anyhow::Error::from(GitError::Other {
+ message: format!(
+ "Git directory has no parent: {}",
+ git_common_dir.display()
+ ),
+ })
+ })
+ .map(Path::to_path_buf)
+ }
+ })
+ .cloned()
}
/// Check if this is a bare repository (no working tree).
///
/// Bare repositories have no main worktree — all worktrees are linked
/// worktrees at templated paths, including the default branch.
+ /// Result is cached for the lifetime of this Repository instance.
pub fn is_bare(&self) -> anyhow::Result<bool> {
- Ok(self.layout()?.is_bare)
+ self.cache
+ .is_bare
+ .get_or_try_init(|| {
+ let output = self.run_command(&["config", "--bool", "core.bare"])?;
+ Ok(output.trim() == "true")
+ })
+ .copied()
}
/// Check if the working tree has uncommitted changes.
@@ -600,10 +612,16 @@ impl Repository {
///
/// Returns the canonicalized absolute path to the top-level directory of the
/// current working tree. This could be the main worktree or a linked worktree.
- pub fn worktree_root(&self) -> anyhow::Result<PathBuf> {
- let stdout = self.run_command(&["rev-parse", "--show-toplevel"])?;
- let path = PathBuf::from(stdout.trim());
- canonicalize(&path).context("Failed to canonicalize worktree root")
+ /// Result is cached for the lifetime of this Repository instance.
+ pub fn worktree_root(&self) -> anyhow::Result<&Path> {
+ self.cache
+ .worktree_root
+ .get_or_try_init(|| {
+ let stdout = self.run_command(&["rev-parse", "--show-toplevel"])?;
+ let path = PathBuf::from(stdout.trim());
+ canonicalize(&path).context("Failed to canonicalize worktree root")
+ })
+ .map(PathBuf::as_path)
}
/// Check if the path is in a worktree (vs the main repository).
@@ -648,6 +666,10 @@ impl Repository {
}
/// Check if base is an ancestor of head (i.e., would be a fast-forward).
+ ///
+ /// See [`--is-ancestor`][1] for details.
+ ///
+ /// [1]: https://git-scm.com/docs/git-merge-base#Documentation/git-merge-base.txt---is-ancestor
pub fn is_ancestor(&self, base: &str, head: &str) -> anyhow::Result<bool> {
self.run_command_check(&["merge-base", "--is-ancestor", base, head])
}
@@ -664,8 +686,10 @@ impl Repository {
/// Check if a branch has file changes beyond the merge-base with target.
///
- /// Uses three-dot diff (`target...branch`) which shows files changed from merge-base
- /// to branch. Returns false when the diff is empty (no added changes).
+ /// Uses [three-dot diff][1] (`target...branch`) which shows files changed from
+ /// merge-base to branch. Returns false when the diff is empty (no added changes).
+ ///
+ /// [1]: https://git-scm.com/docs/git-diff#Documentation/git-diff.txt-emgitdiffemltoptionsgtltcommitgtltcommitgt--telepathhellip
pub fn has_added_changes(&self, branch: &str, target: &str) -> anyhow::Result<bool> {
// git diff --name-only target...branch shows files changed from merge-base to branch
let range = format!("{target}...{branch}");
@@ -770,6 +794,10 @@ impl Repository {
}
/// Get the upstream tracking branch for the given branch.
+ ///
+ /// Uses [`@{upstream}` syntax][1] to resolve the tracking branch.
+ ///
+ /// [1]: https://git-scm.com/docs/gitrevisions#Documentation/gitrevisions.txt-emltaboranchgtemuaboranchgtupaboranchgtupstream
pub fn upstream_branch(&self, branch: &str) -> anyhow::Result<Option<String>> {
let result = self.run_command(&["rev-parse", "--abbrev-ref", &format!("{}@{{u}}", branch)]);
@@ -1150,9 +1178,7 @@ impl Repository {
local_branches.iter().map(|(n, _)| n.clone()).collect();
// Get remote branches with timestamps
- let remote = self
- .primary_remote()
- .unwrap_or_else(|_| "origin".to_string());
+ let remote = self.primary_remote().unwrap_or("origin");
let remote_ref_path = format!("refs/remotes/{}/", remote);
let remote_prefix = format!("{}/", remote);
@@ -1181,7 +1207,7 @@ impl Repository {
return None;
}
let timestamp = parts[1].parse().unwrap_or(0);
- Some((local_name.to_string(), remote.clone(), timestamp))
+ Some((local_name.to_string(), remote.to_string(), timestamp))
} else {
None
}
@@ -1390,7 +1416,7 @@ impl Repository {
/// Returns the refreshed default branch name.
pub fn refresh_default_branch(&self) -> anyhow::Result<String> {
let remote = self.primary_remote()?;
- let branch = self.query_remote_default_branch(&remote)?;
+ let branch = self.query_remote_default_branch(remote)?;
// Update worktrunk's cache
let _ = self.run_command(&["config", "worktrunk.default-branch", &branch]);
Ok(branch)
@@ -1466,67 +1492,74 @@ impl Repository {
///
/// This identifier is used to track which commands have been approved
/// for execution in this project.
- pub fn project_identifier(&self) -> anyhow::Result<String> {
- // Try to get the remote URL first
- let remote = self.primary_remote()?;
-
- if let Ok(url) = self.run_command(&["remote", "get-url", &remote]) {
- let url = url.trim();
-
- // Parse common git URL formats:
- // - https://github.com/user/repo.git
- // - [email protected]:user/repo.git
- // - ssh://[email protected]/user/repo.git
-
- // Remove .git suffix if present
- let url = url.strip_suffix(".git").unwrap_or(url);
+ ///
+ /// Result is cached for the lifetime of this Repository instance.
+ pub fn project_identifier(&self) -> anyhow::Result<&str> {
+ self.cache
+ .project_identifier
+ .get_or_try_init(|| {
+ // Try to get the remote URL first
+ let remote = self.primary_remote()?;
+
+ if let Ok(url) = self.run_command(&["remote", "get-url", remote]) {
+ let url = url.trim();
+
+ // Parse common git URL formats:
+ // - https://github.com/user/repo.git
+ // - [email protected]:user/repo.git
+ // - ssh://[email protected]/user/repo.git
+
+ // Remove .git suffix if present
+ let url = url.strip_suffix(".git").unwrap_or(url);
+
+ // Handle SSH format (git@host:path)
+ if let Some(ssh_part) = url.strip_prefix("git@")
+ && let Some((host, path)) = ssh_part.split_once(':')
+ {
+ return Ok(format!("{}/{}", host, path));
+ }
- // Handle SSH format (git@host:path)
- if let Some(ssh_part) = url.strip_prefix("git@")
- && let Some((host, path)) = ssh_part.split_once(':')
- {
- return Ok(format!("{}/{}", host, path));
- }
+ // Handle HTTPS/HTTP format
+ if let Some(https_part) = url
+ .strip_prefix("https://")
+ .or_else(|| url.strip_prefix("http://"))
+ {
+ return Ok(https_part.to_string());
+ }
- // Handle HTTPS/HTTP format
- if let Some(https_part) = url
- .strip_prefix("https://")
- .or_else(|| url.strip_prefix("http://"))
- {
- return Ok(https_part.to_string());
- }
+ // Handle ssh:// format
+ if let Some(ssh_part) = url.strip_prefix("ssh://") {
+ // Remove git@ prefix if present
+ let ssh_part = ssh_part.strip_prefix("git@").unwrap_or(ssh_part);
+ // Replace first : with /
+ if let Some(colon_pos) = ssh_part.find(':') {
+ let (host, path) = ssh_part.split_at(colon_pos);
+ return Ok(format!("{}{}", host, path.replacen(':', "/", 1)));
+ }
+ return Ok(ssh_part.to_string());
+ }
- // Handle ssh:// format
- if let Some(ssh_part) = url.strip_prefix("ssh://") {
- // Remove git@ prefix if present
- let ssh_part = ssh_part.strip_prefix("git@").unwrap_or(ssh_part);
- // Replace first : with /
- if let Some(colon_pos) = ssh_part.find(':') {
- let (host, path) = ssh_part.split_at(colon_pos);
- return Ok(format!("{}{}", host, path.replacen(':', "/", 1)));
+ // If we can't parse it, use the URL as-is
+ return Ok(url.to_string());
}
- return Ok(ssh_part.to_string());
- }
- // If we can't parse it, use the URL as-is
- return Ok(url.to_string());
- }
-
- // Fall back to repository name (use worktree base for consistency across all worktrees)
- let repo_root = self.worktree_base()?;
- let repo_name = repo_root
- .file_name()
- .and_then(|name| name.to_str())
- .ok_or_else(|| {
- anyhow::Error::from(GitError::Other {
- message: format!(
- "Repository directory has no valid name: {}",
- repo_root.display()
- ),
- })
- })?;
-
- Ok(repo_name.to_string())
+ // Fall back to repository name (use worktree base for consistency across all worktrees)
+ let repo_root = self.worktree_base()?;
+ let repo_name = repo_root
+ .file_name()
+ .and_then(|name| name.to_str())
+ .ok_or_else(|| {
+ anyhow::Error::from(GitError::Other {
+ message: format!(
+ "Repository directory has no valid name: {}",
+ repo_root.display()
+ ),
+ })
+ })?;
+
+ Ok(repo_name.to_string())
+ })
+ .map(String::as_str)
}
/// Get a short display name for this repository, used in logging context.
diff --git a/src/llm.rs b/src/llm.rs
index e36d31027..eb83b9d5e 100644
--- a/src/llm.rs
+++ b/src/llm.rs
@@ -510,7 +510,7 @@ pub fn build_commit_prompt(config: &CommitGenerationConfig) -> anyhow::Result<St
let prepared = prepare_diff(diff_output, diff_stat);
// Get current branch
- let current_branch = repo.current_branch()?.unwrap_or_else(|| "HEAD".to_string());
+ let current_branch = repo.current_branch()?.unwrap_or("HEAD");
// Get repo name from directory
let repo_root = repo.worktree_root()?;
@@ -524,7 +524,7 @@ pub fn build_commit_prompt(config: &CommitGenerationConfig) -> anyhow::Result<St
let context = TemplateContext {
git_diff: &prepared.diff,
git_diff_stat: &prepared.stat,
- branch: &current_branch,
+ branch: current_branch,
recent_commits: recent_commits.as_ref(),
repo_name,
commits: &[],
diff --git a/src/main.rs b/src/main.rs
index 89404ed16..7a44647ba 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,7 +1,7 @@
use anyhow::Context;
use clap::FromArgMatches;
use color_print::cformat;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::process;
use worktrunk::config::{WorktrunkConfig, set_config_path};
use worktrunk::git::{Repository, exit_code, set_base_path};
@@ -1371,7 +1371,7 @@ fn main() {
let ctx = CommandContext::new(
&repo,
&config,
- current_branch.as_deref(),
+ current_branch,
&worktree_path,
&repo_root,
force,
@@ -1399,7 +1399,7 @@ fn main() {
use worktrunk::git::ResolvedWorktree;
// When removing multiple worktrees, we need to handle the current worktree last
// to avoid deleting the directory we're currently in
- let current_worktree = repo.worktree_root().ok();
+ let current_worktree = repo.worktree_root().ok().map(Path::to_path_buf);
// Partition worktrees into current, others, and branch-only.
// Track all errors (resolution + removal) so we can report them and continue.
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 7b7cfc38f..9fd18fdba 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -2085,7 +2085,7 @@ pub fn make_snapshot_cmd(
/// The common git directory path
pub fn resolve_git_common_dir(worktree_path: &Path) -> PathBuf {
let repo = worktrunk::git::Repository::at(worktree_path);
- repo.git_common_dir().unwrap()
+ repo.git_common_dir().unwrap().to_path_buf()
}
/// Validates ANSI escape sequences for the specific nested reset pattern that causes color leaks
diff --git a/tests/integration_tests/default_branch.rs b/tests/integration_tests/default_branch.rs
index 905019f79..9d043855b 100644
--- a/tests/integration_tests/default_branch.rs
+++ b/tests/integration_tests/default_branch.rs
@@ -60,10 +60,8 @@ fn test_get_default_branch_no_remote(repo: TestRepo) {
// The inferred branch should match the current branch
let inferred_branch = result.unwrap();
- let current_branch = Repository::at(repo.root_path())
- .current_branch()
- .unwrap()
- .unwrap();
+ let repo_instance = Repository::at(repo.root_path());
+ let current_branch = repo_instance.current_branch().unwrap().unwrap();
assert_eq!(inferred_branch, current_branch);
}
@@ -81,7 +79,8 @@ fn test_primary_remote_detects_custom_remote(mut repo: TestRepo) {
repo.setup_custom_remote("upstream", "develop");
// Test that primary_remote detects the custom remote name
- let remote = Repository::at(repo.root_path()).primary_remote().unwrap();
+ let git_repo = Repository::at(repo.root_path());
+ let remote = git_repo.primary_remote().unwrap();
assert_eq!(remote, "upstream");
}