Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Show last fetch time in branch-not-found hint (#1877)
Maximilian Roos623a2f922163
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex a936bcaf7..48e3c388f 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -333,6 +333,7 @@ pub fn handle_state_get(key: &str, branch: Option<String>) -> anyhow::Result<()>return Err(worktrunk::git::GitError::BranchNotFound {branch: branch_name,show_create_hint: true,+ last_fetch_ago: None,}.into());}diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex 0e7e7e4b7..9734a8cd4 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -147,6 +147,7 @@ impl RepositoryCliExt for Repository {return Err(GitError::BranchNotFound {branch: branch.into(),show_create_hint: false,+ last_fetch_ago: None,}.into());}diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 2c89a2012..e35615a46 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -4,6 +4,7 @@use std::path::Path;+use crate::display::format_relative_time_short;use anyhow::Context;use color_print::cformat;use dunce::canonicalize;@@ -434,6 +435,7 @@ fn validate_worktree_creation(return Err(GitError::BranchNotFound {branch: branch.to_string(),show_create_hint: true,+ last_fetch_ago: format_last_fetch_ago(repo),}.into());}@@ -912,3 +914,17 @@ fn worktree_creation_error(command,}}++/// Format the last fetch time as a self-contained phrase for error hint parentheticals.+///+/// Returns e.g. "last fetched 3h ago" or "last fetched just now".+/// Returns `None` if FETCH_HEAD doesn't exist (never fetched).+fn format_last_fetch_ago(repo: &Repository) -> Option<String> {+ let epoch = repo.last_fetch_epoch()?;+ let relative = format_relative_time_short(epoch as i64);+ if relative == "now" || relative == "future" {+ Some("last fetched just now".to_string())+ } else {+ Some(format!("last fetched {relative} ago"))+ }+}diff --git a/src/git/error.rs b/src/git/error.rsindex 430dcb4f1..72a3b04a2 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -180,6 +180,9 @@ pub enum GitError {/// Show hint about creating the branch. Set to false for remove operations/// where suggesting creation doesn't make sense.show_create_hint: bool,+ /// Pre-formatted label for the last fetch time (e.g., "3h ago", "never").+ /// When present, the list-branches hint includes the fetch age as a parenthetical.+ last_fetch_ago: Option<String>,},/// Reference (branch, tag, commit) not found - used when any commit-ish is acceptedReferenceNotFound {@@ -404,6 +407,7 @@ impl GitError {GitError::BranchNotFound {branch,show_create_hint,+ last_fetch_ago,} => {let list_cmd = suggest_command("list", &[], &["--branches", "--remotes"]);let hint = if *show_create_hint {@@ -411,8 +415,10 @@ impl GitError {if let Some(ctx) = ctx {create_cmd = ctx.apply(create_cmd);}+ let fetch_note = last_fetch_ago.as_ref().map(|ago| cformat!(" ({ago})"));cformat!(- "To create a new branch, run <underline>{create_cmd}</>; to list branches, run <underline>{list_cmd}</>"+ "To create a new branch, run <underline>{create_cmd}</>; to list branches, run <underline>{list_cmd}</>{note}",+ note = fetch_note.as_deref().unwrap_or(""))} else {cformat!("To list branches, run <underline>{list_cmd}</>")@@ -1640,6 +1646,7 @@ mod tests {source: Box::new(GitError::BranchNotFound {branch: "emails".into(),show_create_hint: true,+ last_fetch_ago: None,}),ctx: SwitchSuggestionCtx {extra_flags: vec!["--execute=claude".into()],diff --git a/src/git/repository/config.rs b/src/git/repository/config.rsindex 9c3addf43..e16c92b68 100644--- a/src/git/repository/config.rs+++ b/src/git/repository/config.rs@@ -332,6 +332,7 @@ impl Repository {return Err(GitError::BranchNotFound {branch,show_create_hint: true,+ last_fetch_ago: None,}.into());}diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 256707599..3b93367e4 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -377,6 +377,20 @@ impl Repository {&self.git_common_dir}+ /// Get the epoch timestamp of the last `git fetch`, if available.+ ///+ /// Checks the modification time of `FETCH_HEAD` in the git common directory.+ /// Returns `None` if the file doesn't exist (never fetched) or on any I/O error.+ pub fn last_fetch_epoch(&self) -> Option<u64> {+ let fetch_head = self.git_common_dir().join("FETCH_HEAD");+ let metadata = std::fs::metadata(fetch_head).ok()?;+ let modified = metadata.modified().ok()?;+ modified+ .duration_since(std::time::UNIX_EPOCH)+ .ok()+ .map(|d| d.as_secs())+ }+/// Get the worktrunk data directory inside the git directory.////// Returns `<git-common-dir>/wt/` (typically `.git/wt/`).diff --git a/tests/integration_tests/git_error_display.rs b/tests/integration_tests/git_error_display.rsindex 3a040ac25..7254e30b9 100644--- a/tests/integration_tests/git_error_display.rs+++ b/tests/integration_tests/git_error_display.rs@@ -109,16 +109,29 @@ fn branch_not_found() {let err = GitError::BranchNotFound {branch: "nonexistent".into(),show_create_hint: true,+ last_fetch_ago: None,};assert_snapshot!("branch_not_found", err.to_string());}+#[test]+fn branch_not_found_with_fetch_time() {+ let err = GitError::BranchNotFound {+ branch: "nonexistent".into(),+ show_create_hint: true,+ last_fetch_ago: Some("last fetched 3h ago".into()),+ };++ assert_snapshot!("branch_not_found_with_fetch_time", err.to_string());+}+#[test]fn branch_not_found_no_create_hint() {let err = GitError::BranchNotFound {branch: "nonexistent".into(),show_create_hint: false,+ last_fetch_ago: None,};assert_snapshot!("branch_not_found_no_create_hint", err.to_string());diff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__branch_not_found_with_fetch_time.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__branch_not_found_with_fetch_time.snapnew file mode 100644index 000000000..b4b09a470--- /dev/null+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__branch_not_found_with_fetch_time.snap@@ -0,0 +1,6 @@+---+source: tests/integration_tests/git_error_display.rs+expression: err.to_string()+---+[31m✗[39m [31mNo branch named [1mnonexistent[22m[39m+[2m↳[22m [2mTo create a new branch, run [4mwt switch --create nonexistent[24m; to list branches, run [4mwt list --branches --remotes[24m (last fetched 3h ago)[22mdiff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 27b0257c0..cb98ffe9e 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -362,6 +362,30 @@ fn test_switch_nonexistent_branch(repo: TestRepo) {snapshot_switch("switch_nonexistent_branch", &repo, &["nonexistent-branch"]);}+#[rstest]+fn test_switch_nonexistent_branch_with_fetch_time(repo: TestRepo) {+ // When FETCH_HEAD exists, the hint should include "last fetched X ago".+ let git_dir = repo.root_path().join(".git");+ fs::write(git_dir.join("FETCH_HEAD"), "").unwrap();++ // Set TEST_EPOCH to 3 hours after the real mtime so the file appears "3h ago"+ let mtime = fs::metadata(git_dir.join("FETCH_HEAD"))+ .unwrap()+ .modified()+ .unwrap()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_secs();+ let epoch_3h_later = mtime + 3 * 3600;++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["nonexistent-branch"], None);+ cmd.env("WORKTRUNK_TEST_EPOCH", epoch_3h_later.to_string());+ assert_cmd_snapshot!("switch_nonexistent_with_fetch_time", cmd);+ });+}+#[rstest]fn test_switch_base_accepts_commitish(repo: TestRepo) {// Issue #630: --base should accept any commit-ish, not just branch namesdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_nonexistent_with_fetch_time.snap b/tests/snapshots/integration__integration_tests__switch__switch_nonexistent_with_fetch_time.snapnew file mode 100644index 000000000..79f1e4b74--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_nonexistent_with_fetch_time.snap@@ -0,0 +1,46 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - nonexistent-branch+ 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: ""+ 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: "1775079226"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m✗[39m [31mNo branch named [1mnonexistent-branch[22m[39m+[2m↳[22m [2mTo create a new branch, run [4mwt switch --create nonexistent-branch[24m; to list branches, run [4mwt list --branches --remotes[24m (last fetched 3h ago)[22m