Skip to content

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

refactor(error): split short Display from styled Diagnostic (#2611)

Maximilian Roosa9b92cff894b
diff --git a/CLAUDE.md b/CLAUDE.md
index 99ac34160..5d2284050 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -259,11 +259,11 @@ When no structured alternative exists, document the fragility inline.
**Implementation:**
- Signal-derived child exits surface as `WorktrunkError::ChildProcessExited { signal: Some(sig), .. }`. The `signal` field is the structured channel — never sniff `code >= 128` or parse error messages.
-- Use `worktrunk::git::interrupt_exit_code(&err)` to detect them. When it returns `Some(exit_code)`, propagate via `WorktrunkError::AlreadyDisplayed { exit_code }` (`128 + sig` by convention — 130 for SIGINT, 143 for SIGTERM) and break the loop.
+- Use `err.interrupt_exit_code()` (from the `worktrunk::git::ErrorExt` trait) to detect them. When it returns `Some(exit_code)`, propagate via `WorktrunkError::AlreadyDisplayed { exit_code }` (`128 + sig` by convention — 130 for SIGINT, 143 for SIGTERM) and break the loop.
- The check happens **before** any `FailureStrategy` branch — Warn must NOT swallow signal-derived errors.
- `handle_command_error` in `src/commands/command_executor.rs` enforces the policy for hook and alias pipelines (foreground and concurrent groups). `for_each.rs` enforces it directly for the worktree loop.
-When adding a new code path that loops over child processes, run `interrupt_exit_code` on per-iteration errors and break.
+When adding a new code path that loops over child processes, call `.interrupt_exit_code()` on per-iteration errors and break.
## Hook Output Logs
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 6b10f256a..9f27e2e11 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -8,7 +8,7 @@ use worktrunk::config::{
Command, CommandConfig, HookStep, UserConfig, expand_template, format_hook_variables,
template_references_var, validate_template_syntax,
};
-use worktrunk::git::{Repository, WorktrunkError, interrupt_exit_code};
+use worktrunk::git::{ErrorExt, Repository, WorktrunkError};
use worktrunk::path::{format_path_for_display, to_posix_path};
use worktrunk::styling::{
eprintln, error_message, format_bash_with_gutter, format_with_gutter, info_message,
@@ -634,7 +634,7 @@ fn handle_command_error(
error_wrapper: &ErrorWrapper,
failure_strategy: FailureStrategy,
) -> anyhow::Result<()> {
- if let Some(exit_code) = interrupt_exit_code(&err) {
+ if let Some(exit_code) = err.interrupt_exit_code() {
return Err(WorktrunkError::AlreadyDisplayed { exit_code }.into());
}
diff --git a/src/commands/config/show.rs b/src/commands/config/show.rs
index 2a6daca93..4834dd11f 100644
--- a/src/commands/config/show.rs
+++ b/src/commands/config/show.rs
@@ -12,7 +12,7 @@ use color_print::cformat;
use worktrunk::config::{
ProjectConfig, UserConfig, default_system_config_path, system_config_path,
};
-use worktrunk::git::Repository;
+use worktrunk::git::{ErrorExt, Repository};
use worktrunk::path::format_path_for_display;
use worktrunk::shell::{FileDetectionResult, Shell, scan_for_detection_details};
use worktrunk::shell_exec::Cmd;
@@ -420,7 +420,10 @@ fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {
"Commit generation failed (<bold>{command_display}</>)"
))
)?;
- writeln!(out, "{}", format_with_gutter(&e.to_string(), None))?;
+ // Use the typed diagnostic block (with hint, gutter, etc.)
+ // when present; otherwise fall back to the short Display label.
+ let body = e.render_diagnostic().unwrap_or_else(|| e.to_string());
+ writeln!(out, "{}", format_with_gutter(&body, None))?;
}
}
}
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index 422ea1760..e707ecc5b 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -30,7 +30,7 @@ use std::process::Stdio;
use color_print::cformat;
use worktrunk::config::{UserConfig, expand_template};
-use worktrunk::git::{Repository, WorktreeInfo, WorktrunkError, interrupt_exit_code};
+use worktrunk::git::{ErrorExt, Repository, WorktreeInfo, WorktrunkError};
use worktrunk::shell_exec::Cmd;
use worktrunk::styling::{
eprintln, error_message, format_with_gutter, progress_message, success_message, warning_message,
@@ -105,32 +105,35 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
}
}
Err(err) => {
- let signal_exit = interrupt_exit_code(&err);
- let (exit_info, exit_code, error_msg, show_detail) =
+ let signal_exit = err.interrupt_exit_code();
+ // Two error strings: a styled block for stderr (preserves
+ // hints from typed diagnostics) and a plain string for
+ // JSON (consumers shouldn't see ANSI codes or symbols).
+ let (exit_info, exit_code, stderr_detail, json_detail) =
if let Some(WorktrunkError::ChildProcessExited { code, message, .. }) =
err.downcast_ref::<WorktrunkError>()
{
(
format!(" (exit code {code})"),
serde_json::json!(code),
+ None,
message.clone(),
- false,
)
} else {
- let msg = err.to_string();
+ let styled = err.render_diagnostic().unwrap_or_else(|| err.to_string());
(
" (spawn failed)".to_string(),
serde_json::json!(null),
- msg,
- true,
+ Some(styled),
+ err.to_string(),
)
};
eprintln!(
"{}",
error_message(cformat!("Failed in <bold>{display_name}</>{exit_info}"))
);
- if show_detail {
- eprintln!("{}", format_with_gutter(&error_msg, None));
+ if let Some(detail) = &stderr_detail {
+ eprintln!("{}", format_with_gutter(detail, None));
}
failed.push(display_name.to_string());
if json_mode {
@@ -139,7 +142,7 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
"path": wt.path,
"exit_code": exit_code,
"success": false,
- "error": error_msg,
+ "error": json_detail,
}));
}
if let Some(code) = signal_exit {
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index e1ae8c448..5a0b4f292 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -10,7 +10,7 @@ use anyhow::Context;
use color_print::cformat;
use worktrunk::HookType;
use worktrunk::config::{CommandConfig, UserConfig, format_hook_variables};
-use worktrunk::git::Repository;
+use worktrunk::git::{Repository, add_hook_skip_hint};
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{
eprintln, format_with_gutter, info_message, progress_message, verbosity, warning_message,
@@ -752,7 +752,7 @@ pub(crate) fn execute_hook(
},
failure_strategy,
)
- .map_err(worktrunk::git::add_hook_skip_hint)
+ .map_err(add_hook_skip_hint)
}
#[cfg(test)]
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index 1434397b8..b2d640da1 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -234,7 +234,7 @@ use crossbeam_channel as chan;
use dunce::canonicalize;
use once_cell::sync::OnceCell;
use rayon::prelude::*;
-use worktrunk::git::{LocalBranch, Repository, WorktreeInfo};
+use worktrunk::git::{ErrorExt, LocalBranch, Repository, WorktreeInfo};
use worktrunk::styling::{
INFO_SYMBOL, eprintln, format_with_gutter, hint_message, warning_message,
};
@@ -750,7 +750,7 @@ pub fn collect(
let commit_details_map = repo.commit_details_many(&all_shas).unwrap_or_else(|err| {
// Surface git's actual stderr (when available via the typed leaf)
// rather than our `CommandError` summary.
- let detail = worktrunk::git::display_message(&err);
+ let detail = err.display_message();
eprintln!(
"{}",
warning_message(cformat!("Failed to batch-fetch commit details: {detail}"))
diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rs
index c0a2cc7e7..81244dd97 100644
--- a/src/commands/list/collect/tasks.rs
+++ b/src/commands/list/collect/tasks.rs
@@ -9,7 +9,7 @@ use std::time::Duration;
use std::sync::Arc;
use anyhow::Context;
-use worktrunk::git::{IntegrationTargets, LineDiff, RefSnapshot, Repository};
+use worktrunk::git::{ErrorExt, IntegrationTargets, LineDiff, RefSnapshot, Repository};
use super::super::ci_status::{CiBranchName, PrStatus};
use super::super::model::{
@@ -88,7 +88,7 @@ impl TaskContext {
// user sees git's actual error message (e.g., "fatal: bad object
// HEAD") rather than our single-line `CommandError` summary
// ("git status --porcelain failed (exit 128)").
- let message = worktrunk::git::display_message(err);
+ let message = err.display_message();
TaskError::new(self.item_idx, kind, message, cause)
}
diff --git a/src/commands/relocate.rs b/src/commands/relocate.rs
index cc3bfa6a0..41aa213bb 100644
--- a/src/commands/relocate.rs
+++ b/src/commands/relocate.rs
@@ -26,7 +26,7 @@ use std::path::{Path, PathBuf};
use anyhow::Context;
use color_print::cformat;
use worktrunk::config::UserConfig;
-use worktrunk::git::{Repository, WorktreeInfo};
+use worktrunk::git::{ErrorExt, Repository, WorktreeInfo};
use worktrunk::path::{format_path_for_display, paths_match};
use worktrunk::styling::{
eprintln, format_with_gutter, hint_message, info_message, progress_message, success_message,
@@ -197,7 +197,9 @@ pub fn gather_candidates(
"Skipping <bold>{branch}</> due to template error:"
))
);
- eprintln!("{}", e);
+ // Render the styled diagnostic block (Display is just the short label).
+ let rendered = e.render_diagnostic().unwrap_or_else(|| e.to_string());
+ eprintln!("{rendered}");
template_error_branches.push(branch.to_string());
}
}
diff --git a/src/commands/run_pipeline.rs b/src/commands/run_pipeline.rs
index 26b563389..a6d9bce2b 100644
--- a/src/commands/run_pipeline.rs
+++ b/src/commands/run_pipeline.rs
@@ -310,7 +310,7 @@ fn format_signal(sig: i32) -> String {
mod tests {
use super::*;
use std::os::unix::process::ExitStatusExt;
- use worktrunk::git::interrupt_exit_code;
+ use worktrunk::git::ErrorExt;
fn downcast_child_exit(err: &anyhow::Error) -> (i32, Option<i32>, String) {
match err.downcast_ref::<WorktrunkError>() {
@@ -350,7 +350,7 @@ mod tests {
assert_eq!(code, expected_code, "exit code for {sig}");
assert_eq!(message, expected_msg, "message for {sig}");
assert_eq!(
- interrupt_exit_code(&err),
+ err.interrupt_exit_code(),
Some(expected_code),
"interrupt_exit_code for {sig}",
);
@@ -367,6 +367,6 @@ mod tests {
assert_eq!(code, 2);
assert_eq!(message, "command failed with exit code 2: my-step");
// Non-signal errors must NOT trip the interrupt abort path.
- assert_eq!(interrupt_exit_code(&err), None);
+ assert_eq!(err.interrupt_exit_code(), None);
}
}
diff --git a/src/commands/step/rebase.rs b/src/commands/step/rebase.rs
index 86cca53f3..2a2d344e9 100644
--- a/src/commands/step/rebase.rs
+++ b/src/commands/step/rebase.rs
@@ -2,7 +2,7 @@
use anyhow::Context;
use color_print::cformat;
-use worktrunk::git::Repository;
+use worktrunk::git::{ErrorExt, Repository};
use worktrunk::styling::{eprintln, progress_message, success_message};
use super::super::repository_ext::RepositoryCliExt;
@@ -53,7 +53,7 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {
// Pull git's stderr from the typed leaf when present so we get the
// raw conflict-marker bytes regardless of how many `.context(...)`
// layers wrap the error.
- let detail = worktrunk::git::display_message(&e);
+ let detail = e.display_message();
if is_rebasing {
return Err(worktrunk::git::GitError::RebaseConflict {
target_branch: integration_target,
diff --git a/src/commands/worktree/push.rs b/src/commands/worktree/push.rs
index 39b9a0d53..a30a17dda 100644
--- a/src/commands/worktree/push.rs
+++ b/src/commands/worktree/push.rs
@@ -8,7 +8,7 @@ use std::path::PathBuf;
use anyhow::Context;
use color_print::cformat;
-use worktrunk::git::{GitError, Repository};
+use worktrunk::git::{ErrorExt, GitError, Repository};
use worktrunk::styling::{
eprintln, format_with_gutter, info_message, progress_message, success_message, warning_message,
};
@@ -315,7 +315,7 @@ pub fn handle_push(
])
.map_err(|e| GitError::PushFailed {
target_branch: ctx.target_branch.clone(),
- error: worktrunk::git::display_message(&e),
+ error: e.display_message(),
})?;
ctx.restore_stash();
@@ -411,10 +411,7 @@ pub fn handle_no_ff_merge(
.run_command(&["update-ref", &target_ref, &merge_sha, &ctx.target_tip])
.map_err(|e| GitError::PushFailed {
target_branch: ctx.target_branch.clone(),
- error: format!(
- "Failed to update ref: {}",
- worktrunk::git::display_message(&e)
- ),
+ error: format!("Failed to update ref: {}", e.display_message()),
})?;
// Sync the target worktree's working tree if it exists.
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index d2bf129d2..71488420e 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -21,7 +21,7 @@ use minijinja::{Environment, ErrorKind, UndefinedBehavior, Value};
use regex::Regex;
use shell_escape::escape;
-use crate::git::{HookType, Repository};
+use crate::git::{Diagnostic, HookType, Repository};
use crate::path::to_posix_path;
use crate::styling::{
eprintln, error_message, format_bash_with_gutter, format_with_gutter, hint_message,
@@ -514,6 +514,12 @@ pub struct TemplateExpandError {
impl std::fmt::Display for TemplateExpandError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.message)
+ }
+}
+
+impl Diagnostic for TemplateExpandError {
+ fn render(&self) -> String {
let mut parts = vec![error_message(&self.message).to_string()];
if let Some(ref line) = self.source_line {
parts.push(format_with_gutter(line, None));
@@ -532,7 +538,7 @@ impl std::fmt::Display for TemplateExpandError {
.to_string(),
);
}
- write!(f, "{}", parts.join("\n"))
+ parts.join("\n")
}
}
@@ -1112,8 +1118,8 @@ mod tests {
assert!(err.message.contains("syntax error"), "got: {}", err.message);
assert!(expand_template("{{ 1 + }}", &vars, false, &test.repo, "test").is_err());
- // Display impl renders source line but no available vars hint for syntax errors
- assert_snapshot!(err, @"
+ // Diagnostic::render produces source line but no available vars hint for syntax errors
+ assert_snapshot!(crate::git::Diagnostic::render(&err), @"
✗ Failed to expand test: syntax error: unexpected end of input, expected end of variable block @ line 1
  {{ unclosed
");
@@ -1137,8 +1143,8 @@ mod tests {
assert!(err.available_vars.contains(&"remote".to_string()));
assert_eq!(err.source_line.as_deref(), Some("echo {{ target }}"));
- // Display impl renders source line and available vars hint
- assert_snapshot!(err, @"
+ // Diagnostic::render produces source line and available vars hint
+ assert_snapshot!(crate::git::Diagnostic::render(&err), @"
✗ Failed to expand test: undefined value @ line 1
  echo {{ target }}
↳ Available variables: branch, remote
diff --git a/src/git/error.rs b/src/git/error.rs
index a0eff75ff..ec10226f6 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -4,22 +4,34 @@
//!
//! - **`GitError`** - A typed enum for domain errors that can be pattern-matched
//! and tested. Use `.into()` to convert to `anyhow::Error` while preserving the
-//! type for pattern matching. Display produces styled output for users.
+//! type for pattern matching.
//!
//! - **`WorktrunkError`** - A minimal enum for semantic errors that need
//! special handling (exit codes, silent errors).
+//!
+//! ## Display vs. Diagnostic
+//!
+//! Each typed error has two faces:
+//!
+//! - [`Display`](std::fmt::Display) is a single-line label suitable for
+//! embedding in another error's message field (e.g.,
+//! `GitError::Other.message: format!("…: {e}")`).
+//! - [`Diagnostic::render`] is the rich terminal block — emoji, color,
+//! gutter, follow-up hints. The renderer in `main.rs` walks the anyhow
+//! chain looking for the first type that implements `Diagnostic` and
+//! emits its rendered output.
use std::borrow::Cow;
use std::path::PathBuf;
-use color_print::{cformat, cwrite};
+use color_print::cformat;
use shell_escape::escape;
use super::HookType;
use crate::path::format_path_for_display;
use crate::styling::{
- ERROR_SYMBOL, HINT_SYMBOL, error_message, format_bash_with_gutter, format_with_gutter,
- hint_message, info_message, suggest_command,
+ error_message, format_bash_with_gutter, format_with_gutter, hint_message, info_message,
+ suggest_command,
};
/// Platform-specific reference type (PR vs MR).
@@ -93,6 +105,68 @@ pub trait RefContext {
fn source_ref(&self) -> String;
}
+/// Multi-line styled rendering for terminal display.
+///
+/// See the module docstring for the contract: types implementing
+/// `Diagnostic` keep [`Display`](std::fmt::Display) as a short single-line
+/// label and place the styled multi-line output (emoji, color, gutter,
+/// follow-up hints) here.
+pub trait Diagnostic {
+ /// Render the full styled block. Returned string has no trailing newline.
+ fn render(&self) -> String;
+}
+
+/// Worktrunk-specific extension methods on [`anyhow::Error`].
+///
+/// Bring this trait into scope (`use worktrunk::git::ErrorExt;`) to use
+/// method syntax on anyhow errors:
+///
+/// ```text
+/// if let Some(code) = err.exit_code() { ... }
+/// let detail = err.display_message();
+/// let rendered = err.render_diagnostic().unwrap_or_else(|| err.to_string());
+/// ```
+pub trait ErrorExt {
+ /// Render the first [`Diagnostic`]-implementing error in the chain.
+ ///
+ /// Returns `None` when the chain has no typed diagnostic — callers
+ /// typically fall back to `error.to_string()`.
+ fn render_diagnostic(&self) -> Option<String>;
+
+ /// User-facing detail string for an error that may carry a [`CommandError`].
+ ///
+ /// When a [`CommandError`] is anywhere in the chain, returns its captured
+ /// stderr/stdout via [`CommandError::combined_output`] — that's git's actual
+ /// error message, often multi-line. Otherwise falls back to the top-level
+ /// `Display`, which under the [`Diagnostic`] split is the typed error's
+ /// short single-line label.
+ ///
+ /// Use this when embedding a sub-error's text inside another typed error's
+ /// message field (e.g., `GitError::WorktreeRemovalFailed::error`,
+ /// `GitError::PushFailed::error`) so the user sees git's real reason
+ /// rather than just the [`CommandError`] single-line summary.
+ fn display_message(&self) -> String;
+
+ /// Extract a propagatable exit code from the error.
+ ///
+ /// Looks through [`HookErrorWithHint`] wrappers and matches on
+ /// [`WorktrunkError`] variants that carry an exit code.
+ fn exit_code(&self) -> Option<i32>;
+
+ /// If the error is signal-derived, return the equivalent shell exit
+ /// code (`128 + signal`).
+ ///
+ /// Implements the Ctrl-C cancellation policy: command loops call this
+ /// on every per-iteration failure and, when it returns `Some`, abort
+ /// the loop rather than continuing. The returned code preserves the
+ /// standard `128 + sig` shell convention (130 for SIGINT, 143 for
+ /// SIGTERM).
+ ///
+ /// See the "Signal Handling" section of the project `CLAUDE.md` for
+ /// the rationale and the full list of loops that apply this policy.
+ fn interrupt_exit_code(&self) -> Option<i32>;
+}
+
/// Information about a failed command, for display in error messages.
///
/// Separates the command string from exit information so Display impls
@@ -167,6 +241,15 @@ impl CommandError {
}
}
+ /// Walk an [`anyhow::Error`] chain for a [`CommandError`].
+ ///
+ /// Returns the first match. Useful for renderers and callers that
+ /// need the raw stderr regardless of how many `.context(...)` layers
+ /// wrap it.
+ pub fn find_in(error: &anyhow::Error) -> Option<&CommandError> {
+ error.chain().find_map(|e| e.downcast_ref::<CommandError>())
+ }
+
/// stderr + stdout, trimmed and joined by `\n`, with empty pieces
/// dropped. Mirrors the legacy `bail!("{}", error_msg)` payload so
/// callers that previously parsed `e.to_string()` (notably
@@ -191,28 +274,47 @@ impl std::fmt::Display for CommandError {
impl std::error::Error for CommandError {}
-/// Walk an anyhow chain looking for a [`CommandError`].
-///
-/// Returns the first match. Useful for renderers and callers that need the
-/// raw stderr regardless of how many `.context(...)` layers wrap it.
-pub fn find_command_error(error: &anyhow::Error) -> Option<&CommandError> {
- error.chain().find_map(|e| e.downcast_ref::<CommandError>())
+impl Diagnostic for CommandError {
+ fn render(&self) -> String {
+ let header = error_message(self.to_string()).to_string();
+ let body = self.combined_output();
+ if body.is_empty() {
+ header
+ } else {
+ format!("{header}\n{}", format_with_gutter(&body, None))
+ }
+ }
}
-/// User-facing detail string for an error that may carry a [`CommandError`].
+/// Render `err` via [`Diagnostic`] if it's a typed diagnostic, else `None`.
+///
+/// Rust trait objects can't be trait-downcast (you can't ask `&dyn Error`
+/// "do you implement `Diagnostic`?"), so this helper enumerates every
+/// known type with a `Diagnostic` impl. Add new types here when they
+/// grow one.
///
-/// When a [`CommandError`] is anywhere in the chain, returns its captured
-/// stderr/stdout via [`CommandError::combined_output`] — that's git's actual
-/// error message. Otherwise falls back to the rendered top-level string.
+/// Order matters only inasmuch as we want the most specific wrapper
+/// first ([`HookErrorWithHint`] before its [`WorktrunkError`] source).
///
-/// Use this when embedding a sub-error's text inside another typed error's
-/// message field (e.g., `GitError::WorktreeRemovalFailed::error`,
-/// `GitError::PushFailed::error`) so the user sees git's real reason rather
-/// than the [`CommandError`] single-line summary.
-pub fn display_message(error: &anyhow::Error) -> String {
- find_command_error(error)
- .map(|cmd_err| cmd_err.combined_output())
- .unwrap_or_else(|| error.to_string())
+/// To render the first typed diagnostic anywhere in an [`anyhow::Error`]'s
+/// chain, use [`ErrorExt::render_diagnostic`].
+pub fn try_render_diagnostic(err: &(dyn std::error::Error + 'static)) -> Option<String> {
+ if let Some(e) = err.downcast_ref::<GitError>() {
+ return Some(e.render());
+ }
+ if let Some(e) = err.downcast_ref::<HookErrorWithHint>() {
+ return Some(e.render());
+ }
+ if let Some(e) = err.downcast_ref::<WorktrunkError>() {
+ return Some(e.render());
+ }
+ if let Some(e) = err.downcast_ref::<crate::config::TemplateExpandError>() {
+ return Some(e.render());
+ }
+ if let Some(e) = err.downcast_ref::<CommandError>() {
+ return Some(e.render());
+ }
+ None
}
/// Extra CLI context for enriching `wt switch` suggestions in error hints.
@@ -256,12 +358,16 @@ impl SwitchSuggestionCtx {
///
/// This enum provides structured error data that can be pattern-matched and tested.
/// Each variant stores the data needed to construct a user-facing error message.
-/// Display produces styled output with emoji and colors.
+///
+/// [`Display`](std::fmt::Display) is a short single-line label per variant
+/// suitable for embedding in another error's message field;
+/// [`Diagnostic::render`] produces the rich styled block (emoji, color,
+/// gutter, follow-up hints).
///
/// # Usage
///
/// ```ignore
-/// // Return a typed error (Display produces styled output)
+/// // Return a typed error
/// return Err(GitError::DetachedHead { action: Some("merge".into()) }.into());
///
/// // Pattern match on errors
@@ -452,28 +558,229 @@ pub enum GitError {
impl std::error::Error for GitError {}
impl GitError {
- /// Format with optional switch suggestion context.
+ /// Styled title for this variant (first line, with inline `<bold>`
+ /// highlights on entity names like branch and path).
+ ///
+ /// Single source of truth: [`Diagnostic::render`] uses this directly
+ /// for the header; the [`std::fmt::Display`] impl strips ANSI codes
+ /// (via [`ansi_str::AnsiStr::ansi_strip`]) for embedding into other
+ /// error messages or non-terminal sinks like JSON.
+ fn title(&self) -> String {
+ match self {
+ GitError::WithSwitchSuggestion { source, .. } => source.title(),
+
+ GitError::DetachedHead { action } => match action {
+ Some(action) => cformat!("Cannot {action}: not on a branch (detached HEAD)"),
+ None => "Not on a branch (detached HEAD)".to_string(),
+ },
+
+ GitError::UncommittedChanges { action, branch, .. } => match (action, branch) {
+ (Some(action), Some(b)) => {
+ cformat!("Cannot {action}: <bold>{b}</> has uncommitted changes")
+ }
+ (Some(action), None) => {
+ format!("Cannot {action}: working tree has uncommitted changes")
+ }
+ (None, Some(b)) => cformat!("<bold>{b}</> has uncommitted changes"),
+ (None, None) => "Working tree has uncommitted changes".to_string(),
+ },
+
+ GitError::BranchAlreadyExists { branch } => {
+ cformat!("Branch <bold>{branch}</> already exists")
+ }
+
+ GitError::BranchNotFound { branch, .. } => {
+ cformat!("No branch named <bold>{branch}</>")
+ }
+
+ GitError::ReferenceNotFound { reference } => {
+ cformat!("No branch, tag, or commit named <bold>{reference}</>")
+ }
+
+ GitError::StaleDefaultBranch { branch } => {
+ cformat!("Default branch <bold>{branch}</> does not exist locally")
+ }
+
+ GitError::NotInWorktree { action } => match action {
+ Some(action) => format!("Cannot {action}: not in a worktree"),
+ None => "Not in a worktree".to_string(),
+ },
+
+ GitError::WorktreeMissing { branch } => {
+ cformat!("Worktree directory missing for <bold>{branch}</>")
+ }
+
+ GitError::RemoteOnlyBranch { branch, remote } => {
+ cformat!("Branch <bold>{branch}</> exists only on remote ({remote}/{branch})")
+ }
+
+ GitError::WorktreePathOccupied {
+ branch,
+ path,
+ occupant,
+ } => {
+ let path_display = format_path_for_display(path);
+ match occupant {
+ Some(occupant_branch) => cformat!(
+ "Cannot switch to <bold>{branch}</> — there's a worktree at the expected path <bold>{path_display}</> on branch <bold>{occupant_branch}</>"
+ ),
+ None => cformat!(
+ "Cannot switch to <bold>{branch}</> — there's a detached worktree at the expected path <bold>{path_display}</>"
+ ),
+ }
+ }
+
+ GitError::WorktreePathExists { path, .. } => {
+ let path_display = format_path_for_display(path);
+ cformat!("Directory already exists: <bold>{path_display}</>")
+ }
+
+ GitError::WorktreeCreationFailed {
+ branch,
+ base_branch,
+ ..
+ } => match base_branch {
+ Some(base) => cformat!(
+ "Failed to create worktree for <bold>{branch}</> from base <bold>{base}</>"
+ ),
+ None => cformat!("Failed to create worktree for <bold>{branch}</>"),
+ },
+
+ GitError::WorktreeRemovalFailed { branch, path, .. } => {
+ let path_display = format_path_for_display(path);
+ cformat!(
+ "Failed to remove worktree for <bold>{branch}</> @ <bold>{path_display}</>"
+ )
+ }
+
+ GitError::CannotRemoveMainWorktree => "The main worktree cannot be removed".to_string(),
+
+ GitError::CannotRemoveDefaultBranch { branch } => {
+ cformat!("Cannot remove the default branch <bold>{branch}</>")
+ }
+
+ GitError::WorktreeLocked { branch, reason, .. } => {
+ let reason_text = match reason {
+ Some(r) if !r.is_empty() => format!(" ({r})"),
+ _ => String::new(),
+ };
+ cformat!("Cannot remove <bold>{branch}</>, worktree is locked{reason_text}")
+ }
+
+ GitError::ConflictingChanges { target_branch, .. } => cformat!(
+ "Can't push to local <bold>{target_branch}</> branch: conflicting uncommitted changes"
+ ),
+
+ GitError::NotFastForward { target_branch, .. } => cformat!(
+ "Can't push to local <bold>{target_branch}</> branch: it has newer commits"
+ ),
+
+ GitError::RebaseConflict { target_branch, .. } => {
+ cformat!("Rebase onto <bold>{target_branch}</> incomplete")
+ }
+
+ GitError::NotRebased { target_branch } => {
+ cformat!("Branch not rebased onto <bold>{target_branch}</>")
+ }
+
+ GitError::PushFailed { target_branch, .. } => {
+ cformat!("Can't push to local <bold>{target_branch}</> branch")
+ }
+
+ GitError::NotInteractive => {
+ "Cannot prompt for approval in non-interactive environment".to_string()
+ }
+
+ GitError::HookCommandNotFound { name, available } => {
+ if available.is_empty() {
+ cformat!("No command named <bold>{name}</> (hook has no named commands)")
+ } else {
+ let styled_list = available
+ .iter()
+ .map(|s| cformat!("<bold>{s}</>"))
+ .collect::<Vec<_>>()
+ .join(", ");
+ cformat!("No command named <bold>{name}</> (available: {styled_list})")
+ }
+ }
+
+ GitError::LlmCommandFailed { .. } => "Commit generation command failed".to_string(),
+
+ GitError::ProjectConfigNotFound { .. } => "No project configuration found".to_string(),
+
+ GitError::ParseError { message } => message.clone(),
+
+ GitError::WorktreeIncludeParseError { .. } => {
+ cformat!("Error parsing <bold>.worktreeinclude</>")
+ }
+
+ GitError::WorktreeNotFound { branch } => {
+ cformat!("Branch <bold>{branch}</> has no worktree")
+ }
+
+ GitError::RefCreateConflict {
+ ref_type,
+ number,
+ branch,
+ } => {
+ let name = ref_type.name();
+ let syntax = ref_type.syntax();
+ cformat!(
+ "Cannot create branch for <bold>{syntax}{number}</> — {name} already has branch <bold>{branch}</>"
+ )
+ }
+
+ GitError::RefBaseConflict { ref_type, number } => {
+ let syntax = ref_type.syntax();
+ cformat!("Cannot use <bold>--base</> with <bold>{syntax}{number}</>")
+ }
+
+ GitError::BranchTracksDifferentRef {
+ branch,
+ ref_type,
+ number,
+ } => {
+ let name = ref_type.name();
+ let symbol = ref_type.symbol();
+ cformat!(
+ "Branch <bold>{branch}</> exists but doesn't track {name} {symbol}{number}"
+ )
+ }
+
+ GitError::NoRemoteForRepo { owner, repo, .. } => {
+ cformat!("No remote found for <bold>{owner}/{repo}</>")
+ }
+
+ GitError::CliApiError { message, .. } => message.clone(),
+
+ GitError::Other { message } => message.clone(),
+ }
+ }
+
+ /// Write the styled diagnostic block, with optional switch-suggestion
+ /// context propagated from a [`GitError::WithSwitchSuggestion`] wrapper.
///
/// Most variants ignore `ctx`. The three that render `wt switch` suggestions
/// (`BranchAlreadyExists`, `BranchNotFound`, `WorktreePathExists`) use it
/// to append extra flags and trailing args for a copy-pasteable command.
- fn fmt_with_ctx(
+ ///
+ /// Called internally by [`Diagnostic::render`]; not part of the public API.
+ fn write_render_with_ctx<W: std::fmt::Write>(
&self,
- f: &mut std::fmt::Formatter<'_>,
+ f: &mut W,
ctx: Option<&SwitchSuggestionCtx>,
) -> std::fmt::Result {
match self {
- GitError::WithSwitchSuggestion { source, ctx } => source.fmt_with_ctx(f, Some(ctx)),
+ GitError::WithSwitchSuggestion { source, ctx } => {
+ source.write_render_with_ctx(f, Some(ctx))
+ }
- GitError::DetachedHead { action } => {
- let message = match action {
- Some(action) => cformat!("Cannot {action}: not on a branch (detached HEAD)"),
- None => "Not on a branch (detached HEAD)".to_string(),
- };
+ GitError::DetachedHead { .. } => {
+ let title = self.title();
write!(
f,
"{}\n{}",
- error_message(&message),
+ error_message(&title),
hint_message(cformat!(
"To switch to a branch, run <underline>git switch <<branch>></>"
))
@@ -481,22 +788,9 @@ impl GitError {
}
GitError::UncommittedChanges {
- action,
- branch,
- force_hint,
+ branch, force_hint, ..
} => {
- let message = match (action, branch) {
- (Some(action), Some(b)) => {
- cformat!("Cannot {action}: <bold>{b}</> has uncommitted changes")
- }
- (Some(action), None) => {
- cformat!("Cannot {action}: working tree has uncommitted changes")
- }
- (None, Some(b)) => {
- cformat!("<bold>{b}</> has uncommitted changes")
- }
- (None, None) => cformat!("Working tree has uncommitted changes"),
- };
+ let title = self.title();
let hint = if *force_hint {
// Construct full command: "wt remove [branch] --force"
let args: Vec<&str> = branch.as_deref().into_iter().collect();
@@ -507,10 +801,11 @@ impl GitError {
} else {
"Commit or stash changes first".to_string()
};
- write!(f, "{}\n{}", error_message(&message), hint_message(hint))
+ write!(f, "{}\n{}", error_message(&title), hint_message(hint))
}
GitError::BranchAlreadyExists { branch } => {
+ let title = self.title();
let mut switch_cmd = suggest_command("switch", &[branch], &[]);
if let Some(ctx) = ctx {
switch_cmd = ctx.apply(switch_cmd);
@@ -518,7 +813,7 @@ impl GitError {
write!(
f,
"{}\n{}",
- error_message(cformat!("Branch <bold>{branch}</> already exists")),
+ error_message(&title),
hint_message(cformat!(
"To switch to the existing branch, run without <underline>--create</>: <underline>{switch_cmd}</>"
))
@@ -531,6 +826,7 @@ impl GitError {
last_fetch_ago,
pr_mr_platform,
} => {
+ let title = self.title();
let list_cmd = suggest_command("list", &[], &["--branches", "--remotes"]);
let fetch_note = last_fetch_ago
.as_ref()
@@ -557,93 +853,73 @@ impl GitError {
} else {
cformat!("To list branches, run <underline>{list_cmd}</>")
};
- write!(
- f,
- "{}\n{}",
- error_message(cformat!("No branch named <bold>{branch}</>")),
- hint_message(hint)
- )
+ write!(f, "{}\n{}", error_message(&title), hint_message(hint))
}
- GitError::ReferenceNotFound { reference } => {
- write!(
- f,
- "{}",
- error_message(cformat!(
- "No branch, tag, or commit named <bold>{reference}</>"
- ))
- )
+ GitError::ReferenceNotFound { .. } => {
+ let title = self.title();
+ write!(f, "{}", error_message(&title))
}
- GitError::StaleDefaultBranch { branch } => {
+ GitError::StaleDefaultBranch { .. } => {
+ let title = self.title();
write!(
f,
"{}\n{}",
- error_message(cformat!(
- "Default branch <bold>{branch}</> does not exist locally"
- )),
+ error_message(&title),
hint_message(cformat!(
"Reset the cached value with <underline>wt config state default-branch clear</>, or set it explicitly with <underline>wt config state default-branch set BRANCH</>"
))
)
}
- GitError::NotInWorktree { action } => {
- let message = match action {
- Some(action) => cformat!("Cannot {action}: not in a worktree"),
- None => "Not in a worktree".to_string(),
- };
+ GitError::NotInWorktree { .. } => {
+ let title = self.title();
write!(
f,
"{}\n{}",
- error_message(&message),
+ error_message(&title),
hint_message(cformat!(
"Run from inside a worktree, or specify a branch name"
))
)
}
- GitError::WorktreeMissing { branch } => {
+ GitError::WorktreeMissing { .. } => {
+ let title = self.title();
write!(
f,
"{}\n{}",
- error_message(cformat!("Worktree directory missing for <bold>{branch}</>")),
+ error_message(&title),
hint_message(cformat!(
"To clean up, run <underline>git worktree prune</>"
))
)
}
- GitError::RemoteOnlyBranch { branch, remote } => {
+ GitError::RemoteOnlyBranch { branch, .. } => {
+ let title = self.title();
let cmd = suggest_command("switch", &[branch], &[]);
- cwrite!(
+ write!(
f,
- "{ERROR_SYMBOL} <red>Branch <bold>{branch}</> exists only on remote ({remote}/{branch})</>\n{HINT_SYMBOL} <dim>To create a local worktree, run <underline>{cmd}</></>"
+ "{}\n{}",
+ error_message(&title),
+ hint_message(cformat!(
+ "To create a local worktree, run <underline>{cmd}</>"
+ ))
)
}
- GitError::WorktreePathOccupied {
- branch,
- path,
- occupant,
- } => {
+ GitError::WorktreePathOccupied { branch, path, .. } => {
+ let title = self.title();
let path_display = format_path_for_display(path);
- let reason = if let Some(occupant_branch) = occupant {
- cformat!(
- "there's a worktree at the expected path <bold>{path_display}</> on branch <bold>{occupant_branch}</>"
- )
- } else {
- cformat!(
- "there's a detached worktree at the expected path <bold>{path_display}</>"
- )
- };
let escaped_path = escape(path.to_string_lossy());
let escaped_branch = escape(Cow::Borrowed(branch.as_str()));
let command = format!("cd {escaped_path} && git switch {escaped_branch}");
write!(
f,
"{}\n{}",
- error_message(cformat!("Cannot switch to <bold>{branch}</> — {reason}")),
+ error_message(&title),
hint_message(cformat!(
"To switch the worktree at <underline>{path_display}</> to <underline>{branch}</>, run <underline>{command}</>"
))
@@ -655,6 +931,7 @@ impl GitError {
path,
create,
} => {
+ let title = self.title();
let path_display = format_path_for_display(path);
let flags: &[&str] = if *create {
&["--create", "--clobber"]
@@ -668,29 +945,16 @@ impl GitError {
write!(
f,
"{}\n{}",
- error_message(cformat!(
- "Directory already exists: <bold>{path_display}</>"
- )),
+ error_message(&title),
hint_message(cformat!(
"To remove manually, run <underline>rm -rf {path_display}</>; to overwrite (with backup), run <underline>{switch_cmd}</>"
))
)
}
- GitError::WorktreeCreationFailed {
- branch,
- base_branch,
- error,
- command,
- } => {
- let header = if let Some(base) = base_branch {
- error_message(cformat!(
- "Failed to create worktree for <bold>{branch}</> from base <bold>{base}</>"
- ))
- } else {
- error_message(cformat!("Failed to create worktree for <bold>{branch}</>"))
- };
- write!(f, "{}", format_error_block(header, error))?;
+ GitError::WorktreeCreationFailed { error, command, .. } => {
+ let title = self.title();
+ write!(f, "{}", format_error_block(error_message(&title), error))?;
if let Some(cmd) = command {
write!(
f,
@@ -703,16 +967,12 @@ impl GitError {
}
GitError::WorktreeRemovalFailed {
- branch,
- path,
error,
remaining_entries,
+ ..
} => {
- let path_display = format_path_for_display(path);
- let header = error_message(cformat!(
- "Failed to remove worktree for <bold>{branch}</> @ <bold>{path_display}</>"
- ));
- write!(f, "{}", format_error_block(header, error))?;
+ let title = self.title();
+ write!(f, "{}", format_error_block(error_message(&title), error))?;
if let Some(entries) = remaining_entries {
const MAX_SHOWN: usize = 10;
let listing = if entries.len() > MAX_SHOWN {
@@ -741,45 +1001,28 @@ impl GitError {
}
GitError::CannotRemoveMainWorktree => {
- write!(
- f,
- "{}",
- error_message("The main worktree cannot be removed")
- )
+ let title = self.title();
+ write!(f, "{}", error_message(&title))
}
GitError::CannotRemoveDefaultBranch { branch } => {
+ let title = self.title();
let cmd = suggest_command("remove", &[branch], &["-D"]);
write!(
f,
- "{}",
- error_message(cformat!(
- "Cannot remove the default branch <bold>{branch}</>"
- ))
- )?;
- write!(
- f,
- "\n{}",
+ "{}\n{}",
+ error_message(&title),
hint_message(cformat!("To force-delete, run <underline>{cmd}</>"))
)
}
- GitError::WorktreeLocked {
- branch,
- path,
- reason,
- } => {
- let reason_text = match reason {
- Some(r) if !r.is_empty() => format!(" ({r})"),
- _ => String::new(),
- };
+ GitError::WorktreeLocked { path, .. } => {
+ let title = self.title();
let path_display = format_path_for_display(path);
write!(
f,
"{}\n{}",
- error_message(cformat!(
- "Cannot remove <bold>{branch}</>, worktree is locked{reason_text}"
- )),
+ error_message(&title),
hint_message(cformat!(
"To unlock, run <underline>git worktree unlock {path_display}</>"
))
@@ -787,17 +1030,12 @@ impl GitError {
}
GitError::ConflictingChanges {
- target_branch,
files,
worktree_path,
+ ..
} => {
- write!(
- f,
- "{}",
- error_message(cformat!(
- "Can't push to local <bold>{target_branch}</> branch: conflicting uncommitted changes"
- ))
- )?;
+ let title = self.title();
+ write!(f, "{}", error_message(&title))?;
if !files.is_empty() {
let joined_files = files.join("\n");
write!(f, "\n{}", format_with_gutter(&joined_files, None))?;
@@ -817,13 +1055,8 @@ impl GitError {
commits_formatted,
in_merge_context,
} => {
- write!(
- f,
- "{}",
- error_message(cformat!(
- "Can't push to local <bold>{target_branch}</> branch: it has newer commits"
- ))
- )?;
+ let title = self.title();
+ write!(f, "{}", error_message(&title))?;
if !commits_formatted.is_empty() {
write!(f, "\n{}", format_with_gutter(commits_formatted, None))?;
}
@@ -849,15 +1082,9 @@ impl GitError {
}
}
- GitError::RebaseConflict {
- target_branch,
- git_output,
- } => {
- write!(
- f,
- "{}",
- error_message(cformat!("Rebase onto <bold>{target_branch}</> incomplete"))
- )?;
+ GitError::RebaseConflict { git_output, .. } => {
+ let title = self.title();
+ write!(f, "{}", error_message(&title))?;
if !git_output.is_empty() {
write!(f, "\n{}", format_with_gutter(git_output, None))
} else {
@@ -873,62 +1100,39 @@ impl GitError {
}
GitError::NotRebased { target_branch } => {
+ let title = self.title();
let rebase_cmd = suggest_command("step", &["rebase", target_branch], &[]);
write!(
f,
"{}\n{}",
- error_message(cformat!("Branch not rebased onto <bold>{target_branch}</>")),
+ error_message(&title),
hint_message(cformat!(
"To rebase first, run <underline>{rebase_cmd}</>; or remove <underline>--no-rebase</>"
))
)
}
- GitError::PushFailed {
- target_branch,
- error,
- } => {
- let header = error_message(cformat!(
- "Can't push to local <bold>{target_branch}</> branch"
- ));
- write!(f, "{}", format_error_block(header, error))
+ GitError::PushFailed { error, .. } => {
+ let title = self.title();
+ write!(f, "{}", format_error_block(error_message(&title), error))
}
GitError::NotInteractive => {
+ let title = self.title();
let approvals_cmd = suggest_command("config", &["approvals", "add"], &[]);
write!(
f,
"{}\n{}",
- error_message("Cannot prompt for approval in non-interactive environment"),
+ error_message(&title),
hint_message(cformat!(
"To skip prompts in CI/CD, add <underline>--yes</>; to pre-approve commands, run <underline>{approvals_cmd}</>"
))
)
}
- GitError::HookCommandNotFound { name, available } => {
- if available.is_empty() {
- write!(
- f,
- "{}",
- error_message(cformat!(
- "No command named <bold>{name}</> (hook has no named commands)"
- ))
- )
- } else {
- let available_str = available
- .iter()
- .map(|s| cformat!("<bold>{s}</>"))
- .collect::<Vec<_>>()
- .join(", ");
- write!(
- f,
- "{}",
- error_message(cformat!(
- "No command named <bold>{name}</> (available: {available_str})"
- ))
- )
- }
+ GitError::HookCommandNotFound { .. } => {
+ let title = self.title();
+ write!(f, "{}", error_message(&title))
}
GitError::LlmCommandFailed {
@@ -936,8 +1140,8 @@ impl GitError {
error,
reproduction_command,
} => {
- let error_header = error_message("Commit generation command failed");
- let error_block = format_error_block(error_header, error);
+ let title = self.title();
+ let error_block = format_error_block(error_message(&title), error);
// Show full pipeline command if available, otherwise just the LLM command
let display_command = reproduction_command.as_ref().unwrap_or(command);
let command_gutter = format_with_gutter(display_command, None);
@@ -951,32 +1155,35 @@ impl GitError {
}
GitError::ProjectConfigNotFound { config_path } => {
+ let title = self.title();
let path_display = format_path_for_display(config_path);
write!(
f,
"{}\n{}",
- error_message("No project configuration found"),
+ error_message(&title),
hint_message(cformat!(
"Create a config file at: <underline>{path_display}</>"
))
)
}
- GitError::ParseError { message } => {
- write!(f, "{}", error_message(message))
+ GitError::ParseError { .. } => {
+ let title = self.title();
+ write!(f, "{}", error_message(&title))
}
GitError::WorktreeIncludeParseError { error } => {
- let header = error_message(cformat!("Error parsing <bold>.worktreeinclude</>"));
- write!(f, "{}", format_error_block(header, error))
+ let title = self.title();
+ write!(f, "{}", format_error_block(error_message(&title), error))
}
GitError::WorktreeNotFound { branch } => {
+ let title = self.title();
let switch_cmd = suggest_command("switch", &[branch], &[]);
write!(
f,
"{}\n{}",
- error_message(cformat!("Branch <bold>{branch}</> has no worktree")),
+ error_message(&title),
hint_message(cformat!(
"To create a worktree, run <underline>{switch_cmd}</>"
))
@@ -1070,9 +1277,22 @@ impl GitError {
}
}
+impl Diagnostic for GitError {
+ fn render(&self) -> String {
+ let mut out = String::new();
+ self.write_render_with_ctx(&mut out, None)
+ .expect("writing to a String never fails");
+ out
+ }
+}
+
impl std::fmt::Display for GitError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- self.fmt_with_ctx(f, None)
+ // The styled title carries inline `<bold>` highlights for terminal
+ // rendering. For embedding in another error's message field or
+ // any non-terminal sink (JSON, log files, snapshots), strip the
+ // ANSI codes so consumers see plain text.
+ f.write_str(&ansi_str::AnsiStr::ansi_strip(&self.title()))
}
}
@@ -1108,9 +1328,41 @@ pub enum WorktrunkError {
impl std::fmt::Display for WorktrunkError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ WorktrunkError::ChildProcessExited { message, .. } => f.write_str(message),
+ WorktrunkError::HookCommandFailed {
+ hook_type,
+ command_name,
+ error,
+ ..
+ } => match command_name {
+ Some(name) => write!(f, "{hook_type} command failed: {name}: {error}"),
+ None => write!(f, "{hook_type} command failed: {error}"),
+ },
+ // on_skip callback handles the printing for CommandNotApproved;
+ // AlreadyDisplayed has already shown its error via output functions.
+ WorktrunkError::CommandNotApproved | WorktrunkError::AlreadyDisplayed { .. } => Ok(()),
+ }
+ }
+}
+
+impl WorktrunkError {
+ /// Exit code carried by this variant, if any.
+ pub fn exit_code(&self) -> Option<i32> {
+ match self {
+ WorktrunkError::ChildProcessExited { code, .. } => Some(*code),
+ WorktrunkError::HookCommandFailed { exit_code, .. } => *exit_code,
+ WorktrunkError::AlreadyDisplayed { exit_code } => Some(*exit_code),
+ WorktrunkError::CommandNotApproved => None,
+ }
+ }
+}
+
+impl Diagnostic for WorktrunkError {
+ fn render(&self) -> String {
match self {
WorktrunkError::ChildProcessExited { message, .. } => {
- write!(f, "{}", error_message(message))
+ error_message(message).to_string()
}
WorktrunkError::HookCommandFailed {
hook_type,
@@ -1118,28 +1370,18 @@ impl std::fmt::Display for WorktrunkError {
error,
..
} => {
- // Note: Callers that support --no-hooks should add the hint themselves
if let Some(name) = command_name {
- write!(
- f,
- "{}",
- error_message(cformat!(
- "{hook_type} command failed: <bold>{name}</>: {error}"
- ))
- )
+ error_message(cformat!(
+ "{hook_type} command failed: <bold>{name}</>: {error}"
+ ))
+ .to_string()
} else {
- write!(
- f,
- "{}",
- error_message(format!("{hook_type} command failed: {error}"))
- )
+ error_message(format!("{hook_type} command failed: {error}")).to_string()
}
}
- WorktrunkError::CommandNotApproved => {
- Ok(()) // on_skip callback handles the printing
- }
- WorktrunkError::AlreadyDisplayed { .. } => {
- Ok(()) // error already shown via output functions
+ // Silent — caller already handled display; render is empty.
+ WorktrunkError::CommandNotApproved | WorktrunkError::AlreadyDisplayed { .. } => {
+ String::new()
}
}
}
@@ -1147,90 +1389,108 @@ impl std::fmt::Display for WorktrunkError {
impl std::error::Error for WorktrunkError {}
-/// Extract exit code from WorktrunkError, if applicable
-pub fn exit_code(err: &anyhow::Error) -> Option<i32> {
- // Check for wrapped HookErrorWithHint first
- if let Some(wrapper) = err.downcast_ref::<HookErrorWithHint>() {
- return exit_code(&wrapper.inner);
- }
- err.downcast_ref::<WorktrunkError>().and_then(|e| match e {
- WorktrunkError::ChildProcessExited { code, .. } => Some(*code),
- WorktrunkError::HookCommandFailed { exit_code, .. } => *exit_code,
- WorktrunkError::CommandNotApproved => None,
- WorktrunkError::AlreadyDisplayed { exit_code } => Some(*exit_code),
- })
-}
+impl ErrorExt for anyhow::Error {
+ fn render_diagnostic(&self) -> Option<String> {
+ self.chain().find_map(try_render_diagnostic)
+ }
-/// If `err` is a signal-derived child exit, return the equivalent shell exit
-/// code (`128 + signal`).
-///
-/// Implements the Ctrl-C cancellation policy: command loops call this on every
-/// per-iteration failure and, when it returns `Some`, abort the loop rather
-/// than continuing to the next iteration. The returned code is what wt itself
-/// should exit with, preserving the standard `128 + sig` shell convention
-/// (130 for SIGINT, 143 for SIGTERM).
-///
-/// See the "Signal Handling" section of the project `CLAUDE.md` for the
-/// rationale and the full list of loops that apply this policy.
-pub fn interrupt_exit_code(err: &anyhow::Error) -> Option<i32> {
- if let Some(WorktrunkError::ChildProcessExited {
- signal: Some(sig), ..
- }) = err.downcast_ref::<WorktrunkError>()
- {
- Some(128 + sig)
- } else {
- None
+ fn display_message(&self) -> String {
+ // For chains carrying a `CommandError`, prefer git's captured
+ // stderr/stdout. Fall back to the command summary when the
+ // capture is empty (e.g., signal-killed before output) so a
+ // higher-level error like `PushFailed { error: … }` doesn't end
+ // up with a blank detail.
+ if let Some(cmd_err) = CommandError::find_in(self) {
+ let body = cmd_err.combined_output();
+ return if body.is_empty() {
+ cmd_err.to_string()
+ } else {
+ body
+ };
+ }
+ self.to_string()
+ }
+
+ fn exit_code(&self) -> Option<i32> {
+ // Walks past `HookErrorWithHint` (whose `Error::source` exposes
+ // the inner `WorktrunkError`) without a special case here.
+ self.chain()
+ .find_map(|e| e.downcast_ref::<WorktrunkError>())
+ .and_then(WorktrunkError::exit_code)
+ }
+
+ fn interrupt_exit_code(&self) -> Option<i32> {
+ if let Some(WorktrunkError::ChildProcessExited {
+ signal: Some(sig), ..
+ }) = self.downcast_ref::<WorktrunkError>()
+ {
+ Some(128 + sig)
+ } else {
+ None
+ }
}
}
-/// If the error is a HookCommandFailed, wrap it to add a hint about using --no-hooks.
+/// If the error wraps a [`WorktrunkError::HookCommandFailed`], wrap it
+/// with [`HookErrorWithHint`] to surface a `--no-hooks` hint when
+/// rendered. Pass-through for any other error.
+///
+/// Domain behavior, not a general property of an error — kept as a free
+/// function so it stays out of [`ErrorExt`].
///
/// ## When to use
///
-/// Use this for commands where a hook runs as a side effect of the user's intent:
-/// - `wt merge` - user wants to merge, hooks run as part of that
-/// - `wt commit` - user wants to commit, pre-commit hooks run
-/// - `wt switch --create` - user wants a worktree, post-create hooks run
+/// Use this for commands where a hook runs as a side effect of the
+/// user's intent:
+/// - `wt merge` — user wants to merge, hooks run as part of that
+/// - `wt commit` — user wants to commit, pre-commit hooks run
+/// - `wt switch --create` — user wants a worktree, post-create hooks run
///
/// ## When NOT to use
///
-/// Don't use for `wt hook <type>` - the user explicitly asked to run hooks,
-/// so suggesting `--no-hooks` makes no sense.
+/// Don't use for `wt hook <type>` — the user explicitly asked to run
+/// hooks, so suggesting `--no-hooks` makes no sense.
pub fn add_hook_skip_hint(err: anyhow::Error) -> anyhow::Error {
- // Extract hook_type first (if applicable), then decide whether to wrap
- let hook_type = err
- .downcast_ref::<WorktrunkError>()
- .and_then(|wt_err| match wt_err {
- WorktrunkError::HookCommandFailed { hook_type, .. } => Some(*hook_type),
- _ => None,
- });
-
- match hook_type {
- Some(hook_type) => HookErrorWithHint {
- inner: err,
- hook_type,
- }
- .into(),
- None => err,
- }
+ let inner = match err.downcast::<WorktrunkError>() {
+ Ok(inner) => inner,
+ Err(err) => return err,
+ };
+ let hook_type = match &inner {
+ WorktrunkError::HookCommandFailed { hook_type, .. } => *hook_type,
+ // Not a hook failure — pass the typed leaf through unchanged.
+ _ => return inner.into(),
+ };
+ HookErrorWithHint { inner, hook_type }.into()
}
-/// Wrapper that displays a HookCommandFailed error with the --no-hooks hint.
-/// Created by `add_hook_skip_hint()` for commands that support `--no-hooks`.
+/// Wrapper that displays a [`WorktrunkError::HookCommandFailed`] with a
+/// `--no-hooks` hint. Created by [`add_hook_skip_hint`] for commands that
+/// support `--no-hooks`.
+///
+/// The typed inner field captures the invariant that this only ever wraps
+/// a hook failure — no runtime downcast or fallback in `render`.
#[derive(Debug)]
pub struct HookErrorWithHint {
- inner: anyhow::Error,
+ inner: WorktrunkError,
hook_type: HookType,
}
impl std::fmt::Display for HookErrorWithHint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- // Display the original error (always HookCommandFailed - validated by add_hook_skip_hint)
- write!(f, "{}", self.inner)?;
- // Can't derive command from hook type (e.g., PreRemove is used by both `wt remove` and `wt merge`)
- write!(
- f,
- "\n{}",
+ write!(f, "{}", self.inner)
+ }
+}
+
+impl Diagnostic for HookErrorWithHint {
+ fn render(&self) -> String {
+ // The wrapper is only constructed for `HookCommandFailed`, whose
+ // render always emits an `error_message(…)` line — never empty.
+ // No empty-body fallback needed.
+ // Can't derive command from hook type (e.g., PreRemove is used
+ // by both `wt remove` and `wt merge`), so the hint stays generic.
+ format!(
+ "{}\n{}",
+ self.inner.render(),
hint_message(cformat!(
"To skip {} hooks, re-run with <underline>--no-hooks</>",
self.hook_type
@@ -1241,7 +1501,10 @@ impl std::fmt::Display for HookErrorWithHint {
impl std::error::Error for HookErrorWithHint {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
- self.inner.source()
+ // Expose the typed leaf so chain walks (e.g., `ErrorExt::exit_code`)
+ // can find the underlying `WorktrunkError` without knowing about
+ // this wrapper.
+ Some(&self.inner)
}
}
@@ -1301,6 +1564,27 @@ mod tests {
use anyhow::Context;
use insta::assert_snapshot;
+ /// Render the first `Diagnostic`-implementing error in `err`'s chain,
+ /// or fall back to the top-level `Display`. Mirrors what
+ /// `format_command_error` in `main.rs` does for the chain-walk case.
+ fn render_anyhow(err: &anyhow::Error) -> String {
+ for cause in err.chain() {
+ if let Some(e) = cause.downcast_ref::<GitError>() {
+ return e.render();
+ }
+ if let Some(e) = cause.downcast_ref::<HookErrorWithHint>() {
+ return e.render();
+ }
+ if let Some(e) = cause.downcast_ref::<WorktrunkError>() {
+ return e.render();
+ }
+ if let Some(e) = cause.downcast_ref::<CommandError>() {
+ return e.render();
+ }
+ }
+ err.to_string()
+ }
+
#[test]
fn snapshot_into_preserves_type_for_display() {
// .into() preserves type so we can downcast and use Display
@@ -1310,7 +1594,10 @@ mod tests {
.into();
let downcast = err.downcast_ref::<GitError>().expect("Should downcast");
- assert_snapshot!(downcast.to_string(), @"
+ // Display is the short single-line label
+ assert_snapshot!(downcast.to_string(), @"Branch main already exists");
+ // Diagnostic::render produces the full styled block
+ assert_snapshot!(downcast.render(), @"
✗ Branch main already exists
↳ To switch to the existing branch, run without --create: wt switch main
");
@@ -1337,7 +1624,7 @@ mod tests {
path: PathBuf::from("/some/path"),
create: true,
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Directory already exists: /some/path
↳ To remove manually, run rm -rf /some/path; to overwrite (with backup), run wt switch --create --clobber feature
");
@@ -1352,7 +1639,7 @@ mod tests {
signal: None,
}
.into();
- assert_eq!(exit_code(&err), Some(42));
+ assert_eq!(err.exit_code(), Some(42));
// HookCommandFailed with code
let err: anyhow::Error = WorktrunkError::HookCommandFailed {
@@ -1362,7 +1649,7 @@ mod tests {
exit_code: Some(1),
}
.into();
- assert_eq!(exit_code(&err), Some(1));
+ assert_eq!(err.exit_code(), Some(1));
// HookCommandFailed without code
let err: anyhow::Error = WorktrunkError::HookCommandFailed {
@@ -1372,16 +1659,19 @@ mod tests {
exit_code: None,
}
.into();
- assert_eq!(exit_code(&err), None);
+ assert_eq!(err.exit_code(), None);
// CommandNotApproved, AlreadyDisplayed, GitError
- assert_eq!(exit_code(&WorktrunkError::CommandNotApproved.into()), None);
assert_eq!(
- exit_code(&WorktrunkError::AlreadyDisplayed { exit_code: 5 }.into()),
+ anyhow::Error::from(WorktrunkError::CommandNotApproved).exit_code(),
+ None
+ );
+ assert_eq!(
+ anyhow::Error::from(WorktrunkError::AlreadyDisplayed { exit_code: 5 }).exit_code(),
Some(5)
);
assert_eq!(
- exit_code(&GitError::DetachedHead { action: None }.into()),
+ anyhow::Error::from(GitError::DetachedHead { action: None }).exit_code(),
None
);
@@ -1393,7 +1683,7 @@ mod tests {
exit_code: Some(7),
}
.into();
- assert_eq!(exit_code(&add_hook_skip_hint(inner)), Some(7));
+ assert_eq!(add_hook_skip_hint(inner).exit_code(), Some(7));
}
#[test]
@@ -1405,7 +1695,7 @@ mod tests {
signal: Some(2),
}
.into();
- assert_eq!(interrupt_exit_code(&err), Some(130));
+ assert_eq!(err.interrupt_exit_code(), Some(130));
let err: anyhow::Error = WorktrunkError::ChildProcessExited {
code: 143,
@@ -1413,7 +1703,7 @@ mod tests {
signal: Some(15),
}
.into();
- assert_eq!(interrupt_exit_code(&err), Some(143));
+ assert_eq!(err.interrupt_exit_code(), Some(143));
// Ordinary non-zero exit → not an interrupt
let err: anyhow::Error = WorktrunkError::ChildProcessExited {
@@ -1422,21 +1712,22 @@ mod tests {
signal: None,
}
.into();
- assert_eq!(interrupt_exit_code(&err), None);
+ assert_eq!(err.interrupt_exit_code(), None);
// Other WorktrunkError variants → not an interrupt
assert_eq!(
- interrupt_exit_code(&WorktrunkError::AlreadyDisplayed { exit_code: 130 }.into()),
+ anyhow::Error::from(WorktrunkError::AlreadyDisplayed { exit_code: 130 })
+ .interrupt_exit_code(),
None,
);
assert_eq!(
- interrupt_exit_code(&WorktrunkError::CommandNotApproved.into()),
+ anyhow::Error::from(WorktrunkError::CommandNotApproved).interrupt_exit_code(),
None,
);
// Plain anyhow error → not an interrupt
assert_eq!(
- interrupt_exit_code(&anyhow::anyhow!("some unrelated failure")),
+ anyhow::anyhow!("some unrelated failure").interrupt_exit_code(),
None,
);
}
@@ -1451,7 +1742,7 @@ mod tests {
exit_code: Some(1),
}
.into();
- assert_snapshot!(add_hook_skip_hint(inner).to_string(), @"
+ assert_snapshot!(render_anyhow(&add_hook_skip_hint(inner)), @"
✗ pre-merge command failed: test: failed
↳ To skip pre-merge hooks, re-run with --no-hooks
");
@@ -1464,7 +1755,7 @@ mod tests {
exit_code: Some(1),
}
.into();
- assert_snapshot!(add_hook_skip_hint(inner).to_string(), @"
+ assert_snapshot!(render_anyhow(&add_hook_skip_hint(inner)), @"
✗ pre-commit command failed: build: Build failed
↳ To skip pre-commit hooks, re-run with --no-hooks
");
@@ -1476,16 +1767,90 @@ mod tests {
signal: None,
}
.into();
- assert!(!add_hook_skip_hint(err).to_string().contains("--no-hooks"));
+ assert!(!render_anyhow(&add_hook_skip_hint(err)).contains("--no-hooks"));
let err: anyhow::Error = GitError::DetachedHead { action: None }.into();
- assert!(!add_hook_skip_hint(err).to_string().contains("--no-hooks"));
+ assert!(!render_anyhow(&add_hook_skip_hint(err)).contains("--no-hooks"));
let err: anyhow::Error = GitError::Other {
message: "some error".into(),
}
.into();
- assert!(!add_hook_skip_hint(err).to_string().contains("--no-hooks"));
+ assert!(!render_anyhow(&add_hook_skip_hint(err)).contains("--no-hooks"));
+ }
+
+ /// `Display` is the short single-line label per variant — no symbol,
+ /// no color codes, no hint. It's what callers embed in another error's
+ /// message field (e.g., `format!("…: {e}")`).
+ #[test]
+ fn snapshot_short_display_per_variant() {
+ // GitError variants
+ assert_snapshot!(
+ GitError::BranchAlreadyExists { branch: "feature".into() }.to_string(),
+ @"Branch feature already exists"
+ );
+ assert_snapshot!(
+ GitError::WorktreeRemovalFailed {
+ branch: "feature".into(),
+ path: PathBuf::from("/tmp/repo.feature"),
+ error: "fatal: …".into(),
+ remaining_entries: None,
+ }.to_string(),
+ @"Failed to remove worktree for feature @ /tmp/repo.feature"
+ );
+ assert_snapshot!(
+ GitError::RebaseConflict {
+ target_branch: "main".into(),
+ git_output: "CONFLICT (content): …".into(),
+ }.to_string(),
+ @"Rebase onto main incomplete"
+ );
+ assert_snapshot!(
+ GitError::DetachedHead { action: Some("merge".into()) }.to_string(),
+ @"Cannot merge: not on a branch (detached HEAD)"
+ );
+ assert_snapshot!(
+ GitError::DetachedHead { action: None }.to_string(),
+ @"Not on a branch (detached HEAD)"
+ );
+
+ // WithSwitchSuggestion delegates to inner — ctx only affects render
+ let inner = GitError::BranchAlreadyExists {
+ branch: "feature".into(),
+ };
+ let wrapped = GitError::WithSwitchSuggestion {
+ source: Box::new(inner.clone()),
+ ctx: SwitchSuggestionCtx {
+ extra_flags: vec!["--execute=claude".into()],
+ trailing_args: vec![],
+ },
+ };
+ assert_eq!(inner.to_string(), wrapped.to_string());
+
+ // WorktrunkError variants
+ assert_snapshot!(
+ WorktrunkError::HookCommandFailed {
+ hook_type: HookType::PreMerge,
+ command_name: Some("lint".into()),
+ error: "lint failed".into(),
+ exit_code: Some(1),
+ }.to_string(),
+ @"pre-merge command failed: lint: lint failed"
+ );
+ assert_snapshot!(
+ WorktrunkError::ChildProcessExited {
+ code: 1,
+ message: "exit status: 1".into(),
+ signal: None,
+ }.to_string(),
+ @"exit status: 1"
+ );
+ // Silent variants
+ assert_eq!(WorktrunkError::CommandNotApproved.to_string(), "");
+ assert_eq!(
+ WorktrunkError::AlreadyDisplayed { exit_code: 1 }.to_string(),
+ ""
+ );
}
#[test]
@@ -1508,7 +1873,7 @@ mod tests {
message: "Command failed".into(),
signal: None,
};
- assert_snapshot!(err.to_string(), @"✗ Command failed");
+ assert_snapshot!(err.render(), @"✗ Command failed");
let err = WorktrunkError::HookCommandFailed {
hook_type: HookType::PreMerge,
@@ -1516,7 +1881,7 @@ mod tests {
error: "lint failed".into(),
exit_code: Some(1),
};
- assert_snapshot!(err.to_string(), @"✗ pre-merge command failed: lint: lint failed");
+ assert_snapshot!(err.render(), @"✗ pre-merge command failed: lint: lint failed");
let err = WorktrunkError::HookCommandFailed {
hook_type: HookType::PreStart,
@@ -1524,7 +1889,7 @@ mod tests {
error: "setup failed".into(),
exit_code: None,
};
- assert_snapshot!(err.to_string(), @"✗ pre-start command failed: setup failed");
+ assert_snapshot!(err.render(), @"✗ pre-start command failed: setup failed");
// Silent errors produce empty output
assert_eq!(format!("{}", WorktrunkError::CommandNotApproved), "");
@@ -1539,13 +1904,13 @@ mod tests {
let err = GitError::NotInWorktree {
action: Some("resolve @".into()),
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Cannot resolve @: not in a worktree
↳ Run from inside a worktree, or specify a branch name
");
let err = GitError::NotInWorktree { action: None };
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Not in a worktree
↳ Run from inside a worktree, or specify a branch name
");
@@ -1558,7 +1923,7 @@ mod tests {
path: PathBuf::from("/tmp/repo"),
occupant: Some("main".into()),
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Cannot switch to feature — there's a worktree at the expected path /tmp/repo on branch main
↳ To switch the worktree at /tmp/repo to feature, run cd /tmp/repo && git switch feature
");
@@ -1568,7 +1933,7 @@ mod tests {
path: PathBuf::from("/tmp/repo"),
occupant: None,
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Cannot switch to feature — there's a detached worktree at the expected path /tmp/repo
↳ To switch the worktree at /tmp/repo to feature, run cd /tmp/repo && git switch feature
");
@@ -1582,7 +1947,7 @@ mod tests {
path: PathBuf::from("/tmp/my repo"),
occupant: Some("main".into()),
};
- let output = err.to_string();
+ let output = err.render();
// The hint command must quote the path and branch for safe shell execution
assert!(
output.contains("cd '/tmp/my repo' && git switch 'feature/my branch'"),
@@ -1598,7 +1963,7 @@ mod tests {
error: "git error".into(),
command: None,
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Failed to create worktree for feature from base main
  git error
");
@@ -1609,7 +1974,7 @@ mod tests {
error: "git error".into(),
command: None,
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Failed to create worktree for feature
  git error
");
@@ -1623,7 +1988,7 @@ mod tests {
exit_info: "exit code 128".into(),
}),
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Failed to create worktree for feature from base main
  fatal: ref exists
↳ Failed command, exit code 128:
@@ -1638,7 +2003,7 @@ mod tests {
path: PathBuf::from("/tmp/repo.feature"),
reason: Some("Testing lock".into()),
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Cannot remove feature, worktree is locked (Testing lock)
↳ To unlock, run git worktree unlock /tmp/repo.feature
");
@@ -1649,7 +2014,7 @@ mod tests {
path: PathBuf::from("/tmp/repo.feature"),
reason: Some("".into()),
};
- let display = err.to_string();
+ let display = err.render();
assert_snapshot!(display, @"
✗ Cannot remove feature, worktree is locked
↳ To unlock, run git worktree unlock /tmp/repo.feature
@@ -1665,7 +2030,7 @@ mod tests {
let err = GitError::NotRebased {
target_branch: "main".into(),
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Branch not rebased onto main
↳ To rebase first, run wt step rebase main; or remove --no-rebase
");
@@ -1677,13 +2042,13 @@ mod tests {
name: "unknown".into(),
available: vec!["lint".into(), "test".into()],
};
- assert_snapshot!(err.to_string(), @"✗ No command named unknown (available: lint, test)");
+ assert_snapshot!(err.render(), @"✗ No command named unknown (available: lint, test)");
let err = GitError::HookCommandNotFound {
name: "unknown".into(),
available: vec![],
};
- assert_snapshot!(err.to_string(), @"✗ No command named unknown (hook has no named commands)");
+ assert_snapshot!(err.render(), @"✗ No command named unknown (hook has no named commands)");
}
#[test]
@@ -1693,7 +2058,7 @@ mod tests {
error: "connection failed".into(),
reproduction_command: Some("wt step commit --show-prompt | llm".into()),
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Commit generation command failed
  connection failed
○ Ran command:
@@ -1705,7 +2070,7 @@ mod tests {
error: "timeout".into(),
reproduction_command: None,
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Commit generation command failed
  timeout
○ Ran command:
@@ -1721,7 +2086,7 @@ mod tests {
branch: None,
force_hint: false,
};
- let display = err.to_string();
+ let display = err.render();
assert_snapshot!(display, @"
✗ Cannot push: working tree has uncommitted changes
↳ Commit or stash changes first
@@ -1734,7 +2099,7 @@ mod tests {
branch: Some("feature".into()),
force_hint: false,
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ feature has uncommitted changes
↳ Commit or stash changes first
");
@@ -1745,7 +2110,7 @@ mod tests {
branch: None,
force_hint: false,
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Working tree has uncommitted changes
↳ Commit or stash changes first
");
@@ -1756,7 +2121,7 @@ mod tests {
branch: Some("feature".into()),
force_hint: true,
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Cannot remove worktree: feature has uncommitted changes
↳ Commit or stash changes first, or to lose uncommitted changes, run wt remove --force feature
");
@@ -1770,7 +2135,7 @@ mod tests {
commits_formatted: "".into(),
in_merge_context: false,
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Can't push to local main branch: it has newer commits
↳ To rebase onto main, run wt step rebase main
");
@@ -1781,7 +2146,7 @@ mod tests {
commits_formatted: "abc123 Some commit".into(),
in_merge_context: false,
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Can't push to local develop branch: it has newer commits
  abc123 Some commit
↳ To rebase onto develop, run wt step rebase develop
@@ -1793,7 +2158,7 @@ mod tests {
commits_formatted: "def456 Another commit".into(),
in_merge_context: true,
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Can't push to local main branch: it has newer commits
  def456 Another commit
↳ To incorporate these changes, run wt merge main again
@@ -1807,7 +2172,7 @@ mod tests {
files: vec![],
worktree_path: PathBuf::from("/tmp/repo"),
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Can't push to local main branch: conflicting uncommitted changes
↳ Commit or stash these changes in /tmp/repo first
");
@@ -1820,7 +2185,7 @@ mod tests {
message: "gh api failed for PR #42".into(),
stderr: "error: unexpected response\ncode: 500".into(),
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ gh api failed for PR #42
  error: unexpected response
  code: 500
@@ -1834,7 +2199,7 @@ mod tests {
repo: "upstream-repo".into(),
suggested_url: "https://github.com/upstream-owner/upstream-repo.git".into(),
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ No remote found for upstream-owner/upstream-repo
↳ Add the remote: git remote add upstream https://github.com/upstream-owner/upstream-repo.git
");
@@ -1846,7 +2211,7 @@ mod tests {
target_branch: "main".into(),
git_output: "".into(),
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Rebase onto main incomplete
↳ To continue after resolving conflicts, run git rebase --continue
↳ To abort, run git rebase --abort
@@ -1864,7 +2229,7 @@ mod tests {
trailing_args: vec!["Check my emails".into()],
},
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Branch emails already exists
↳ To switch to the existing branch, run without --create: wt switch emails --execute=claude -- 'Check my emails'
");
@@ -1883,7 +2248,7 @@ mod tests {
trailing_args: vec!["Check my emails".into()],
},
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Directory already exists: /tmp/repo.emails
↳ To remove manually, run rm -rf /tmp/repo.emails; to overwrite (with backup), run wt switch --create --clobber emails --execute=claude -- 'Check my emails'
");
@@ -1900,7 +2265,7 @@ mod tests {
trailing_args: vec![],
},
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ Branch emails already exists
↳ To switch to the existing branch, run without --create: wt switch emails --execute=claude
");
@@ -1920,7 +2285,7 @@ mod tests {
trailing_args: vec!["Check my emails".into()],
},
};
- assert_snapshot!(err.to_string(), @"
+ assert_snapshot!(err.render(), @"
✗ No branch named emails
↳ To create a new branch, run wt switch --create emails --execute=claude -- 'Check my emails'; to list branches, run wt list --branches --remotes
");
@@ -2018,7 +2383,7 @@ mod tests {
}
#[test]
- fn find_command_error_walks_anyhow_chain() {
+ fn command_error_find_in_walks_anyhow_chain() {
// Wrapping with `.context(...)` must not hide the typed leaf — the
// helper should pull it out regardless of how many layers wrap.
let err: anyhow::Error = Err::<(), _>(sample_command_error())
@@ -2026,7 +2391,7 @@ mod tests {
.context("running prune")
.unwrap_err();
- let cmd_err = find_command_error(&err).expect("CommandError should be found in chain");
+ let cmd_err = CommandError::find_in(&err).expect("CommandError should be found in chain");
assert_eq!(cmd_err.program, "git");
assert_eq!(
cmd_err.args,
@@ -2036,8 +2401,8 @@ mod tests {
}
#[test]
- fn find_command_error_returns_none_for_unrelated_error() {
+ fn command_error_find_in_returns_none_for_unrelated_error() {
let err = anyhow::anyhow!("some other failure");
- assert!(find_command_error(&err).is_none());
+ assert!(CommandError::find_in(&err).is_none());
}
}
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 3111a5c82..8cc059af2 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -40,11 +40,18 @@ pub use diff::{LineDiff, parse_numstat_line};
pub use error::{
// Typed leaf error for buffered command-runner failures (downcast target)
CommandError,
+ // Trait for typed errors that produce a rich, styled diagnostic block
+ // distinct from their short single-line `Display`
+ Diagnostic,
+ // Extension methods on `anyhow::Error` (render_diagnostic,
+ // display_message, exit_code, interrupt_exit_code). Bring into scope
+ // to call them via method syntax.
+ ErrorExt,
// Structured command failure info
FailedCommand,
- // Typed error enum (Display produces styled output)
+ // Typed error enum
GitError,
- // Special-handling error enum (Display produces styled output)
+ // Special-handling error enum
HookErrorWithHint,
// Platform-specific reference type (PR vs MR)
RefContext,
@@ -52,14 +59,10 @@ pub use error::{
// CLI context for enriching switch suggestions in error hints
SwitchSuggestionCtx,
WorktrunkError,
- // Error inspection functions
+ // Wrap a HookCommandFailed-bearing error with a --no-hooks hint
add_hook_skip_hint,
- // User-facing detail string (prefers CommandError stderr)
- display_message,
- exit_code,
- // Walk an anyhow chain for the first CommandError
- find_command_error,
- interrupt_exit_code,
+ // Render a single error via Diagnostic if it implements one
+ try_render_diagnostic,
};
pub use parse::{parse_porcelain_z, parse_untracked_files};
pub use recover::{current_or_recover, cwd_removed_hint};
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index fd5b2bf5b..9af55f704 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -103,7 +103,7 @@ use dunce::canonicalize;
use crate::config::{LoadError, ProjectConfig, ResolvedConfig, UserConfig};
// Import types from parent module
-use super::{DefaultBranchName, GitError, LineDiff, WorktreeInfo};
+use super::{CommandError, DefaultBranchName, GitError, LineDiff, WorktreeInfo};
// Re-export types needed by submodules
pub(super) use super::{
@@ -1489,7 +1489,7 @@ impl Repository {
}),
);
}
- if let Some(cmd_err) = super::error::find_command_error(err) {
+ if let Some(cmd_err) = CommandError::find_in(err) {
let exit_info = match cmd_err.exit_code {
Some(code) => format!("exit code {code}"),
None => "killed by signal".to_string(),
diff --git a/src/llm.rs b/src/llm.rs
index d360f4ef9..3481d7900 100644
--- a/src/llm.rs
+++ b/src/llm.rs
@@ -1029,7 +1029,7 @@ mod tests {
};
let context = commit_context("diff", "main", None, "repo");
let result = build_prompt(&config, TemplateType::Commit, &context);
- assert_snapshot!(result.unwrap_err().to_string(), @"✗ Template is empty");
+ assert_snapshot!(result.unwrap_err().to_string(), @"Template is empty");
}
#[test]
@@ -1147,7 +1147,7 @@ mod tests {
let commits: Vec<String> = vec![];
let context = squash_context("diff", "feature", None, "repo", &commits, "main");
let result = build_prompt(&config, TemplateType::Squash, &context);
- assert_snapshot!(result.unwrap_err().to_string(), @"✗ Squash template is empty");
+ assert_snapshot!(result.unwrap_err().to_string(), @"Squash template is empty");
}
#[test]
diff --git a/src/main.rs b/src/main.rs
index a70319c0f..c99e92825 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -8,7 +8,7 @@ use color_print::{ceprintln, cformat};
use std::process;
use worktrunk::config::{UserConfig, set_config_path};
use worktrunk::git::{
- Repository, ResolvedWorktree, WorktrunkError, current_or_recover, cwd_removed_hint, exit_code,
+ ErrorExt, Repository, ResolvedWorktree, WorktrunkError, current_or_recover, cwd_removed_hint,
set_base_path,
};
use worktrunk::styling::{
@@ -719,7 +719,14 @@ impl RemovePlans {
}
fn record_error(&mut self, e: anyhow::Error) {
- eprintln!("{}", e);
+ // The remove command collects per-target errors and surfaces each
+ // individually (partial-success path). Render the typed
+ // diagnostic block when present so locked/dirty/etc. errors
+ // carry their hint, falling back to the short label otherwise.
+ let rendered = e.render_diagnostic().unwrap_or_else(|| e.to_string());
+ if !rendered.is_empty() {
+ eprintln!("{rendered}");
+ }
self.errors.push(e);
}
}
@@ -1320,96 +1327,96 @@ fn print_command_error(error: &anyhow::Error) {
fn format_command_error(error: &anyhow::Error) -> String {
use std::fmt::Write;
let mut out = String::new();
- // GitError, WorktrunkError, and HookErrorWithHint produce styled output via Display.
- // Some variants (AlreadyDisplayed, CommandNotApproved) have empty Display impls —
- // skip writes for those to avoid phantom blank lines.
- if let Some(err) = error.downcast_ref::<worktrunk::git::GitError>() {
- let _ = writeln!(out, "{err}");
- } else if let Some(err) = error.downcast_ref::<worktrunk::git::WorktrunkError>() {
- let display = err.to_string();
- if !display.is_empty() {
- let _ = writeln!(out, "{display}");
- }
- } else if let Some(err) = error.downcast_ref::<worktrunk::git::HookErrorWithHint>() {
- let _ = writeln!(out, "{err}");
- } else if let Some(err) = error.downcast_ref::<worktrunk::config::TemplateExpandError>() {
- let _ = writeln!(out, "{err}");
- } else if worktrunk::git::find_command_error(error).is_some() {
- // Captured stderr/stdout from a buffered command (Repository::run_command,
- // WorkingTree::run_command). The header is the top-level message
- // (the outermost `.context(...)` if any, else the CommandError's
- // single-line summary). The gutter shows intermediate context
- // entries followed by the captured output, so wrapped failures
- // like `.context("listing worktrees").context("running prune")`
- // keep their diagnostic context while still surfacing git's
- // actual stderr.
- let _ = writeln!(out, "{}", error_message(error.to_string()));
-
- let mut gutter_parts: Vec<String> = Vec::new();
- let mut command_handled = false;
- for cause in error.chain().skip(1) {
- if !command_handled
- && let Some(cmd_err) = cause.downcast_ref::<worktrunk::git::CommandError>()
- {
- let body = cmd_err.combined_output();
- gutter_parts.push(if body.is_empty() {
- cmd_err.to_string()
- } else {
- body
- });
- command_handled = true;
- } else {
- gutter_parts.push(cause.to_string());
+
+ // Locate the first error in the chain that implements `Diagnostic`.
+ // Most typed errors render directly even when wrapped in
+ // `.context(...)`: their styled block is self-contained and the
+ // wrapping context (if any) was added to enrich logs, not the
+ // user-facing message. The exception is `CommandError`: its captured
+ // stderr/stdout pairs naturally with the wrapping context to form a
+ // header + body block (e.g., header `"running prune"`, body git's
+ // actual error).
+ let diagnostic_hit = error.chain().enumerate().find_map(|(i, cause)| {
+ worktrunk::git::try_render_diagnostic(cause)
+ .map(|r| (i, r, cause.is::<worktrunk::git::CommandError>()))
+ });
+
+ let wrapped_command_error = matches!(diagnostic_hit, Some((pos, _, true)) if pos > 0);
+
+ match diagnostic_hit {
+ Some((_, rendered, _)) if !wrapped_command_error => {
+ // The type's `render()` produces a complete styled block —
+ // emit it directly. Empty rendering (AlreadyDisplayed,
+ // CommandNotApproved) is a signal to skip output entirely.
+ if !rendered.is_empty() {
+ let _ = writeln!(out, "{rendered}");
}
}
- if !command_handled {
- // Top-level error itself was the CommandError — header is its
- // single-line summary; put the captured body in the gutter.
- if let Some(cmd_err) = error.downcast_ref::<worktrunk::git::CommandError>() {
- let body = cmd_err.combined_output();
- if !body.is_empty() {
- gutter_parts.push(body);
+ Some(_) => {
+ // Wrapped `CommandError`: outermost context becomes the
+ // header, intermediate contexts plus the captured
+ // stderr/stdout join the gutter so wrapped failures like
+ // `.context("listing worktrees").context("running prune")`
+ // keep their diagnostic context while still surfacing git's
+ // actual stderr.
+ let _ = writeln!(out, "{}", error_message(error.to_string()));
+ let mut gutter_parts: Vec<String> = Vec::new();
+ let mut command_handled = false;
+ for cause in error.chain().skip(1) {
+ if !command_handled
+ && let Some(cmd_err) = cause.downcast_ref::<worktrunk::git::CommandError>()
+ {
+ let body = cmd_err.combined_output();
+ gutter_parts.push(if body.is_empty() {
+ cmd_err.to_string()
+ } else {
+ body
+ });
+ command_handled = true;
+ } else {
+ gutter_parts.push(cause.to_string());
}
}
- }
- if !gutter_parts.is_empty() {
- let _ = writeln!(
- out,
- "{}",
- format_with_gutter(&gutter_parts.join("\n"), None)
- );
- }
- } else {
- // Anyhow error formatting:
- // - With context: show context as header, root cause in gutter
- // - Simple error: inline with emoji
- // - Empty error: skip (errors already printed elsewhere)
- let msg = error.to_string();
- if !msg.is_empty() {
- let chain: Vec<String> = error.chain().skip(1).map(|e| e.to_string()).collect();
- if !chain.is_empty() {
- let _ = writeln!(out, "{}", error_message(&msg));
- let chain_text = chain.join("\n");
- let _ = writeln!(out, "{}", format_with_gutter(&chain_text, None));
- } else if msg.contains('\n') || msg.contains('\r') {
- // A multi-line error reached this branch without being wrapped
- // in a typed `CommandError` and without `.context(...)` on top.
- // Buffered command failures should always surface as
- // `CommandError`; if you hit this assert, route the failing
- // path through `Repository::run_command` /
- // `WorkingTree::run_command` (or construct a
- // `worktrunk::git::CommandError` directly) instead of
- // `bail!("{stderr}")`.
- debug_assert!(
- false,
- "Multiline error without CommandError or context: {msg}"
+ if !gutter_parts.is_empty() {
+ let _ = writeln!(
+ out,
+ "{}",
+ format_with_gutter(&gutter_parts.join("\n"), None)
);
- log::warn!("Multiline error without CommandError or context: {msg}");
- let normalized = msg.replace("\r\n", "\n").replace('\r', "\n");
- let _ = writeln!(out, "{}", error_message("Command failed"));
- let _ = writeln!(out, "{}", format_with_gutter(&normalized, None));
- } else {
- let _ = writeln!(out, "{}", error_message(&msg));
+ }
+ }
+ None => {
+ // Anyhow error formatting:
+ // - With context: show context as header, root cause in gutter
+ // - Simple error: inline with emoji
+ // - Empty error: skip (errors already printed elsewhere)
+ let msg = error.to_string();
+ if !msg.is_empty() {
+ let chain: Vec<String> = error.chain().skip(1).map(|e| e.to_string()).collect();
+ if !chain.is_empty() {
+ let _ = writeln!(out, "{}", error_message(&msg));
+ let chain_text = chain.join("\n");
+ let _ = writeln!(out, "{}", format_with_gutter(&chain_text, None));
+ } else if msg.contains('\n') || msg.contains('\r') {
+ // A multi-line error reached this branch without being wrapped
+ // in a typed `CommandError` and without `.context(...)` on top.
+ // Buffered command failures should always surface as
+ // `CommandError`; if you hit this assert, route the failing
+ // path through `Repository::run_command` /
+ // `WorkingTree::run_command` (or construct a
+ // `worktrunk::git::CommandError` directly) instead of
+ // `bail!("{stderr}")`.
+ debug_assert!(
+ false,
+ "Multiline error without CommandError or context: {msg}"
+ );
+ log::warn!("Multiline error without CommandError or context: {msg}");
+ let normalized = msg.replace("\r\n", "\n").replace('\r', "\n");
+ let _ = writeln!(out, "{}", error_message("Command failed"));
+ let _ = writeln!(out, "{}", format_with_gutter(&normalized, None));
+ } else {
+ let _ = writeln!(out, "{}", error_message(&msg));
+ }
}
}
}
@@ -1442,7 +1449,7 @@ fn handle_command_failure(error: anyhow::Error, verbose_level: u8, command_line:
print_cwd_removed_hint_if_needed();
// Preserve exit code from child processes (especially for signals like SIGINT)
- let code = exit_code(&error).unwrap_or(1);
+ let code = error.exit_code().unwrap_or(1);
finish_command(verbose_level, command_line, Some(&error));
process::exit(code);
}
@@ -1641,10 +1648,27 @@ mod tests {
let err: anyhow::Error = Err::<(), _>(permission_denied_command_error())
.context("creating worktree")
.unwrap_err();
- let detail = worktrunk::git::display_message(&err);
+ let detail = err.display_message();
assert!(detail.contains("Permission denied"));
assert!(detail.contains("unknown error occurred while reading"));
- // Without find_command_error this would be "creating worktree".
+ // Without `CommandError::find_in` this would be "creating worktree".
assert!(!detail.starts_with("creating worktree"));
}
+
+ /// When a `CommandError` has empty stderr/stdout (signal-killed before
+ /// output, or git silent on a non-zero exit), `display_message` falls
+ /// back to the command summary so the embedding error doesn't end up
+ /// with a blank detail.
+ #[test]
+ fn display_message_falls_back_to_summary_when_capture_empty() {
+ let empty = CommandError {
+ program: "git".into(),
+ args: vec!["fetch".into()],
+ stderr: String::new(),
+ stdout: String::new(),
+ exit_code: None,
+ };
+ let err: anyhow::Error = empty.into();
+ assert_eq!(err.display_message(), "git fetch failed");
+ }
}
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 9bbe39937..01a2cabf6 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -18,6 +18,7 @@ use crate::commands::process::{
use crate::commands::worktree::hooks::PostRemoveContext;
use crate::commands::worktree::{RemoveResult, SwitchBranchInfo, SwitchResult};
use worktrunk::config::UserConfig;
+use worktrunk::git::ErrorExt;
use worktrunk::git::GitError;
use worktrunk::git::IntegrationReason;
use worktrunk::git::Repository;
@@ -449,10 +450,7 @@ fn handle_branch_deletion_result(
"{}",
error_message(cformat!("Failed to delete branch <bold>{branch_name}</>"))
);
- eprintln!(
- "{}",
- format_with_gutter(&worktrunk::git::display_message(&e), None)
- );
+ eprintln!("{}", format_with_gutter(&e.display_message(), None));
Err(e)
}
}
@@ -1268,7 +1266,7 @@ fn handle_detached_removed_worktree_output(
branch: path_dir_name(ctx.worktree_path).to_string(),
path: ctx.worktree_path.to_path_buf(),
remaining_entries: list_remaining_entries(ctx.worktree_path),
- error: worktrunk::git::display_message(&err),
+ error: err.display_message(),
})?;
let (files, bytes) = output
.staged_path
@@ -1344,7 +1342,7 @@ fn handle_named_removed_worktree_foreground(
branch: branch_name.into(),
path: ctx.worktree_path.to_path_buf(),
remaining_entries: list_remaining_entries(ctx.worktree_path),
- error: worktrunk::git::display_message(&err),
+ error: err.display_message(),
})?;
let stats = output
.staged_path
diff --git a/tests/integration_tests/git_error_display.rs b/tests/integration_tests/git_error_display.rs
index de511935f..42ddfcdbc 100644
--- a/tests/integration_tests/git_error_display.rs
+++ b/tests/integration_tests/git_error_display.rs
@@ -1,6 +1,9 @@
use insta::assert_snapshot;
use std::path::PathBuf;
-use worktrunk::git::{FailedCommand, GitError, HookType, WorktrunkError, add_hook_skip_hint};
+use worktrunk::git::{
+ Diagnostic, FailedCommand, GitError, HookErrorWithHint, HookType, WorktrunkError,
+ add_hook_skip_hint,
+};
// ============================================================================
// Worktree errors
@@ -15,7 +18,7 @@ fn display_worktree_removal_failed() {
remaining_entries: None,
};
- assert_snapshot!("worktree_removal_failed", err.to_string());
+ assert_snapshot!("worktree_removal_failed", err.render());
}
#[test]
@@ -31,10 +34,7 @@ fn display_worktree_removal_failed_directory_not_empty() {
]),
};
- assert_snapshot!(
- "worktree_removal_failed_directory_not_empty",
- err.to_string()
- );
+ assert_snapshot!("worktree_removal_failed_directory_not_empty", err.render());
}
#[test]
@@ -48,7 +48,7 @@ fn display_worktree_removal_failed_with_remaining_entries() {
assert_snapshot!(
"worktree_removal_failed_with_remaining_entries",
- err.to_string()
+ err.render()
);
}
@@ -63,7 +63,7 @@ fn display_worktree_removal_failed_many_remaining_entries() {
assert_snapshot!(
"worktree_removal_failed_many_remaining_entries",
- err.to_string()
+ err.render()
);
}
@@ -76,7 +76,7 @@ fn display_worktree_creation_failed() {
command: None,
};
- assert_snapshot!("worktree_creation_failed", err.to_string());
+ assert_snapshot!("worktree_creation_failed", err.render());
}
#[test]
@@ -92,7 +92,7 @@ fn display_worktree_creation_failed_with_command() {
}),
};
- assert_snapshot!("worktree_creation_failed_with_command", err.to_string());
+ assert_snapshot!("worktree_creation_failed_with_command", err.render());
}
#[test]
@@ -101,7 +101,7 @@ fn display_worktree_missing() {
branch: "stale-branch".into(),
};
- assert_snapshot!("worktree_missing", err.to_string());
+ assert_snapshot!("worktree_missing", err.render());
}
#[test]
@@ -113,7 +113,7 @@ fn branch_not_found() {
pr_mr_platform: None,
};
- assert_snapshot!("branch_not_found", err.to_string());
+ assert_snapshot!("branch_not_found", err.render());
}
#[test]
@@ -125,7 +125,7 @@ fn branch_not_found_with_fetch_time() {
pr_mr_platform: None,
};
- assert_snapshot!("branch_not_found_with_fetch_time", err.to_string());
+ assert_snapshot!("branch_not_found_with_fetch_time", err.render());
}
#[test]
@@ -137,7 +137,7 @@ fn branch_not_found_no_create_hint() {
pr_mr_platform: None,
};
- assert_snapshot!("branch_not_found_no_create_hint", err.to_string());
+ assert_snapshot!("branch_not_found_no_create_hint", err.render());
}
#[test]
@@ -150,7 +150,7 @@ fn branch_not_found_numeric_unknown_platform() {
pr_mr_platform: None,
};
- assert_snapshot!("branch_not_found_numeric_unknown_platform", err.to_string());
+ assert_snapshot!("branch_not_found_numeric_unknown_platform", err.render());
}
#[test]
@@ -163,7 +163,7 @@ fn branch_not_found_numeric_github() {
pr_mr_platform: Some(RefType::Pr),
};
- assert_snapshot!("branch_not_found_numeric_github", err.to_string());
+ assert_snapshot!("branch_not_found_numeric_github", err.render());
}
#[test]
@@ -176,7 +176,7 @@ fn branch_not_found_numeric_gitlab() {
pr_mr_platform: Some(RefType::Mr),
};
- assert_snapshot!("branch_not_found_numeric_gitlab", err.to_string());
+ assert_snapshot!("branch_not_found_numeric_gitlab", err.render());
}
#[test]
@@ -187,7 +187,7 @@ fn display_worktree_path_occupied() {
occupant: Some("other-branch".into()),
};
- assert_snapshot!("worktree_path_occupied", err.to_string());
+ assert_snapshot!("worktree_path_occupied", err.render());
}
#[test]
@@ -198,14 +198,14 @@ fn display_worktree_path_exists() {
create: false,
};
- assert_snapshot!("worktree_path_exists", err.to_string());
+ assert_snapshot!("worktree_path_exists", err.render());
}
#[test]
fn display_cannot_remove_main_worktree() {
let err = GitError::CannotRemoveMainWorktree;
- assert_snapshot!("cannot_remove_main_worktree", err.to_string());
+ assert_snapshot!("cannot_remove_main_worktree", err.render());
}
// ============================================================================
@@ -218,14 +218,14 @@ fn display_detached_head() {
action: Some("merge".into()),
};
- assert_snapshot!("detached_head", err.to_string());
+ assert_snapshot!("detached_head", err.render());
}
#[test]
fn display_detached_head_no_action() {
let err = GitError::DetachedHead { action: None };
- assert_snapshot!("detached_head_no_action", err.to_string());
+ assert_snapshot!("detached_head_no_action", err.render());
}
#[test]
@@ -236,7 +236,7 @@ fn display_uncommitted_changes() {
force_hint: false,
};
- assert_snapshot!("uncommitted_changes", err.to_string());
+ assert_snapshot!("uncommitted_changes", err.render());
}
#[test]
@@ -247,7 +247,7 @@ fn display_uncommitted_changes_with_branch() {
force_hint: false,
};
- assert_snapshot!("uncommitted_changes_with_branch", err.to_string());
+ assert_snapshot!("uncommitted_changes_with_branch", err.render());
}
#[test]
@@ -258,7 +258,7 @@ fn display_uncommitted_changes_with_force_hint() {
force_hint: true,
};
- assert_snapshot!("uncommitted_changes_with_force_hint", err.to_string());
+ assert_snapshot!("uncommitted_changes_with_force_hint", err.render());
}
#[test]
@@ -267,7 +267,7 @@ fn display_branch_already_exists() {
branch: "feature".into(),
};
- assert_snapshot!("branch_already_exists", err.to_string());
+ assert_snapshot!("branch_already_exists", err.render());
}
// ============================================================================
@@ -281,7 +281,7 @@ fn display_push_failed() {
error: "To /Users/user/workspace/repo/.git\n ! [remote rejected] HEAD -> main (Up-to-date check failed)\nerror: failed to push some refs to '/Users/user/workspace/repo/.git'".into(),
};
- assert_snapshot!("push_failed", err.to_string());
+ assert_snapshot!("push_failed", err.render());
}
#[test]
@@ -292,7 +292,7 @@ fn display_conflicting_changes() {
worktree_path: PathBuf::from("/tmp/repo.main"),
};
- assert_snapshot!("conflicting_changes", err.to_string());
+ assert_snapshot!("conflicting_changes", err.render());
}
#[test]
@@ -303,7 +303,7 @@ fn display_not_fast_forward() {
in_merge_context: false,
};
- assert_snapshot!("not_fast_forward", err.to_string());
+ assert_snapshot!("not_fast_forward", err.render());
}
#[test]
@@ -314,7 +314,7 @@ fn display_not_fast_forward_merge_context() {
in_merge_context: true,
};
- assert_snapshot!("not_fast_forward_merge_context", err.to_string());
+ assert_snapshot!("not_fast_forward_merge_context", err.render());
}
#[test]
@@ -324,7 +324,7 @@ fn display_rebase_conflict() {
git_output: "CONFLICT (content): Merge conflict in src/main.rs".into(),
};
- assert_snapshot!("rebase_conflict", err.to_string());
+ assert_snapshot!("rebase_conflict", err.render());
}
// ============================================================================
@@ -335,7 +335,7 @@ fn display_rebase_conflict() {
fn display_not_interactive() {
let err = GitError::NotInteractive;
- assert_snapshot!("not_interactive", err.to_string());
+ assert_snapshot!("not_interactive", err.render());
}
#[test]
@@ -346,7 +346,7 @@ fn display_llm_command_failed() {
reproduction_command: None,
};
- assert_snapshot!("llm_command_failed", err.to_string());
+ assert_snapshot!("llm_command_failed", err.render());
}
#[test]
@@ -357,7 +357,7 @@ fn display_llm_command_failed_with_reproduction() {
reproduction_command: Some("wt step commit --show-prompt | llm --model claude".into()),
};
- assert_snapshot!("llm_command_failed_with_reproduction", err.to_string());
+ assert_snapshot!("llm_command_failed_with_reproduction", err.render());
}
#[test]
@@ -366,7 +366,7 @@ fn display_project_config_not_found() {
config_path: PathBuf::from("/tmp/repo/.config/wt.toml"),
};
- assert_snapshot!("project_config_not_found", err.to_string());
+ assert_snapshot!("project_config_not_found", err.render());
}
#[test]
@@ -375,7 +375,7 @@ fn display_parse_error() {
message: "Invalid branch name format".into(),
};
- assert_snapshot!("parse_error", err.to_string());
+ assert_snapshot!("parse_error", err.render());
}
#[test]
@@ -385,7 +385,7 @@ fn display_remote_only_branch() {
remote: "origin".into(),
};
- assert_snapshot!("remote_only_branch", err.to_string());
+ assert_snapshot!("remote_only_branch", err.render());
}
#[test]
@@ -394,7 +394,7 @@ fn display_other() {
message: "Unexpected git error".into(),
};
- assert_snapshot!("other", err.to_string());
+ assert_snapshot!("other", err.render());
}
// ============================================================================
@@ -410,7 +410,7 @@ fn display_hook_command_failed_with_name() {
exit_code: Some(1),
};
- assert_snapshot!("hook_command_failed_with_name", err.to_string());
+ assert_snapshot!("hook_command_failed_with_name", err.render());
}
#[test]
@@ -422,7 +422,7 @@ fn display_hook_command_failed_without_name() {
exit_code: Some(127),
};
- assert_snapshot!("hook_command_failed_without_name", err.to_string());
+ assert_snapshot!("hook_command_failed_without_name", err.render());
}
/// Shows the complete error with hint, as users would see it.
@@ -441,7 +441,10 @@ fn display_hook_command_failed_with_skip_hint() {
assert_snapshot!(
"hook_command_failed_with_skip_hint",
- err_with_hint.to_string()
+ err_with_hint
+ .downcast_ref::<HookErrorWithHint>()
+ .expect("wrapped to HookErrorWithHint")
+ .render()
);
}
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__remote_only_branch.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__remote_only_branch.snap
index 87cd87753..4197e3f6b 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__remote_only_branch.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__remote_only_branch.snap
@@ -1,6 +1,6 @@
---
source: tests/integration_tests/git_error_display.rs
-expression: err.to_string()
+expression: err.render()
---
✗ Branch feature exists only on remote (origin/feature)
-↳ To create a local worktree, run wt switch feature
+↳ To create a local worktree, run wt switch feature
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_remote_only_branch.snap b/tests/snapshots/integration__integration_tests__remove__remove_remote_only_branch.snap
index cc1f7bb87..9eed4b206 100644
--- a/tests/snapshots/integration__integration_tests__remove__remove_remote_only_branch.snap
+++ b/tests/snapshots/integration__integration_tests__remove__remove_remote_only_branch.snap
@@ -11,10 +11,15 @@ info:
COLUMNS: "500"
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMON_DIR: ""
GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
GIT_CONFIG_SYSTEM: /dev/null
+ GIT_DIR: ""
GIT_EDITOR: ""
+ GIT_INDEX_FILE: ""
+ GIT_OBJECT_DIRECTORY: ""
GIT_TERMINAL_PROMPT: "0"
+ GIT_WORK_TREE: ""
HOME: "[TEST_HOME]"
LANG: C
LC_ALL: C
@@ -30,13 +35,17 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
---
success: false
@@ -45,4 +54,4 @@ exit_code: 1
----- stderr -----
✗ Branch remote-feature exists only on remote (origin/remote-feature)
-↳ To create a local worktree, run wt switch remote-feature
+↳ To create a local worktree, run wt switch remote-feature