Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Extract timestamp logic into utils module
Maximilian Roos7708200c10c8
diff --git a/src/commands/config.rs b/src/commands/config.rsindex ac0dcf935..84ea7ff8f 100644--- a/src/commands/config.rs+++ b/src/commands/config.rs@@ -12,6 +12,7 @@ use worktrunk::styling::{error_message, format_heading, format_toml, format_with_gutter, hint_message, info_message,progress_message, success_message, warning_message,};+use worktrunk::utils::get_now;use super::configure_shell::{ConfigAction, scan_shell_configs};use super::list::ci_status::CachedCiStatus;@@ -752,10 +753,7 @@ pub fn handle_state_set(key: &str, value: String, branch: Option<String>) -> any};// Store as JSON with timestamp- let now = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .expect("system clock before Unix epoch")- .as_secs();+ let now = get_now();let json = serde_json::json!({"marker": value,"set_at": nowdiff --git a/src/commands/list/ci_status.rs b/src/commands/list/ci_status.rsindex c030e8ee8..2256746b2 100644--- a/src/commands/list/ci_status.rs+++ b/src/commands/list/ci_status.rs@@ -2,6 +2,7 @@ use serde::{Deserialize, Serialize, de::DeserializeOwned};use std::process::Command;use worktrunk::git::Repository;use worktrunk::shell_exec::run;+use worktrunk::utils::get_now;/// CI platform detected from remote URL// TODO: Add a `[ci] platform = "github" | "gitlab"` override in project config@@ -1253,8 +1254,7 @@ impl PrStatus {let repo_root = repo_path.to_str()?;// Check cache first to avoid hitting API rate limits- use std::time::{SystemTime, UNIX_EPOCH};- let now_secs = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();+ let now_secs = get_now();if let Some(cached) = CachedCiStatus::read(branch, repo_root) {if cached.is_valid(local_head, now_secs, repo_root) {diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 733cdf0f6..2ab2a150c 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -562,7 +562,7 @@ pub fn handle_switch(use anyhow::Context;// Generate timestamped backup path- let timestamp = crate::display::get_now();+ let timestamp = worktrunk::utils::get_now() as i64;let datetime =chrono::DateTime::from_timestamp(timestamp, 0).unwrap_or_else(chrono::Utc::now);let suffix = datetime.format("%Y%m%d-%H%M%S").to_string();diff --git a/src/display.rs b/src/display.rsindex 4a1cf1ea3..9e342b3f4 100644--- a/src/display.rs+++ b/src/display.rs@@ -7,25 +7,13 @@//! - Terminal width detectionuse std::path::{Path, PathBuf};-use std::time::{SystemTime, UNIX_EPOCH};use worktrunk::path::format_path_for_display;+use worktrunk::utils::get_now;/// Format timestamp as abbreviated relative time (e.g., "2h")pub fn format_relative_time_short(timestamp: i64) -> String {- format_relative_time_impl(timestamp, get_now(), true)-}--/// Get current time, respecting SOURCE_DATE_EPOCH for reproducible builds/tests-pub fn get_now() -> i64 {- std::env::var("SOURCE_DATE_EPOCH")- .ok()- .and_then(|val| val.parse::<i64>().ok())- .unwrap_or_else(|| {- SystemTime::now()- .duration_since(UNIX_EPOCH)- .unwrap()- .as_secs() as i64- })+ // Cast to i64 for signed arithmetic (handles future timestamps)+ format_relative_time_impl(timestamp, get_now() as i64, true)}fn format_relative_time_impl(timestamp: i64, now: i64, short: bool) -> String {diff --git a/src/lib.rs b/src/lib.rsindex 596b7f7cd..1c77bc131 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -5,6 +5,7 @@ pub mod shell;pub mod shell_exec;pub mod styling;pub mod sync;+pub mod utils;// Re-export HookType for conveniencepub use git::HookType;diff --git a/src/utils.rs b/src/utils.rsnew file mode 100644index 000000000..f45ba5475--- /dev/null+++ b/src/utils.rs@@ -0,0 +1,44 @@+//! General utilities.++use std::time::{SystemTime, UNIX_EPOCH};++/// Get current Unix timestamp in seconds, respecting `SOURCE_DATE_EPOCH`.+///+/// When `SOURCE_DATE_EPOCH` environment variable is set, returns that value+/// instead of the actual current time. This enables reproducible builds and+/// deterministic test snapshots.+///+/// All code that needs timestamps for display or storage should use this+/// function rather than `SystemTime::now()` directly.+pub fn get_now() -> u64 {+ std::env::var("SOURCE_DATE_EPOCH")+ .ok()+ .and_then(|val| val.parse::<u64>().ok())+ .unwrap_or_else(|| {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .expect("system clock before Unix epoch")+ .as_secs()+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_get_now_returns_reasonable_timestamp() {+ let now = get_now();+ // Should be after 2020-01-01+ assert!(now > 1577836800, "get_now() should return current time");+ }++ #[test]+ fn test_get_now_respects_source_date_epoch() {+ // When SOURCE_DATE_EPOCH is set (by test harness), get_now() returns it+ if let Ok(epoch) = std::env::var("SOURCE_DATE_EPOCH") {+ let expected: u64 = epoch.parse().unwrap();+ assert_eq!(get_now(), expected);+ }+ }+}diff --git a/tests/CLAUDE.md b/tests/CLAUDE.mdindex effbfb3a8..c1687f72d 100644--- a/tests/CLAUDE.md+++ b/tests/CLAUDE.md@@ -189,4 +189,4 @@ repo.git_command(&[]);```-**For production code** that calculates age/duration, check `SOURCE_DATE_EPOCH` (see `src/display.rs::get_now()` for pattern). Using `SystemTime::now()` directly causes flaky tests.+**For production code** that needs timestamps, use `worktrunk::utils::get_now()` which respects `SOURCE_DATE_EPOCH`. Using `SystemTime::now()` directly causes flaky tests.