Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Errors: `GitError` now formats itself
Maximilian Roos11bad5d86a4b
diff --git a/Cargo.lock b/Cargo.lockindex a03873a50..86a9da90c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2911,7 +2911,6 @@ dependencies = ["synoptic","tempfile","terminal_size",- "thiserror 2.0.17","toml","toml_edit","tree-sitter",diff --git a/Cargo.toml b/Cargo.tomlindex e4a7bd1a8..cd1c5b3d4 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -45,7 +45,6 @@ required-features = ["shell-integration-tests"][dependencies]anyhow = "1.0"-thiserror = "2.0"anstream = "0.6"anstyle = "1.0"ansi-str = "0.9"diff --git a/src/git/error.rs b/src/git/error.rsindex 4702f406d..d4a2f2bd0 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -4,7 +4,7 @@//!//! - **`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 and styled display in main.rs.+//! type for pattern matching. Display produces styled output for users.//!//! - **`WorktrunkError`** - A minimal enum for semantic errors that need//! special handling (exit codes, silent errors).@@ -25,11 +25,12 @@ use crate::styling::{////// 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.////// # Usage////// ```ignore-/// // Return a typed error (main.rs handles styled display via downcast)+/// // Return a typed error (Display produces styled output)/// return Err(GitError::DetachedHead { action: Some("merge".into()) }.into());////// // Pattern match on errors@@ -37,42 +38,36 @@ use crate::styling::{/// println!("Branch {} exists", branch);/// }/// ```-#[derive(Debug, Clone, thiserror::Error)]+#[derive(Debug, Clone)]pub enum GitError {// -------------------------------------------------------------------------// Git state errors// -------------------------------------------------------------------------/// HEAD is detached (not on a branch)- #[error("not on a branch (detached HEAD)")]DetachedHead {/// Action that was blocked (e.g., "merge", "push")action: Option<String>,},/// Working tree has uncommitted changes- #[error("working tree has uncommitted changes")]UncommittedChanges {/// Action that was blocked (e.g., "remove worktree")action: Option<String>,},/// Branch already exists- #[error("branch '{branch}' already exists")]BranchAlreadyExists { branch: String },// -------------------------------------------------------------------------// Worktree errors// -------------------------------------------------------------------------/// Worktree directory is missing from filesystem- #[error("worktree directory missing for '{branch}'")]WorktreeMissing { branch: String },/// No worktree exists for the given branch- #[error("no worktree found for branch '{branch}'")]NoWorktreeFound { branch: String },/// Target path for worktree is already occupied- #[error("cannot create worktree for '{branch}': target path already exists")]WorktreePathOccupied {branch: String,path: PathBuf,@@ -81,11 +76,9 @@ pub enum GitError {},/// Directory already exists at target path- #[error("directory already exists: {}", path.display())]WorktreePathExists { path: PathBuf },/// Failed to create worktree- #[error("failed to create worktree for '{branch}'")]WorktreeCreationFailed {branch: String,base_branch: Option<String>,@@ -93,7 +86,6 @@ pub enum GitError {},/// Failed to remove worktree- #[error("failed to remove worktree for '{branch}'")]WorktreeRemovalFailed {branch: String,path: PathBuf,@@ -104,14 +96,12 @@ pub enum GitError {// Merge/push errors// -------------------------------------------------------------------------/// Conflicting uncommitted changes prevent operation- #[error("conflicting uncommitted changes")]ConflictingChanges {files: Vec<String>,worktree_path: PathBuf,},/// Push is not fast-forward- #[error("cannot push: target branch has newer commits")]NotFastForward {target_branch: String,/// Formatted commit list for display@@ -121,33 +111,27 @@ pub enum GitError {},/// Merge commits found in push range- #[error("found merge commits in push range")]MergeCommitsFound,/// Rebase stopped due to conflicts- #[error("rebase onto '{target_branch}' incomplete")]RebaseConflict {target_branch: String,git_output: String,},/// Push operation failed- #[error("push failed")]PushFailed { error: String },// -------------------------------------------------------------------------// Validation errors// -------------------------------------------------------------------------/// Cannot prompt in non-interactive environment- #[error("cannot prompt for approval in non-interactive environment")]NotInteractive,/// Parse error (for git output parsing failures)- #[error("{message}")]ParseError { message: String },/// LLM command failed during commit generation- #[error("commit generation command failed")]LlmCommandFailed {/// The full command string (e.g., "llm --model claude")command: String,@@ -156,30 +140,27 @@ pub enum GitError {},/// Project configuration file not found- #[error("no project configuration found")]ProjectConfigNotFound {/// Path where config file was expectedconfig_path: PathBuf,},/// Generic error with custom message- #[error("{message}")]Other { message: String },}-impl GitError {- /// Returns the styled error message with emoji and colors.- ///- /// Use this when displaying errors to users. The styling follows the- /// project's output conventions (ERROR_EMOJI, ERROR style, hints).- pub fn styled(&self) -> String {+impl std::error::Error for GitError {}++impl std::fmt::Display for GitError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {match self {GitError::DetachedHead { action } => {let message = match action {Some(action) => format!("Cannot {action}: not on a branch (detached HEAD)"),None => "Not on a branch (detached HEAD)".to_string(),};- format!(+ write!(+ f,"{ERROR_EMOJI} {ERROR}{message}{ERROR:#}\n\n{HINT_EMOJI} {HINT}Switch to a branch first with 'git switch <branch>'{HINT:#}")}@@ -191,25 +172,29 @@ impl GitError {}None => "Working tree has uncommitted changes".to_string(),};- format!(+ write!(+ f,"{ERROR_EMOJI} {ERROR}{message}{ERROR:#}\n\n{HINT_EMOJI} {HINT}Commit or stash them first{HINT:#}")}GitError::BranchAlreadyExists { branch } => {- format!(+ write!(+ f,"{ERROR_EMOJI} {ERROR}Branch {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR} already exists{ERROR:#}\n\n{HINT_EMOJI} {HINT}Remove --create flag to switch to it{HINT:#}")}GitError::WorktreeMissing { branch } => {- format!(+ write!(+ f,"{ERROR_EMOJI} {ERROR}Worktree directory missing for {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR:#}\n\n{HINT_EMOJI} {HINT}Run 'git worktree prune' to clean up{HINT:#}")}GitError::NoWorktreeFound { branch } => {- format!(+ write!(+ f,"{ERROR_EMOJI} {ERROR}No worktree found for branch {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR:#}")}@@ -223,7 +208,8 @@ impl GitError {.as_ref().map(|b| format!(" (currently on {HINT_BOLD}{b}{HINT_BOLD:#}{HINT})")).unwrap_or_default();- format!(+ write!(+ f,"{ERROR_EMOJI} {ERROR}Cannot create worktree for {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR}: target path already exists{ERROR:#}\n\n{HINT_EMOJI} {HINT}Reuse the existing worktree at {}{} or remove it before retrying{HINT:#}",format_path_for_display(path),occupant_note@@ -231,7 +217,8 @@ impl GitError {}GitError::WorktreePathExists { path } => {- format!(+ write!(+ f,"{ERROR_EMOJI} {ERROR}Directory already exists: {ERROR_BOLD}{}{ERROR_BOLD:#}{ERROR:#}\n\n{HINT_EMOJI} {HINT}Remove the directory or use a different branch name{HINT:#}",format_path_for_display(path))@@ -251,7 +238,7 @@ impl GitError {let header = format!("{ERROR_EMOJI} {ERROR}Failed to create worktree for {ERROR_BOLD}{branch}{ERROR_BOLD:#}{base_suffix}{ERROR:#}");- format_error_block(header, error)+ write!(f, "{}", format_error_block(header, error))}GitError::WorktreeRemovalFailed {@@ -263,25 +250,26 @@ impl GitError {"{ERROR_EMOJI} {ERROR}Failed to remove worktree for {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR} at {ERROR_BOLD}{}{ERROR_BOLD:#}{ERROR:#}",format_path_for_display(path));- format_error_block(header, error)+ write!(f, "{}", format_error_block(header, error))}GitError::ConflictingChanges {files,worktree_path,} => {- let mut msg = format!(+ write!(+ f,"{ERROR_EMOJI} {ERROR}Cannot push: conflicting uncommitted changes in:{ERROR:#}\n\n"- );+ )?;if !files.is_empty() {let joined_files = files.join("\n");- msg.push_str(&format_with_gutter(&joined_files, "", None));+ write!(f, "{}", format_with_gutter(&joined_files, "", None))?;}- msg.push_str(&format!(+ write!(+ f,"\n{HINT_EMOJI} {HINT}Commit or stash these changes in {} first{HINT:#}",format_path_for_display(worktree_path)- ));- msg+ )}GitError::NotFastForward {@@ -289,12 +277,12 @@ impl GitError {commits_formatted,in_merge_context,} => {- let mut msg = format!(+ write!(+ f,"{ERROR_EMOJI} {ERROR}Can't push to local {ERROR_BOLD}{target_branch}{ERROR_BOLD:#}{ERROR} branch: it has newer commits{ERROR:#}"- );+ )?;if !commits_formatted.is_empty() {- msg.push('\n');- msg.push_str(&format_with_gutter(commits_formatted, "", None));+ write!(f, "\n{}", format_with_gutter(commits_formatted, "", None))?;}// Context-appropriate hintlet hint = if *in_merge_context {@@ -302,12 +290,12 @@ impl GitError {} else {format!("Use 'wt step rebase' or 'wt merge' to rebase onto {target_branch}")};- msg.push_str(&format!("\n{HINT_EMOJI} {HINT}{hint}{HINT:#}"));- msg+ write!(f, "\n{HINT_EMOJI} {HINT}{hint}{HINT:#}")}GitError::MergeCommitsFound => {- format!(+ write!(+ f,"{ERROR_EMOJI} {ERROR}Found merge commits in push range{ERROR:#}\n\n{HINT_EMOJI} {HINT}Use --allow-merge-commits to push non-linear history{HINT:#}")}@@ -316,27 +304,28 @@ impl GitError {target_branch,git_output,} => {- let mut msg = format!(+ write!(+ f,"{ERROR_EMOJI} {ERROR}Rebase onto {ERROR_BOLD}{target_branch}{ERROR_BOLD:#}{ERROR} incomplete{ERROR:#}"- );+ )?;if !git_output.is_empty() {- msg.push('\n');- msg.push_str(&format_with_gutter(git_output, "", None));+ write!(f, "\n{}", format_with_gutter(git_output, "", None))} else {- msg.push_str(&format!(+ write!(+ f,"\n\n{HINT_EMOJI} {HINT}Resolve conflicts and run 'git rebase --continue'{HINT:#}\n{HINT_EMOJI} {HINT}Or abort with 'git rebase --abort'{HINT:#}"- ));+ )}- msg}GitError::PushFailed { error } => {let header = format!("{ERROR_EMOJI} {ERROR}Push failed{ERROR:#}");- format_error_block(header, error)+ write!(f, "{}", format_error_block(header, error))}GitError::NotInteractive => {- format!(+ write!(+ f,"{ERROR_EMOJI} {ERROR}Cannot prompt for approval in non-interactive environment{ERROR:#}\n\n{HINT_EMOJI} {HINT}In CI/CD, use --force to skip prompts. To pre-approve commands, use 'wt config approvals add'{HINT:#}")}@@ -345,49 +334,33 @@ impl GitError {let error_header =format!("{ERROR_EMOJI} {ERROR}Commit generation command failed{ERROR:#}");let error_block = format_error_block(error_header, error);-- // Build message: error block + blank line separator + info blocklet command_gutter = format_with_gutter(command, "", None);-- let mut msg = error_block.trim_end().to_string();- msg.push_str("\n\n"); // "One blank after blocks"- msg.push_str(INFO_EMOJI);- msg.push_str(" Ran command:\n");- msg.push_str(command_gutter.trim_end());- msg+ write!(+ f,+ "{}\n\n{INFO_EMOJI} Ran command:\n{}",+ error_block.trim_end(),+ command_gutter.trim_end()+ )}GitError::ProjectConfigNotFound { config_path } => {- format!(+ write!(+ f,"{ERROR_EMOJI} {ERROR}No project configuration found{ERROR:#}\n\n{HINT_EMOJI} {HINT}Create a config file at: {HINT_BOLD}{}{HINT_BOLD:#}{HINT:#}",format_path_for_display(config_path))}GitError::ParseError { message } | GitError::Other { message } => {- format!("{ERROR_EMOJI} {ERROR}{message}{ERROR:#}")+ write!(f, "{ERROR_EMOJI} {ERROR}{message}{ERROR:#}")}}}}-/// Check if an error is a specific GitError variant-pub fn is_git_error<F>(err: &anyhow::Error, predicate: F) -> bool-where- F: FnOnce(&GitError) -> bool,-{- err.downcast_ref::<GitError>().is_some_and(predicate)-}--/// Check if error is DetachedHead-pub fn is_detached_head(err: &anyhow::Error) -> bool {- is_git_error(err, |e| matches!(e, GitError::DetachedHead { .. }))-}--/// Check if error is BranchAlreadyExists-pub fn is_branch_already_exists(err: &anyhow::Error) -> bool {- is_git_error(err, |e| matches!(e, GitError::BranchAlreadyExists { .. }))-}+// =============================================================================+// WorktrunkError - Semantic errors with special handling+// =============================================================================/// Semantic errors that require special handling in main.rs///@@ -477,57 +450,44 @@ mod tests {use super::*;#[test]- fn test_git_error_display_plain() {- // thiserror's Display impl provides plain, unstyled messages- let err = GitError::DetachedHead {- action: Some("merge".into()),- };- assert_eq!(err.to_string(), "not on a branch (detached HEAD)");-- let err = GitError::BranchAlreadyExists {- branch: "feature".into(),- };- assert_eq!(err.to_string(), "branch 'feature' already exists");- }-- #[test]- fn test_git_error_styled_contains_emoji() {+ fn test_git_error_display_contains_emoji() {+ // Display produces styled output with emojilet err = GitError::DetachedHead { action: None };- let styled = err.styled();- assert!(styled.contains("β")); // ERROR_EMOJI- assert!(styled.contains("detached HEAD"));- assert!(styled.contains("π‘")); // HINT_EMOJI+ let output = err.to_string();+ assert!(output.contains("β")); // ERROR_EMOJI+ assert!(output.contains("detached HEAD"));+ assert!(output.contains("π‘")); // HINT_EMOJI}#[test]- fn test_git_error_styled_includes_action() {+ fn test_git_error_display_includes_action() {let err = GitError::DetachedHead {action: Some("push".into()),};- let styled = err.styled();- assert!(styled.contains("Cannot push"));+ let output = err.to_string();+ assert!(output.contains("Cannot push"));let err = GitError::UncommittedChanges {action: Some("remove worktree".into()),};- let styled = err.styled();- assert!(styled.contains("Cannot remove worktree"));+ let output = err.to_string();+ assert!(output.contains("Cannot remove worktree"));}#[test]- fn test_into_preserves_type_for_styled_output() {- // .into() preserves type so we can downcast and get styled output+ fn test_into_preserves_type_for_display() {+ // .into() preserves type so we can downcast and use Displaylet err: anyhow::Error = GitError::BranchAlreadyExists {branch: "main".into(),}.into();- // Can downcast and get styled output+ // Can downcast and get styled output via Displaylet git_err = err.downcast_ref::<GitError>().expect("Should downcast");- let styled = git_err.styled();- assert!(styled.contains("β")); // Should be styled- assert!(styled.contains("main"));- assert!(styled.contains("already exists"));+ let output = git_err.to_string();+ assert!(output.contains("β")); // Should be styled+ assert!(output.contains("main"));+ assert!(output.contains("already exists"));}#[test]@@ -545,26 +505,12 @@ mod tests {}}- #[test]- fn test_is_git_error_helper() {- let err: anyhow::Error = GitError::DetachedHead { action: None }.into();- assert!(is_detached_head(&err));- assert!(!is_branch_already_exists(&err));-- let err: anyhow::Error = GitError::BranchAlreadyExists {- branch: "test".into(),- }- .into();- assert!(!is_detached_head(&err));- assert!(is_branch_already_exists(&err));- }-#[test]fn test_worktree_error_with_path() {let err = GitError::WorktreePathExists {path: PathBuf::from("/some/path"),};- let styled = err.styled();- assert!(styled.contains("Directory already exists"));+ let output = err.to_string();+ assert!(output.contains("Directory already exists"));}}diff --git a/src/git/mod.rs b/src/git/mod.rsindex 13f30bcd6..ed6f447f4 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -31,16 +31,13 @@ static HEAVY_OPS_SEMAPHORE: LazyLock<semaphore::Semaphore> =// Re-exports from submodulespub use diff::{DiffStats, LineDiff};pub use error::{- // Typed error enum+ // Typed error enum (Display produces styled output)GitError,- // Special-handling error enum+ // Special-handling error enum (Display produces styled output)WorktrunkError,// Error inspection functionsexit_code,- is_branch_already_exists,is_command_not_approved,- is_detached_head,- is_git_error,};pub use repository::{Repository, set_base_path};diff --git a/src/main.rs b/src/main.rsindex 73966df55..939b2ac5a 100644--- a/src/main.rs+++ b/src/main.rs@@ -783,21 +783,18 @@ fn main() {if let Err(e) = result {use worktrunk::styling::{ERROR, ERROR_EMOJI};- // GitError and WorktrunkError produce styled messages+ // GitError and WorktrunkError produce styled output via Displayif let Some(git_err) = e.downcast_ref::<worktrunk::git::GitError>() {- let _ = output::print(git_err.styled());+ let _ = output::print(git_err.to_string());} else if let Some(wt_err) = e.downcast_ref::<worktrunk::git::WorktrunkError>() {let _ = output::print(wt_err.to_string());} else {- // Anyhow error - format with emoji/styling, multi-line gets gutter+ // Anyhow error - show context message, multi-line root cause gets gutterlet msg = e.to_string();let root_cause = e.root_cause().to_string();- let has_context = msg != root_cause;- if has_context && root_cause.contains('\n') {- let _ = output::print(format!("{ERROR_EMOJI} {ERROR}{msg}{ERROR:#}"));+ let _ = output::print(format!("{ERROR_EMOJI} {ERROR}{msg}{ERROR:#}"));+ if msg != root_cause && root_cause.contains('\n') {let _ = output::gutter(format_with_gutter(&root_cause, "", None));- } else {- let _ = output::print(format!("{ERROR_EMOJI} {ERROR}{msg}{ERROR:#}"));}}diff --git a/tests/git_error_display.rs b/tests/git_error_display.rsindex 708544201..c94ef4371 100644--- a/tests/git_error_display.rs+++ b/tests/git_error_display.rs@@ -10,7 +10,7 @@ fn display_worktree_removal_failed() {error: "fatal: worktree is dirty\nerror: could not remove worktree".into(),};- assert_snapshot!("worktree_removal_failed", err.styled());+ assert_snapshot!("worktree_removal_failed", err.to_string());}#[test]@@ -19,5 +19,5 @@ 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.styled());+ assert_snapshot!("push_failed", err.to_string());}