Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Cut three duplicate git subprocesses per `wt list statusline` render (#2209)
Maximilian Roos83f4fe0daf2b
diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rsindex eba9856a2..f4d2282a0 100644--- a/src/git/repository/diff.rs+++ b/src/git/repository/diff.rs@@ -146,20 +146,28 @@ impl Repository {////// Results are cached in the shared repo cache to avoid redundant git commands/// when multiple tasks need the same merge-base (e.g., parallel `wt list` tasks).- /// The cache key is normalized (sorted) since merge-base(A, B) == merge-base(B, A).+ /// Inputs are resolved to commit SHAs (via the cached `commit_shas` map) before+ /// keying the cache, so equivalent forms (e.g., `"main"` vs the SHA `main` points+ /// to) hit the same entry. The key is also order-normalized since merge-base is+ /// symmetric: `merge-base(A, B) == merge-base(B, A)`.pub fn merge_base(&self, commit1: &str, commit2: &str) -> anyhow::Result<Option<String>> {- // Normalize key order since merge-base is symmetric: merge-base(A, B) == merge-base(B, A)- let key = if commit1 <= commit2 {- (commit1.to_string(), commit2.to_string())+ // Resolve to SHAs so different forms of the same commit dedupe in the cache.+ // `resolve_to_commit_sha` is a no-op for inputs that already look like SHAs.+ let sha1 = self.resolve_to_commit_sha(commit1)?;+ let sha2 = self.resolve_to_commit_sha(commit2)?;++ // Normalize key order since merge-base is symmetric.+ let key = if sha1 <= sha2 {+ (sha1.clone(), sha2.clone())} else {- (commit2.to_string(), commit1.to_string())+ (sha2.clone(), sha1.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 output = self.run_command_output(&["merge-base", &sha1, &sha2])?;let result = if output.status.success() {Some(String::from_utf8_lossy(&output.stdout).trim().to_owned())diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rsindex 9dd2847de..5a820a92e 100644--- a/src/git/repository/integration.rs+++ b/src/git/repository/integration.rs@@ -511,6 +511,18 @@ impl Repository {}}+ /// Resolve a ref to its commit SHA, skipping git when the input already+ /// looks like a 40-char hex SHA.+ ///+ /// Used at cache boundaries (e.g. [`Self::merge_base`]) to normalize keys+ /// without spawning `git rev-parse` for inputs that are already SHAs.+ pub(super) fn resolve_to_commit_sha(&self, r: &str) -> anyhow::Result<String> {+ if is_hex_commit_sha(r) {+ return Ok(r.to_string());+ }+ self.rev_parse_commit(r)+ }+/// Check if a branch is integrated into a target.////// This is a convenience method that combines [`compute_integration_lazy()`] and@@ -557,3 +569,44 @@ impl Repository {}}}++/// Returns true when `s` is a 40-character hex string — the canonical form+/// of a git commit SHA-1.+fn is_hex_commit_sha(s: &str) -> bool {+ s.len() == 40 && s.bytes().all(|b| b.is_ascii_hexdigit())+}++#[cfg(test)]+mod hex_sha_tests {+ use super::is_hex_commit_sha;++ #[test]+ fn detects_full_hex_sha() {+ assert!(is_hex_commit_sha(+ "273f078bd20a09f1a524aae48fcb1771ceac9b5d"+ ));+ }++ #[test]+ fn rejects_branch_names() {+ assert!(!is_hex_commit_sha("main"));+ assert!(!is_hex_commit_sha("feature/foo"));+ }++ #[test]+ fn rejects_short_or_long() {+ assert!(!is_hex_commit_sha(+ "273f078bd20a09f1a524aae48fcb1771ceac9b5"+ ));+ assert!(!is_hex_commit_sha(+ "273f078bd20a09f1a524aae48fcb1771ceac9b5d0"+ ));+ }++ #[test]+ fn rejects_non_hex_chars() {+ assert!(!is_hex_commit_sha(+ "z73f078bd20a09f1a524aae48fcb1771ceac9b5d"+ ));+ }+}diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 33356e1ad..24d141561 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -288,6 +288,21 @@ static BASE_PATH: OnceLock<PathBuf> = OnceLock::new();/// Default base path when -C flag is not provided.static DEFAULT_BASE_PATH: LazyLock<PathBuf> = LazyLock::new(|| PathBuf::from("."));+/// Process-wide cache for `git rev-parse --git-common-dir` resolution,+/// keyed by the discovery path passed to [`Repository::at`].+///+/// Unlike per-Repository caches, this lives for the whole process so that+/// multiple Repository instances pointed at the same path (e.g.+/// `init_command_log` early in `main`, then a command handler later) skip+/// the duplicate `git rev-parse` subprocess. The value (a canonicalized+/// `.git` directory) is invariant for the lifetime of the process.+///+/// Keys are stored as-is (not canonicalized) — the goal is only to dedupe+/// repeated calls with the same path. The duplicate case we care about (both+/// callers go through `base_path()`) always passes the same `PathBuf`, so+/// equality on the raw path is sufficient.+static GIT_COMMON_DIR_CACHE: LazyLock<DashMap<PathBuf, PathBuf>> = LazyLock::new(DashMap::new);+/// Initialize the global base path for repository operations.////// This should be called once at program startup from main().@@ -456,7 +471,15 @@ impl Repository {////// Always returns a canonicalized absolute path to ensure consistent/// comparison with `WorkingTree::git_dir()`.+ ///+ /// Result is cached process-wide in [`GIT_COMMON_DIR_CACHE`] so multiple+ /// `Repository::at()` calls for the same discovery path don't each spawn+ /// `git rev-parse --git-common-dir`.fn resolve_git_common_dir(discovery_path: &Path) -> anyhow::Result<PathBuf> {+ if let Some(cached) = GIT_COMMON_DIR_CACHE.get(discovery_path) {+ return Ok(cached.clone());+ }+let output = Cmd::new("git").args(["rev-parse", "--git-common-dir"]).current_dir(discovery_path)@@ -477,7 +500,10 @@ impl Repository {} else {path};- canonicalize(&absolute_path).context("Failed to resolve git common directory")+ let resolved =+ canonicalize(&absolute_path).context("Failed to resolve git common directory")?;+ GIT_COMMON_DIR_CACHE.insert(discovery_path.to_path_buf(), resolved.clone());+ Ok(resolved)}/// Get the path this repository was discovered from.@@ -498,11 +524,16 @@ impl Repository {/// Get a worktree view at a specific path.////// Use this when you need to operate on a worktree other than the current one.+ ///+ /// The path is canonicalized when it exists so that callers passing+ /// equivalent forms (e.g., cwd from JSON vs path from `git worktree list+ /// --porcelain`) hit the same per-worktree cache entries in `RepoCache`.+ /// Falls back to the raw path if canonicalization fails (e.g., path does+ /// not yet exist for a worktree about to be created).pub fn worktree_at(&self, path: impl Into<PathBuf>) -> WorkingTree<'_> {- WorkingTree {- repo: self,- path: path.into(),- }+ let raw = path.into();+ let path = canonicalize(&raw).unwrap_or(raw);+ WorkingTree { repo: self, path }}/// Get a branch handle for branch-specific operations.diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex e5db1661d..4e5ab5e98 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -72,7 +72,11 @@ impl<'a> WorkingTree<'a> {/// Get the path this WorkingTree was created with.///- /// This is the path passed to `worktree_at()` or `base_path()` for `current_worktree()`.+ /// Returns the canonicalized form when the input passed to `worktree_at()` /+ /// `base_path()` for `current_worktree()` exists on disk; otherwise returns+ /// the raw input. So on macOS, a temp path like `/tmp/foo` may surface here+ /// (and to hook template variables) as `/private/tmp/foo`.+ ////// For the canonical git-determined root, use [`root()`](Self::root) instead.pub fn path(&self) -> &Path {&self.path