Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Refactor commit timestamp and message fetch into single operation (#555)
Maximilian Roosde77a756bb37
diff --git a/src/commands/list/collect_progressive_impl.rs b/src/commands/list/collect_progressive_impl.rsindex 38a44a8e7..96e43e51e 100644--- a/src/commands/list/collect_progressive_impl.rs+++ b/src/commands/list/collect_progressive_impl.rs@@ -377,11 +377,8 @@ impl Task for CommitDetailsTask {fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {let repo = &ctx.repo;- let timestamp = repo- .commit_timestamp(&ctx.branch_ref.commit_sha)- .map_err(|e| ctx.error(Self::KIND, e))?;- let commit_message = repo- .commit_message(&ctx.branch_ref.commit_sha)+ 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,diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rsindex fe9e9abb4..aae6fa178 100644--- a/src/git/repository/diff.rs+++ b/src/git/repository/diff.rs@@ -91,6 +91,23 @@ impl Repository {Ok(stdout.trim().to_owned())}+ /// Get commit timestamp and message in a single git command.+ ///+ /// More efficient than calling `commit_timestamp` and `commit_message` separately.+ pub fn commit_details(&self, commit: &str) -> anyhow::Result<(i64, String)> {+ // Use space separator - timestamps don't contain spaces, and %s (subject)+ // is the first line only (no embedded newlines). Split on first space.+ let stdout = self.run_command(&["show", "-s", "--format=%ct %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(' ')+ .context("Failed to parse commit details")?;+ let timestamp = timestamp_str.parse().context("Failed to parse timestamp")?;+ // Trim the message to match commit_message() behavior+ Ok((timestamp, message.trim().to_owned()))+ }+/// 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", "--format=%s", range])?;@@ -161,16 +178,24 @@ impl Repository {// Count commits using two-dot syntax (faster when merge-base is cached)// ahead = commits in head but not in merge_base// behind = commits in base but not in merge_base- let ahead_output =- self.run_command(&["rev-list", "--count", &format!("{}..{}", merge_base, head)])?;+ //+ // Skip rev-list when merge_base equals head (count would be 0).+ // Note: we don't check merge_base == base because base is typically a+ // refname like "main" while merge_base is a SHA.+ let ahead = if merge_base == head {+ 0+ } else {+ let output =+ self.run_command(&["rev-list", "--count", &format!("{}..{}", merge_base, head)])?;+ output+ .trim()+ .parse()+ .context("Failed to parse ahead count")?+ };+let behind_output =self.run_command(&["rev-list", "--count", &format!("{}..{}", merge_base, base)])?;-- let ahead: usize = ahead_output- .trim()- .parse()- .context("Failed to parse ahead count")?;- let behind: usize = behind_output+ let behind = behind_output.trim().parse().context("Failed to parse behind count")?;diff --git a/src/shell_exec.rs b/src/shell_exec.rsindex c0fbcf80a..66cc53b27 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -11,6 +11,7 @@use std::path::PathBuf;use std::process::Command;use std::sync::OnceLock;+use std::time::Instant;use crate::sync::Semaphore;@@ -18,6 +19,16 @@ use crate::sync::Semaphore;/// Prevents resource exhaustion when spawning many parallel git commands.static CMD_SEMAPHORE: OnceLock<Semaphore> = OnceLock::new();+/// Monotonic epoch for trace timestamps.+///+/// Using `Instant` instead of `SystemTime` ensures monotonic timestamps even if+/// the system clock steps backward. All trace timestamps are relative to this epoch.+static TRACE_EPOCH: OnceLock<Instant> = OnceLock::new();++fn trace_epoch() -> &'static Instant {+ TRACE_EPOCH.get_or_init(Instant::now)+}+/// Default concurrent external commands. Tuned to avoid hitting OS limits/// (file descriptors, process limits) while maintaining good parallelism.const DEFAULT_CONCURRENT_COMMANDS: usize = 32;@@ -203,20 +214,10 @@ pub fn set_command_timeout(timeout: Option<Duration>) {/// trace_instant("Progressive render: headers complete");/// ```pub fn trace_instant(event: &str) {- use std::time::{SystemTime, UNIX_EPOCH};-- let start_time_us = SystemTime::now()- .duration_since(UNIX_EPOCH)- .map(|d| d.as_micros() as u64)- .unwrap_or(0);+ let ts = Instant::now().duration_since(*trace_epoch()).as_micros() as u64;let tid = thread_id_number();- log::debug!(- "[wt-trace] ts={} tid={} event=\"{}\"",- start_time_us,- tid,- event- );+ log::debug!("[wt-trace] ts={} tid={} event=\"{}\"", ts, tid, event);}/// Execute a command with timing and debug logging.@@ -266,7 +267,7 @@ pub fn run_with_timeout(context: Option<&str>,timeout: Option<std::time::Duration>,) -> std::io::Result<std::process::Output> {- use std::time::{Instant, SystemTime, UNIX_EPOCH};+ use std::time::Instant;// Remove WORKTRUNK_DIRECTIVE_FILE to prevent hooks from writing to itcmd.env_remove(DIRECTIVE_FILE_ENV_VAR);@@ -290,14 +291,12 @@ pub fn run_with_timeout(// RAII guard ensures release even on paniclet _guard = get_semaphore().acquire();- // Capture timestamp and thread ID for Chrome Trace Format support- let start_time_us = SystemTime::now()- .duration_since(UNIX_EPOCH)- .map(|d| d.as_micros() as u64)- .unwrap_or(0);- let tid = thread_id_number();-+ // Capture monotonic timestamp and thread ID for Chrome Trace Format support.+ // Using Instant instead of SystemTime ensures monotonic timestamps even if+ // the system clock steps backward.let t0 = Instant::now();+ let ts = t0.duration_since(*trace_epoch()).as_micros() as u64;+ let tid = thread_id_number();// Execute with or without timeoutlet result = match timeout {@@ -305,49 +304,50 @@ pub fn run_with_timeout(Some(timeout_duration) => run_with_timeout_impl(cmd, timeout_duration),};- let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;+ // Use microseconds to avoid precision loss from millisecond rounding+ let dur_us = t0.elapsed().as_micros() as u64;// Log trace with timing, timestamp, and thread ID for concurrency analysismatch (&result, context) {(Ok(output), Some(ctx)) => {log::debug!(- "[wt-trace] ts={} tid={} context={} cmd=\"{}\" dur={:.1}ms ok={}",- start_time_us,+ "[wt-trace] ts={} tid={} context={} cmd=\"{}\" dur_us={} ok={}",+ ts,tid,ctx,cmd_str,- duration_ms,+ dur_us,output.status.success());}(Ok(output), None) => {log::debug!(- "[wt-trace] ts={} tid={} cmd=\"{}\" dur={:.1}ms ok={}",- start_time_us,+ "[wt-trace] ts={} tid={} cmd=\"{}\" dur_us={} ok={}",+ ts,tid,cmd_str,- duration_ms,+ dur_us,output.status.success());}(Err(e), Some(ctx)) => {log::debug!(- "[wt-trace] ts={} tid={} context={} cmd=\"{}\" dur={:.1}ms err=\"{}\"",- start_time_us,+ "[wt-trace] ts={} tid={} context={} cmd=\"{}\" dur_us={} err=\"{}\"",+ ts,tid,ctx,cmd_str,- duration_ms,+ dur_us,e);}(Err(e), None) => {log::debug!(- "[wt-trace] ts={} tid={} cmd=\"{}\" dur={:.1}ms err=\"{}\"",- start_time_us,+ "[wt-trace] ts={} tid={} cmd=\"{}\" dur_us={} err=\"{}\"",+ ts,tid,cmd_str,- duration_ms,+ dur_us,e);}diff --git a/src/trace/parse.rs b/src/trace/parse.rsindex 9e890cc61..9a37b4e5e 100644--- a/src/trace/parse.rs+++ b/src/trace/parse.rs@@ -2,19 +2,21 @@//!//! Trace lines are emitted by `shell_exec::run()` with this format://! ```text-//! [wt-trace] ts=1234567890 tid=3 context=worktree cmd="git status" dur=12.3ms ok=true-//! [wt-trace] ts=1234567890 tid=3 cmd="gh pr list" dur=45.2ms ok=false-//! [wt-trace] ts=1234567890 tid=3 context=main cmd="git merge-base" dur=100.0ms err="fatal: ..."+//! [wt-trace] ts=1234567 tid=3 context=worktree cmd="git status" dur_us=12300 ok=true+//! [wt-trace] ts=1234567 tid=3 cmd="gh pr list" dur_us=45200 ok=false+//! [wt-trace] ts=1234567 tid=3 context=main cmd="git merge-base" dur_us=100000 err="fatal: ..."//! ```//!//! Instant events (milestones without duration) use this format://! ```text-//! [wt-trace] ts=1234567890 tid=3 event="Showed skeleton"+//! [wt-trace] ts=1234567 tid=3 event="Showed skeleton"//! ```//!-//! The `ts` (timestamp in microseconds since epoch) and `tid` (thread ID) fields+//! The `ts` (timestamp in microseconds since trace epoch) and `tid` (thread ID) fields//! enable concurrency analysis and Chrome Trace Format export for visualizing//! thread utilization in tools like chrome://tracing or Perfetto.+//!+//! Both `dur_us` (microseconds, preferred) and `dur` (milliseconds, legacy) are supported.use std::time::Duration;@@ -129,11 +131,16 @@ fn parse_line(line: &str) -> Option<TraceEntry> {"cmd" => command = Some(value.to_string()),"event" => event = Some(value.to_string()),"dur" => {- // Parse "123.4ms"+ // Parse "123.4ms" (legacy format)let ms_str = value.strip_suffix("ms")?;let ms: f64 = ms_str.parse().ok()?;duration = Some(Duration::from_secs_f64(ms / 1000.0));}+ "dur_us" => {+ // Parse microseconds (new format, no precision loss)+ let us: u64 = value.parse().ok()?;+ duration = Some(Duration::from_micros(us));+ }"ok" => {let success = value == "true";result = Some(TraceResult::Completed { success });@@ -340,6 +347,18 @@ more noiseassert_eq!(entry.thread_id, None);}+ #[test]+ fn test_parse_dur_us_format() {+ // New format with microseconds (no precision loss)+ let line = r#"[wt-trace] ts=1234567 tid=3 cmd="git status" dur_us=12345 ok=true"#;+ let entry = parse_line(line).unwrap();++ let TraceEntryKind::Command { duration, .. } = &entry.kind else {+ panic!("expected command");+ };+ assert_eq!(*duration, Duration::from_micros(12345));+ }+// ========================================================================// Instant event tests// ========================================================================diff --git a/tests/integration_tests/diagnostic.rs b/tests/integration_tests/diagnostic.rsindex 76a2509a8..d0906547b 100644--- a/tests/integration_tests/diagnostic.rs+++ b/tests/integration_tests/diagnostic.rs@@ -248,8 +248,8 @@ fn test_diagnostic_verbose_log_contains_git_commands(mut repo: TestRepo) {"Verbose log should contain wt-trace entries");assert!(- verbose_section.contains("dur="),- "Verbose log should contain command durations"+ verbose_section.contains("dur_us="),+ "Verbose log should contain command durations in microseconds");assert!(verbose_section.contains("ok="),