Skip to content

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

perf(list): batch commit subjects with timestamps pre-skeleton (#2369)

Maximilian Roosbfeb5273994d
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index c119294ef..c3eb304f3 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -28,7 +28,14 @@
//! | `git config remote.*.url` (1-3 calls) | Project identifier (for config + path check) | ✓ |
//! | `git for-each-ref refs/heads` | Only with `--branches` flag | ✓ |
//! | `git for-each-ref refs/remotes` | Only with `--remotes` flag | ✓ |
-//! | `git log --no-walk --format='%H %ct' SHA1 SHA2 ...` | **Batched** timestamps | Sequential (needs SHAs) |
+//! | `git log --no-walk --format='%H\0%ct\0%s' SHA1 SHA2 ...` | **Batched** commit details (timestamp + subject) | Sequential (needs SHAs) |
+//!
+//! The batched `git log` fetches subjects too, which the skeleton itself
+//! doesn't strictly need — only timestamps are required for sort order. It
+//! rides along for free: git has to resolve each commit object anyway, and
+//! the subject bytes add no measurable latency to the round trip. The
+//! subjects populate `cache.commit_details` so the post-skeleton
+//! `CommitDetailsTask` is a pure cache hit instead of N `git log -1` forks.
//!
//! **Non-git operations (negligible latency):**
//! - Path canonicalization — detect current worktree
@@ -730,7 +737,11 @@ pub fn collect(
// Defer previous_branch lookup until after skeleton - set is_previous later
// (skeleton shows placeholder gutter, actual symbols appear when data loads)
- // Phase 3: Batch fetch timestamps (needs all SHAs from worktrees + branches)
+ // Phase 3: Batch fetch commit details (timestamp + subject) for all SHAs
+ // from worktrees + branches. Populates `repo.cache.commit_details` so
+ // post-skeleton `CommitDetailsTask` hits the cache instead of spawning
+ // `git log -1` per row.
+ //
// Filter out null OIDs from unborn branches — a single null OID would cause
// `git log --no-walk` to fail for ALL shas in the batch.
let all_shas: Vec<&str> = worktrees
@@ -744,7 +755,12 @@ pub fn collect(
.chain(remote_branches.iter().map(|(_, sha)| sha.as_str()))
.filter(|sha| *sha != worktrunk::git::NULL_OID)
.collect();
- let timestamps = repo.commit_timestamps(&all_shas).unwrap_or_default();
+ let timestamps: std::collections::HashMap<String, i64> = repo
+ .commit_details_many(&all_shas)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|(sha, (ts, _))| (sha, ts))
+ .collect();
// Sort worktrees: current first, main second, then by timestamp descending
let sorted_worktrees = sort_worktrees_with_cache(
diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rs
index 3c7e17f23..166dfca83 100644
--- a/src/git/repository/diff.rs
+++ b/src/git/repository/diff.rs
@@ -53,28 +53,59 @@ impl Repository {
Ok(files)
}
- /// Get commit timestamps for multiple commits in a single git command.
+ /// Get commit timestamp and subject for multiple commits in a single git command.
///
- /// Returns a map from commit SHA to timestamp.
- pub fn commit_timestamps(&self, commits: &[&str]) -> anyhow::Result<HashMap<String, i64>> {
+ /// Returns a map from commit SHA to `(timestamp, subject)` and primes
+ /// `cache.commit_details` with the same entries, so subsequent per-SHA
+ /// `commit_details()` calls hit the cache and skip their `git log -1` fork.
+ ///
+ /// Uses NUL separators between fields so subjects containing spaces or other
+ /// whitespace parse unambiguously. `%s` is the subject line only, so no
+ /// multi-line handling is needed.
+ ///
+ /// Fails if any SHA is invalid (`git log --no-walk` refuses the whole
+ /// batch). Callers that want a best-effort fallback should use
+ /// `unwrap_or_default()` — individual `commit_details()` lookups will then
+ /// fetch on demand.
+ pub fn commit_details_many(
+ &self,
+ commits: &[&str],
+ ) -> anyhow::Result<HashMap<String, (i64, String)>> {
if commits.is_empty() {
return Ok(HashMap::new());
}
- // Build command: git log --no-walk --format='%H %ct' sha1 sha2 sha3 ...
- // --no-walk shows exactly the named commits without DAG walking
- let mut args = vec!["log", "--no-walk", "--no-show-signature", "--format=%H %ct"];
+ // --no-walk shows exactly the named commits without DAG walking.
+ // --no-show-signature suppresses GPG verification output that otherwise
+ // contaminates stdout when log.showSignature is set.
+ let mut args = vec![
+ "log",
+ "--no-walk",
+ "--no-show-signature",
+ "--format=%H%x00%ct%x00%s",
+ ];
args.extend(commits);
let stdout = self.run_command(&args)?;
let mut result = HashMap::with_capacity(commits.len());
for line in stdout.lines() {
- if let Some((sha, timestamp_str)) = line.split_once(' ')
- && let Ok(timestamp) = timestamp_str.parse::<i64>()
- {
- result.insert(sha.to_string(), timestamp);
- }
+ let mut parts = line.splitn(3, '\0');
+ let (Some(sha), Some(timestamp_str), Some(subject)) =
+ (parts.next(), parts.next(), parts.next())
+ else {
+ bail!(
+ "Malformed git log output: expected '<sha>\\0<ts>\\0<subject>', got {line:?}"
+ );
+ };
+ let timestamp: i64 = timestamp_str
+ .parse()
+ .with_context(|| format!("Failed to parse timestamp {timestamp_str:?}"))?;
+ let entry = (timestamp, subject.to_owned());
+ self.cache
+ .commit_details
+ .insert(sha.to_string(), entry.clone());
+ result.insert(sha.to_string(), entry);
}
Ok(result)
@@ -84,30 +115,29 @@ impl Repository {
///
/// 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.
+ /// `git log -1` once. `commit_details_many()` primes the same cache in
+ /// bulk when a set of SHAs is known up front.
pub fn commit_details(&self, commit: &str) -> anyhow::Result<(i64, String)> {
- 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.
+ // Matches the batch path's format (NUL separators) so both populate
+ // the cache with byte-identical values. --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",
+ "--format=%ct%x00%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(' ')
+ let (timestamp_str, subject) = line
+ .split_once('\0')
.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())
+ Ok(e.insert((timestamp, subject.to_owned())).clone())
}
}
}
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index a84af7009..59cb8dbb4 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -606,3 +606,79 @@ fn is_builtin_fsmonitor_enabled_variants() {
}
assert!(!repo_with_fsmonitor(None).is_builtin_fsmonitor_enabled());
}
+
+#[test]
+fn commit_details_many_returns_subject_with_spaces_and_primes_cache() {
+ use crate::testing::TestRepo;
+
+ let test = TestRepo::new();
+ // Commit with a multi-word subject — regression against parsers that split
+ // on the first space and treat "word1" as the timestamp.
+ test.commit_with_message("first commit with spaces");
+ let sha1 = test.repo.run_command(&["rev-parse", "HEAD"]).unwrap();
+ let sha1 = sha1.trim().to_string();
+
+ test.commit_with_message("second commit");
+ let sha2 = test.repo.run_command(&["rev-parse", "HEAD"]).unwrap();
+ let sha2 = sha2.trim().to_string();
+
+ let result = test
+ .repo
+ .commit_details_many(&[sha1.as_str(), sha2.as_str()])
+ .unwrap();
+
+ assert_eq!(result.len(), 2);
+ assert_eq!(result[&sha1].1, "first commit with spaces");
+ assert_eq!(result[&sha2].1, "second commit");
+ assert!(result[&sha1].0 > 0);
+ assert!(result[&sha2].0 > 0);
+
+ // Cache is primed — a subsequent `commit_details()` call must hit the cache
+ // rather than run `git log -1`. We observe this indirectly: the cached
+ // entry is present for both SHAs.
+ assert_eq!(
+ test.repo.cache.commit_details.get(&sha1).map(|v| v.clone()),
+ Some((result[&sha1].0, "first commit with spaces".to_string())),
+ );
+ assert_eq!(
+ test.repo.cache.commit_details.get(&sha2).map(|v| v.clone()),
+ Some((result[&sha2].0, "second commit".to_string())),
+ );
+}
+
+#[test]
+fn commit_details_many_empty_input_is_noop() {
+ use crate::testing::TestRepo;
+
+ let test = TestRepo::with_initial_commit();
+ let result = test.repo.commit_details_many(&[]).unwrap();
+ assert!(result.is_empty());
+ assert!(test.repo.cache.commit_details.is_empty());
+}
+
+#[test]
+fn commit_details_and_many_store_identical_cache_entries() {
+ // The two code paths must produce byte-identical cache entries — otherwise
+ // a SHA's cached value depends on which path populated it first.
+ use crate::testing::TestRepo;
+
+ let test = TestRepo::new();
+ test.commit_with_message(" subject with leading spaces");
+ let sha = test
+ .repo
+ .run_command(&["rev-parse", "HEAD"])
+ .unwrap()
+ .trim()
+ .to_string();
+
+ let via_single = test.repo.commit_details(&sha).unwrap();
+ test.repo.cache.commit_details.clear();
+ let via_batch = test
+ .repo
+ .commit_details_many(&[sha.as_str()])
+ .unwrap()
+ .remove(&sha)
+ .unwrap();
+
+ assert_eq!(via_single, via_batch);
+}