Skip to content

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

refactor(list): drop CommitDetailsTask and the per-SHA fallback (#2379)

Maximilian Roos390b025953f8
diff --git a/src/commands/list/collect/execution.rs b/src/commands/list/collect/execution.rs
index 6b1cdcce2..7bdf8d4e8 100644
--- a/src/commands/list/collect/execution.rs
+++ b/src/commands/list/collect/execution.rs
@@ -28,17 +28,16 @@ use super::super::model::{
};
use super::CollectOptions;
use super::tasks::{
- AheadBehindTask, BranchDiffTask, CiStatusTask, CommitDetailsTask, CommittedTreesMatchTask,
- GitOperationTask, HasFileChangesTask, IsAncestorTask, MergeTreeConflictsTask,
- SummaryGenerateTask, Task, TaskContext, UpstreamTask, UrlStatusTask, UserMarkerTask,
- WorkingTreeConflictsTask, WorkingTreeDiffTask, WouldMergeAddTask,
+ AheadBehindTask, BranchDiffTask, CiStatusTask, CommittedTreesMatchTask, GitOperationTask,
+ HasFileChangesTask, IsAncestorTask, MergeTreeConflictsTask, SummaryGenerateTask, Task,
+ TaskContext, UpstreamTask, UrlStatusTask, UserMarkerTask, WorkingTreeConflictsTask,
+ WorkingTreeDiffTask, WouldMergeAddTask,
};
use super::types::{TaskError, TaskKind, TaskResult};
/// Tasks that require a valid commit SHA. Skipped for unborn branches (no commits yet).
/// Without this, these tasks would fail on the null OID and show as errors in the table.
const COMMIT_TASKS: &[TaskKind] = &[
- TaskKind::CommitDetails,
TaskKind::AheadBehind,
TaskKind::CommittedTreesMatch,
TaskKind::HasFileChanges,
@@ -79,7 +78,6 @@ impl WorkItem {
/// Dispatch a task by kind, calling the appropriate Task::compute().
fn dispatch_task(kind: TaskKind, ctx: TaskContext) -> Result<TaskResult, TaskError> {
match kind {
- TaskKind::CommitDetails => CommitDetailsTask::compute(ctx),
TaskKind::AheadBehind => AheadBehindTask::compute(ctx),
TaskKind::CommittedTreesMatch => CommittedTreesMatchTask::compute(ctx),
TaskKind::HasFileChanges => HasFileChangesTask::compute(ctx),
@@ -159,16 +157,15 @@ impl ExpectedResults {
/// pre-seed `status_symbols.main_state` directly — see
/// [`seed_unborn_main_state`].
///
-/// Non-status-feeding tasks (`CommitDetails`, `BranchDiff`, `CiStatus`,
-/// `UrlStatus`, `SummaryGenerate`) are rendered by their own columns with
-/// their own placeholders; `refresh_status_symbols` doesn't read them, so
-/// there is nothing to seed.
+/// Non-status-feeding tasks (`BranchDiff`, `CiStatus`, `UrlStatus`,
+/// `SummaryGenerate`) are rendered by their own columns with their own
+/// placeholders; `refresh_status_symbols` doesn't read them, so there is
+/// nothing to seed.
pub(super) fn seed_skipped_task_defaults(item: &mut ListItem, kind: TaskKind) {
match kind {
// Not consumed by refresh_status_symbols — columns handle their own
// loading state.
- TaskKind::CommitDetails
- | TaskKind::BranchDiff
+ TaskKind::BranchDiff
| TaskKind::CiStatus
| TaskKind::UrlStatus
| TaskKind::SummaryGenerate => {}
@@ -367,7 +364,6 @@ pub fn work_items_for_worktree(
let mut items = Vec::with_capacity(15);
for kind in [
- TaskKind::CommitDetails,
TaskKind::AheadBehind,
TaskKind::CommittedTreesMatch,
TaskKind::HasFileChanges,
@@ -478,7 +474,6 @@ pub fn work_items_for_branch(
let mut items = Vec::with_capacity(11);
for kind in [
- TaskKind::CommitDetails,
TaskKind::AheadBehind,
TaskKind::CommittedTreesMatch,
TaskKind::HasFileChanges,
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index f880fef93..163d1f4bc 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -34,8 +34,11 @@
//! 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.
+//! full `(timestamp, subject)` map is handed to the post-skeleton loop that
+//! populates `ListItem.commit` directly — no per-SHA `git log -1` fork path.
+//! When the batch fails (e.g., a listed SHA was deleted mid-run), the
+//! failure is surfaced once and Age/Message cells render placeholders for
+//! that run.
//!
//! **Non-git operations (negligible latency):**
//! - Path canonicalization — detect current worktree
@@ -65,6 +68,7 @@
//! │ ├─ integration_target() (10ms)
//! │ ├─ start_fsmonitor_daemon × N worktrees (6ms each, all parallel)
//! │ ) // ~10ms total (max of all spawns)
+//! ├─ populate ListItem.commit from cache (cache-hit lookups, sub-ms)
//! Worker thread spawns
//! ```
//!
@@ -231,7 +235,7 @@ use worktrunk::styling::{
use crate::commands::is_worktree_at_expected_path;
-use super::model::{DisplayFields, ItemKind, ListItem, StatusSymbols, WorktreeData};
+use super::model::{CommitDetails, DisplayFields, ItemKind, ListItem, StatusSymbols, WorktreeData};
use super::progressive_table::ProgressiveTable;
// Re-exports for sibling modules (columns.rs, render.rs, layout.rs)
@@ -736,9 +740,11 @@ pub fn collect(
// (skeleton shows placeholder gutter, actual symbols appear when data loads)
// 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.
+ // from worktrees + branches. The returned map is the single canonical
+ // source of commit details — sorting below and post-skeleton item
+ // population both read from it. A batch failure is surfaced as a
+ // warning and degrades to empty-cell placeholders (no hidden per-SHA
+ // recovery forks).
//
// 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.
@@ -753,28 +759,32 @@ pub fn collect(
.chain(remote_branches.iter().map(|(_, sha)| sha.as_str()))
.filter(|sha| *sha != worktrunk::git::NULL_OID)
.collect();
- let timestamps: std::collections::HashMap<String, i64> = repo
- .commit_details_many(&all_shas)
- .unwrap_or_default()
- .into_iter()
- .map(|(sha, (ts, _))| (sha, ts))
- .collect();
+ let commit_details_map = repo.commit_details_many(&all_shas).unwrap_or_else(|err| {
+ eprintln!(
+ "{}",
+ warning_message(cformat!("Failed to batch-fetch commit details: {err}"))
+ );
+ std::collections::HashMap::new()
+ });
// Sort worktrees: current first, main second, then by timestamp descending
let sorted_worktrees = sort_worktrees_with_cache(
worktrees.to_vec(),
&main_worktree,
current_worktree_path.as_ref(),
- &timestamps,
+ &commit_details_map,
);
// Sort branches by timestamp (most recent first)
- let branches_without_worktrees =
- sort_by_timestamp_desc_with_cache(branches_without_worktrees, &timestamps, |(_, sha)| {
+ let branches_without_worktrees = sort_by_timestamp_desc_with_cache(
+ branches_without_worktrees,
+ &commit_details_map,
+ |(_, sha)| sha.as_str(),
+ );
+ let remote_branches =
+ sort_by_timestamp_desc_with_cache(remote_branches, &commit_details_map, |(_, sha)| {
sha.as_str()
});
- let remote_branches =
- sort_by_timestamp_desc_with_cache(remote_branches, &timestamps, |(_, sha)| sha.as_str());
// Pre-canonicalize main_worktree.path for is_main comparison
// (paths from git worktree list may differ based on symlinks or working directory)
@@ -1066,6 +1076,24 @@ pub fn collect(
}
}
+ // Populate commit details (timestamp + subject) on every item directly
+ // from the pre-skeleton batch map. No per-SHA recovery — if the batch
+ // failed, the warning printed above is the user-visible signal and
+ // Age/Message cells render their placeholder. Prunable worktrees are
+ // skipped because their directory is missing from disk; leaving these
+ // rows at the placeholder matches the old task-queue UX.
+ for item in &mut all_items {
+ if item.worktree_data().is_some_and(|d| d.is_prunable()) {
+ continue;
+ }
+ if let Some((timestamp, commit_message)) = commit_details_map.get(&item.head) {
+ item.commit = Some(CommitDetails {
+ timestamp: *timestamp,
+ commit_message: commit_message.clone(),
+ });
+ }
+ }
+
// Batch-fetch ahead/behind counts for all local branches in a single
// `git for-each-ref` call. Primes the Repository cache so each
// `AheadBehindTask` hits the cache instead of spawning its own
@@ -1464,10 +1492,10 @@ pub fn collect(
// Sorting Helpers
// ============================================================================
-/// Sort items by timestamp descending using pre-fetched timestamps.
+/// Sort items by timestamp descending using the pre-fetched commit-details map.
fn sort_by_timestamp_desc_with_cache<T, F>(
items: Vec<T>,
- timestamps: &std::collections::HashMap<String, i64>,
+ commit_details: &std::collections::HashMap<String, (i64, String)>,
get_sha: F,
) -> Vec<T>
where
@@ -1477,7 +1505,7 @@ where
let mut with_ts: Vec<_> = items
.into_iter()
.map(|item| {
- let ts = *timestamps.get(get_sha(&item)).unwrap_or(&0);
+ let ts = commit_details.get(get_sha(&item)).map_or(0, |(ts, _)| *ts);
(item, ts)
})
.collect();
@@ -1486,12 +1514,12 @@ where
}
/// Sort worktrees: current first, main second, then by timestamp descending.
-/// Uses pre-fetched timestamps for efficiency.
+/// Uses the pre-fetched commit-details map for efficiency.
fn sort_worktrees_with_cache(
worktrees: Vec<WorktreeInfo>,
main_worktree: &WorktreeInfo,
current_path: Option<&std::path::PathBuf>,
- timestamps: &std::collections::HashMap<String, i64>,
+ commit_details: &std::collections::HashMap<String, (i64, String)>,
) -> Vec<WorktreeInfo> {
// Embed timestamp and priority in tuple to avoid parallel Vec and index lookups
let mut with_sort_key: Vec<_> = worktrees
@@ -1504,7 +1532,7 @@ fn sort_worktrees_with_cache(
} else {
2 // Rest by timestamp
};
- let ts = *timestamps.get(&wt.head).unwrap_or(&0);
+ let ts = commit_details.get(&wt.head).map_or(0, |(ts, _)| *ts);
(wt, priority, ts)
})
.collect();
@@ -1572,6 +1600,25 @@ pub fn populate_item(
item: &mut ListItem,
mut options: CollectOptions,
) -> anyhow::Result<()> {
+ // Populate commit details (timestamp + subject) directly. The main
+ // `collect()` path batches this across all items pre-skeleton; the
+ // single-item statusline path has no such batch, so fetch the one SHA
+ // here. Skip null OIDs (unborn branches) and prunable worktrees —
+ // matches the behavior in `collect()`. Silent on batch failure: the
+ // statusline is a compact prompt element with no room for warnings, and
+ // `commit.message` / `commit.timestamp` fall through to their defaults.
+ let is_prunable = item.worktree_data().is_some_and(|d| d.is_prunable());
+ if item.head != worktrunk::git::NULL_OID
+ && !is_prunable
+ && let Ok(map) = repo.commit_details_many(&[&item.head])
+ && let Some((timestamp, commit_message)) = map.get(&item.head)
+ {
+ item.commit = Some(CommitDetails {
+ timestamp: *timestamp,
+ commit_message: commit_message.clone(),
+ });
+ }
+
// Extract worktree data (skip if not a worktree item)
let Some(data) = item.worktree_data() else {
return Ok(());
diff --git a/src/commands/list/collect/results.rs b/src/commands/list/collect/results.rs
index 4c6b8ccee..d7033dcf5 100644
--- a/src/commands/list/collect/results.rs
+++ b/src/commands/list/collect/results.rs
@@ -266,9 +266,6 @@ pub(super) fn drain_results_with_timings(
let item = &mut items[item_idx];
match result {
- TaskResult::CommitDetails { commit, .. } => {
- item.commit = Some(commit);
- }
TaskResult::AheadBehind {
counts, is_orphan, ..
} => {
@@ -658,7 +655,7 @@ mod tests {
// Register expected results but don't send any — simulates tasks still running
let expected = ExpectedResults::default();
- expected.expect(0, TaskKind::CommitDetails);
+ expected.expect(0, TaskKind::Upstream);
expected.expect(0, TaskKind::AheadBehind);
// Use an already-expired deadline — remaining.is_zero() triggers immediately
@@ -687,7 +684,7 @@ mod tests {
assert!(
items_with_missing[0]
.missing_kinds
- .contains(&TaskKind::CommitDetails)
+ .contains(&TaskKind::Upstream)
);
assert!(
items_with_missing[0]
@@ -711,7 +708,7 @@ mod tests {
let expected = ExpectedResults::default();
expected.expect(0, TaskKind::AheadBehind);
- expected.expect(1, TaskKind::CommitDetails);
+ expected.expect(1, TaskKind::Upstream);
let mut stall_events: Vec<(usize, TaskKind, String)> = Vec::new();
let outcome = drain_results_with_timings(
@@ -758,7 +755,7 @@ mod tests {
let mut errors = Vec::new();
let expected = ExpectedResults::default();
- expected.expect(0, TaskKind::CommitDetails);
+ expected.expect(0, TaskKind::Upstream);
tx.send(Ok(TaskResult::SummaryGenerate {
item_idx: 0,
@@ -809,7 +806,7 @@ mod tests {
let mut errors = Vec::new();
let expected = ExpectedResults::default();
- expected.expect(0, TaskKind::CommitDetails);
+ expected.expect(0, TaskKind::Upstream);
expected.expect(0, TaskKind::AheadBehind);
let mut sender = Some(tx);
diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rs
index 147429dff..21412ec97 100644
--- a/src/commands/list/collect/tasks.rs
+++ b/src/commands/list/collect/tasks.rs
@@ -11,8 +11,7 @@ use worktrunk::git::{LineDiff, Repository};
use super::super::ci_status::{CiBranchName, PrStatus};
use super::super::model::{
- ActiveGitOperation, AheadBehind, BranchDiffTotals, CommitDetails, UpstreamStatus,
- WorkingTreeStatus,
+ ActiveGitOperation, AheadBehind, BranchDiffTotals, UpstreamStatus, WorkingTreeStatus,
};
use super::types::{ErrorCause, TaskError, TaskKind, TaskResult};
@@ -120,28 +119,7 @@ pub trait Task: Send + Sync + 'static {
// Task Implementations
// ============================================================================
-/// Task 1: Commit details (timestamp, message)
-pub struct CommitDetailsTask;
-
-impl Task for CommitDetailsTask {
- const KIND: TaskKind = TaskKind::CommitDetails;
-
- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let repo = &ctx.repo;
- let (timestamp, commit_message) = repo
- .commit_details(&ctx.branch_ref.commit_sha)
- .map_err(|e| ctx.error(Self::KIND, &e))?;
- Ok(TaskResult::CommitDetails {
- item_idx: ctx.item_idx,
- commit: CommitDetails {
- timestamp,
- commit_message,
- },
- })
- }
-}
-
-/// Task 2: Ahead/behind counts vs local default branch (informational stats)
+/// Task: Ahead/behind counts vs local default branch (informational stats)
pub struct AheadBehindTask;
impl Task for AheadBehindTask {
diff --git a/src/commands/list/collect/types.rs b/src/commands/list/collect/types.rs
index ccd8215e6..2224e1f28 100644
--- a/src/commands/list/collect/types.rs
+++ b/src/commands/list/collect/types.rs
@@ -9,8 +9,7 @@ use worktrunk::git::LineDiff;
use super::super::ci_status::PrStatus;
use super::super::model::{
- ActiveGitOperation, AheadBehind, BranchDiffTotals, CommitDetails, UpstreamStatus,
- WorkingTreeStatus,
+ ActiveGitOperation, AheadBehind, BranchDiffTotals, UpstreamStatus, WorkingTreeStatus,
};
/// Task results sent as each git operation completes.
@@ -31,11 +30,6 @@ use super::super::model::{
strum(serialize_all = "kebab-case")
)]
pub(crate) enum TaskResult {
- /// Commit timestamp and message
- CommitDetails {
- item_idx: usize,
- commit: CommitDetails,
- },
/// Ahead/behind counts vs default branch
AheadBehind {
item_idx: usize,
@@ -130,8 +124,7 @@ impl TaskResult {
/// Get the item index for this result
pub fn item_idx(&self) -> usize {
match self {
- TaskResult::CommitDetails { item_idx, .. }
- | TaskResult::AheadBehind { item_idx, .. }
+ TaskResult::AheadBehind { item_idx, .. }
| TaskResult::CommittedTreesMatch { item_idx, .. }
| TaskResult::HasFileChanges { item_idx, .. }
| TaskResult::WouldMergeAdd { item_idx, .. }
diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rs
index 27fdb9446..5da2872be 100644
--- a/src/git/repository/diff.rs
+++ b/src/git/repository/diff.rs
@@ -55,18 +55,16 @@ impl Repository {
/// Get commit timestamp and subject for multiple commits in a single git command.
///
- /// 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
+ /// Returns a map from commit SHA to `(timestamp, subject)`. 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.
+ /// Fails if any SHA is invalid — `git log --no-walk` refuses the whole
+ /// batch on a single bad ref. Callers should surface the error rather
+ /// than fall back to per-SHA fetches: the batch is the only commit-detail
+ /// fetch path left, and quietly swallowing the failure produces empty
+ /// cells without telling the user why.
pub fn commit_details_many(
&self,
commits: &[&str],
@@ -101,47 +99,12 @@ impl Repository {
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);
+ result.insert(sha.to_string(), (timestamp, subject.to_owned()));
}
Ok(result)
}
- /// Get commit timestamp and message in a single git command.
- ///
- /// 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. `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)> {
- match self.cache.commit_details.entry(commit.to_string()) {
- Entry::Occupied(e) => Ok(e.get().clone()),
- Entry::Vacant(e) => {
- // 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%x00%s",
- commit,
- ])?;
- let line = stdout.trim_end_matches('\n');
- 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, subject.to_owned())).clone())
- }
- }
- }
-
/// Get commit subjects (first line of commit message) from a range.
pub fn commit_subjects(&self, range: &str) -> anyhow::Result<Vec<String>> {
let output = self.run_command(&["log", "--no-show-signature", "--format=%s", range])?;
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index a2d842bc8..186e648ac 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -290,10 +290,6 @@ pub(super) struct RepoCache {
/// `collect::collect` pass hits memory instead of respawning the
/// subprocess on the critical path to skeleton.
pub(super) worktrees: OnceCell<Vec<WorktreeInfo>>,
- /// Commit details cache: commit SHA -> (timestamp, subject).
- /// Multiple items sharing the same HEAD commit (e.g., worktrees on main)
- /// would otherwise each spawn a `git log -1` for the same SHA.
- pub(super) commit_details: DashMap<String, (i64, String)>,
/// In-memory branch diff stats cache: (base_sha, head_sha) -> LineDiff.
/// Sits in front of the persistent `sha_cache` to prevent parallel tasks
/// from racing through the file-based cache for the same SHA pair.
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index 479867811..1b367c0ae 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -608,7 +608,7 @@ fn is_builtin_fsmonitor_enabled_variants() {
}
#[test]
-fn commit_details_many_returns_subject_with_spaces_and_primes_cache() {
+fn commit_details_many_returns_subject_with_spaces() {
use crate::testing::TestRepo;
let test = TestRepo::new();
@@ -632,18 +632,6 @@ fn commit_details_many_returns_subject_with_spaces_and_primes_cache() {
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]
@@ -653,7 +641,24 @@ fn commit_details_many_empty_input_is_noop() {
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_many_fails_loudly_on_unknown_sha() {
+ // `git log --no-walk` refuses the whole batch on a single bad ref. The
+ // error surfaces as an `Err`, which `collect()` turns into a user-facing
+ // warning. Pin this behavior so we don't silently fall back to
+ // empty-map defaults.
+ use crate::testing::TestRepo;
+
+ let test = TestRepo::with_initial_commit();
+ let bogus = "0000000000000000000000000000000000000001";
+ let err = test.repo.commit_details_many(&[bogus]).unwrap_err();
+ let msg = format!("{err:#}");
+ assert!(
+ msg.contains("git") || msg.contains("unknown") || msg.contains("bad"),
+ "error message should surface git's complaint about the bogus SHA, got: {msg}"
+ );
}
#[test]
@@ -681,7 +686,7 @@ fn commit_details_many_preserves_multibyte_utf8_subject() {
#[test]
fn commit_details_many_deduplicates_repeated_sha() {
// `git log --no-walk SHA SHA` emits each commit once; pin that the batch
- // code returns a single cache entry for a duplicated input SHA.
+ // returns a single entry for a duplicated input SHA.
use crate::testing::TestRepo;
let test = TestRepo::new();
@@ -700,32 +705,4 @@ fn commit_details_many_deduplicates_repeated_sha() {
assert_eq!(result.len(), 1);
assert_eq!(result[&sha].1, "only commit");
- assert_eq!(test.repo.cache.commit_details.len(), 1);
-}
-
-#[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);
}
diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rs
index 3096b8f04..81e7edab8 100644
--- a/tests/integration_tests/list.rs
+++ b/tests/integration_tests/list.rs
@@ -2980,6 +2980,34 @@ fn test_list_shows_warning_on_git_error(mut repo: TestRepo) {
assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}
+///
+/// Corrupts a detached worktree's HEAD file to a non-null but unresolvable
+/// SHA. The `collect()` batch filters out `NULL_OID`, so a non-null invalid
+/// SHA reaches `commit_details_many` and fails the whole batch — exercising
+/// the `unwrap_or_else` warning path that reports "Failed to batch-fetch
+/// commit details" on stderr.
+#[rstest]
+fn test_list_warns_when_commit_details_batch_fails(mut repo: TestRepo) {
+ let worktree_path = repo.add_worktree("feature");
+
+ // Detach the worktree's HEAD and rewrite its HEAD file to a non-null but
+ // unresolvable SHA. `git worktree list --porcelain` happily reports the
+ // invalid SHA, which flows into the commit-details batch. Delete the
+ // branch ref so `for-each-ref refs/heads/` (branch inventory scan) doesn't
+ // choke on the now-dangling branch.
+ repo.run_git_in(&worktree_path, &["checkout", "--detach"]);
+ repo.run_git(&["branch", "-D", "feature"]);
+ let worktree_dir_name = worktree_path.file_name().unwrap().to_str().unwrap();
+ let head_path = repo
+ .root_path()
+ .join(".git/worktrees")
+ .join(worktree_dir_name)
+ .join("HEAD");
+ std::fs::write(&head_path, "0000000000000000000000000000000000000001\n").unwrap();
+
+ assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
+}
+
///
/// Creates a true orphan branch using `git checkout --orphan` which has no merge base
/// with main. Verifies no error warning appears and the branch shows as unmerged.
diff --git a/tests/integration_tests/statusline.rs b/tests/integration_tests/statusline.rs
index cd973aa11..ab5424a16 100644
--- a/tests/integration_tests/statusline.rs
+++ b/tests/integration_tests/statusline.rs
@@ -412,9 +412,17 @@ fn test_statusline_json_basic(repo: TestRepo) {
assert!(item["is_current"].as_bool().unwrap());
assert!(item["is_main"].as_bool().unwrap());
- // commit object should exist with sha
+ // commit object should exist with sha, message, and non-zero timestamp
assert!(item["commit"]["sha"].is_string());
assert!(item["commit"]["short_sha"].is_string());
+ assert!(
+ !item["commit"]["message"].as_str().unwrap().is_empty(),
+ "commit.message should be populated from git log"
+ );
+ assert!(
+ item["commit"]["timestamp"].as_i64().unwrap() > 0,
+ "commit.timestamp should be populated from git log"
+ );
}
#[rstest]
diff --git a/tests/snapshots/integration__integration_tests__list__list_warns_when_commit_details_batch_fails.snap b/tests/snapshots/integration__integration_tests__list__list_warns_when_commit_details_batch_fails.snap
new file mode 100644
index 000000000..080e6ecb0
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__list_warns_when_commit_details_batch_fails.snap
@@ -0,0 +1,61 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+ Branch Status HEAD± main↕ Remote⇅ Path Commit Age Message
+@ main ^| | . 05a4a45d · ·
++ - · ·· · · ../repo.feature 00000000 · ·
++ feature-a ↑ ↑1 ../repo.feature-a 1b87d473 · ·
++ feature-b ↑ ↑1 ../repo.feature-b f62940fc · ·
++ feature-c ↑ ↑1 ../repo.feature-c 345c7c93 · ·
+
+○ Showing 5 worktrees, 3 ahead. 5 tasks failed
+
+----- stderr -----
+▲ Failed to batch-fetch commit details: fatal: bad object 0000000000000000000000000000000000000001
+▲ Some git operations failed:
+  (detached): ahead-behind (git merge-base failed for main 0000000000000000000000000000000000000001: fatal: Not a valid commit name 0000000000000000000000000000000000000001)
+  (detached): committed-trees-match (fatal: ambiguous argument '0000000000000000000000000000000000000001^{tree}': unknown revision or path not in the working tree.)
+  (detached): working-tree-diff (fatal: bad object HEAD)
+  (detached): merge-tree-conflicts (git merge-base failed for 05a4a45d0b981dad5c27db59dca482836d59f89e 0000000000000000000000000000000000000001: fatal: Not a valid commit name 0000000000000000000000000000000000000001)
+  (detached): working-tree-conflicts (fatal: bad object HEAD)
+↳ To create a diagnostic file, run with -vv