Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Refactor: Introduce typed GitError for robust error handling
Maximilian Roos2173f3a1349e
diff --git a/Cargo.lock b/Cargo.lockindex 86a9da90c..a03873a50 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2911,6 +2911,7 @@ dependencies = ["synoptic","tempfile","terminal_size",+ "thiserror 2.0.17","toml","toml_edit","tree-sitter",diff --git a/Cargo.toml b/Cargo.tomlindex cd1c5b3d4..e4a7bd1a8 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -45,6 +45,7 @@ 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/commands/command_approval.rs b/src/commands/command_approval.rsindex 3634efbb9..0ae6938d0 100644--- a/src/commands/command_approval.rs+++ b/src/commands/command_approval.rs@@ -5,7 +5,7 @@use crate::output;use anyhow::Context;use worktrunk::config::{Command, WorktrunkConfig};-use worktrunk::git::not_interactive;+use worktrunk::git::GitError;use worktrunk::styling::{AnstyleStyle, HINT_EMOJI, INFO_EMOJI, WARNING, WARNING_BOLD, WARNING_EMOJI, eprint, eprintln,format_bash_with_gutter, stderr,@@ -109,7 +109,7 @@ fn prompt_for_batch_approval(commands: &[&Command], project_id: &str) -> anyhow:// This happens AFTER showing the commands so they appear in CI/CD logs// even when the prompt cannot be displayed (fail-fast principle)if !io::stdin().is_terminal() {- return Err(not_interactive());+ return Err(GitError::NotInteractive.styled_err());}// Flush stderr before showing prompt to ensure all output is visiblediff --git a/src/commands/merge.rs b/src/commands/merge.rsindex b6644c34f..7d2241073 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -84,10 +84,10 @@ pub fn handle_merge(// Validate --no-commit: requires clean working treeif !commit && repo.is_dirty()? {- return Err(anyhow::anyhow!(- "{}",- worktrunk::git::uncommitted_changes(Some("merge with --no-commit"))- ));+ return Err(worktrunk::git::GitError::UncommittedChanges {+ action: Some("merge with --no-commit".into()),+ }+ .styled_err());}// Validate --no-commit flag compatibilitydiff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex a53ebb1df..e524036ac 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -5,7 +5,7 @@ use std::time::{SystemTime, UNIX_EPOCH};use super::worktree::RemoveResult;use anyhow::Context;use worktrunk::config::ProjectConfig;-use worktrunk::git::{Repository, conflicting_changes, no_worktree_found, worktree_missing};+use worktrunk::git::{GitError, Repository};use worktrunk::path::format_path_for_display;use worktrunk::styling::{CYAN, CYAN_BOLD, ERROR, ERROR_EMOJI, HINT, HINT_BOLD, HINT_EMOJI, WARNING, WARNING_BOLD,@@ -89,12 +89,18 @@ impl RepositoryCliExt for Repository {force_delete,});}- return Err(no_worktree_found(branch_name));+ return Err(GitError::NoWorktreeFound {+ branch: branch_name.into(),+ }+ .styled_err());}};if !worktree_path.exists() {- return Err(worktree_missing(branch_name));+ return Err(GitError::WorktreeMissing {+ branch: branch_name.into(),+ }+ .styled_err());}let target_repo = Repository::at(&worktree_path);@@ -153,7 +159,11 @@ impl RepositoryCliExt for Repository {.collect();if !overlapping.is_empty() {- return Err(conflicting_changes(&overlapping, wt_path));+ return Err(GitError::ConflictingChanges {+ files: overlapping,+ worktree_path: wt_path.clone(),+ }+ .styled_err());}let nanos = SystemTime::now()diff --git a/src/commands/standalone.rs b/src/commands/standalone.rsindex 375a746a1..3b485f3a6 100644--- a/src/commands/standalone.rs+++ b/src/commands/standalone.rs@@ -1,4 +1,4 @@-use anyhow::{Context, bail};+use anyhow::Context;use worktrunk::HookType;use worktrunk::git::Repository;use worktrunk::styling::{AnstyleStyle, CYAN, CYAN_BOLD, GREEN_BOLD, format_with_gutter};@@ -54,7 +54,10 @@ pub fn handle_standalone_run_hook(hook_type: HookType, force: bool) -> anyhow::Rfn check_hook_configured<T>(hook: &Option<T>, hook_type: HookType) -> anyhow::Result<()> {if hook.is_none() {- return Err(anyhow::anyhow!(format!("No {hook_type} hook configured")));+ return Err(worktrunk::git::GitError::Other {+ message: format!("No {hook_type} hook configured"),+ }+ .styled_err());}Ok(())}@@ -326,19 +329,27 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {{// Extract git's stderr output from the errorlet git_output = e.to_string();- bail!(- "{}",- worktrunk::git::rebase_conflict(&target_branch, &git_output)- );+ return Err(worktrunk::git::GitError::RebaseConflict {+ target_branch: target_branch.clone(),+ git_output,+ }+ .styled_err());}// Not a rebase conflict, return original error- bail!("Failed to rebase onto '{}': {}", target_branch, e);+ return Err(worktrunk::git::GitError::Other {+ message: format!("Failed to rebase onto '{}': {}", target_branch, e),+ }+ .styled_err());}// Verify rebase completed successfully (safety check for edge cases)if let Some(state) = repo.worktree_state()? {let _ = state; // used for diagnostics- return Err(worktrunk::git::rebase_conflict(&target_branch, ""));+ return Err(worktrunk::git::GitError::RebaseConflict {+ target_branch: target_branch.clone(),+ git_output: String::new(),+ }+ .styled_err());}// Successdiff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 95cb1b50e..bc71adeca 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -108,17 +108,13 @@//!//! The shell wrapper is generated by `wt config shell init <shell>` from templates in `templates/`.-use anyhow::{Context, bail};+use anyhow::Context;use std::path::PathBuf;use worktrunk::HookType;use worktrunk::config::{CommandPhase, WorktrunkConfig};-use worktrunk::git::{- Repository, branch_already_exists, is_command_not_approved, merge_commits_found, push_failed,- worktree_creation_failed, worktree_missing, worktree_path_exists, worktree_path_occupied,-};+use worktrunk::git::{GitError, Repository, is_command_not_approved};use worktrunk::styling::{- AnstyleStyle, CYAN, CYAN_BOLD, ERROR, ERROR_BOLD, ERROR_EMOJI, GREEN, GREEN_BOLD, HINT,- HINT_EMOJI, WARNING, format_with_gutter,+ AnstyleStyle, CYAN, CYAN_BOLD, GREEN, GREEN_BOLD, WARNING, format_with_gutter,};use super::command_executor::CommandContext;@@ -222,7 +218,10 @@ pub fn handle_switch(// Check for conflicting conditionsif create && repo.local_branch_exists(&resolved_branch)? {- return Err(branch_already_exists(&resolved_branch));+ return Err(GitError::BranchAlreadyExists {+ branch: resolved_branch.clone(),+ }+ .styled_err());}// Check if base flag was provided without create flag@@ -261,7 +260,10 @@ pub fn handle_switch());}Some(_) => {- return Err(worktree_missing(&resolved_branch));+ return Err(GitError::WorktreeMissing {+ branch: resolved_branch.clone(),+ }+ .styled_err());}None => {}}@@ -288,10 +290,12 @@ pub fn handle_switch(.current_branch().ok().flatten();- bail!(- "{}",- worktree_path_occupied(&resolved_branch, &worktree_path, occupant.as_deref())- );+ return Err(GitError::WorktreePathOccupied {+ branch: resolved_branch.clone(),+ path: worktree_path,+ occupant,+ }+ .styled_err());}// Create the worktree@@ -337,14 +341,19 @@ pub fn handle_switch(let path = std::path::PathBuf::from(path_str);// Canonicalize if possible, otherwise use as-islet normalized_path = path.canonicalize().unwrap_or(path);- return Err(worktree_path_exists(&normalized_path));+ return Err(GitError::WorktreePathExists {+ path: normalized_path,+ }+ .styled_err());}}// Fall back to generic error with context- bail!(- "{}",- worktree_creation_failed(&resolved_branch, base_for_creation.as_deref(), &msg)- );+ return Err(GitError::WorktreeCreationFailed {+ branch: resolved_branch.clone(),+ base_branch: base_for_creation.clone(),+ error: msg,+ }+ .styled_err());}// Canonicalize the path to resolve any .. components@@ -518,30 +527,18 @@ pub fn handle_push(.trim().to_string();- let mut msg = format!(- "{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));+ return Err(GitError::NotFastForward {+ target_branch: target_branch.clone(),+ commits_formatted,+ in_merge_context: operations.is_some(),}-- // Context-appropriate hint: operations.is_some() means we're in merge context- let hint = if operations.is_some() {- "Run 'wt merge' again to incorporate these changes".to_string()- } else {- format!("Use 'wt step rebase' or 'wt merge' to rebase onto {target_branch}")- };- msg.push_str(&format!("\n{HINT_EMOJI} {HINT}{hint}{HINT:#}"));-- bail!("{}", msg);+ .styled_err());}// Check for merge commits unless allowedlet has_merge_commits = repo.has_merge_commits(&target_branch, "HEAD")?;if !allow_merge_commits && has_merge_commits {- return Err(merge_commits_found());+ return Err(GitError::MergeCommitsFound.styled_err());}// Check for conflicting changes in target worktree (auto-stash safe changes)@@ -639,7 +636,10 @@ pub fn handle_push(stash.restore()?;}// CommandFailed contains raw git output, wrap in PushFailed for proper formatting- return Err(push_failed(&e.to_string()));+ return Err(GitError::PushFailed {+ error: e.to_string(),+ }+ .styled_err());}if let Some(stash) = target_worktree_stash.take() {diff --git a/src/git/error.rs b/src/git/error.rsindex 51205fa34..5418a5128 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -1,9 +1,15 @@-//! Worktrunk error types and formatting helpers+//! Worktrunk error types and formatting//!-//! Uses anyhow for error propagation. WorktrunkError is a minimal enum for-//! semantic errors that need special handling (exit codes, silent errors).+//! This module provides typed error handling:+//!+//! - **`GitError`** - A typed enum for domain errors that can be pattern-matched+//! and tested. Use `.styled_err()` to convert to styled `anyhow::Error` for user+//! display, or `.into()` to preserve the type for pattern matching.+//!+//! - **`WorktrunkError`** - A minimal enum for semantic errors that need+//! special handling (exit codes, silent errors).-use std::path::Path;+use std::path::PathBuf;use super::HookType;use crate::path::format_path_for_display;@@ -11,6 +17,385 @@ use crate::styling::{ERROR, ERROR_BOLD, ERROR_EMOJI, HINT, HINT_BOLD, HINT_EMOJI, INFO_EMOJI, format_with_gutter,};+// =============================================================================+// GitError - Typed domain errors+// =============================================================================++/// Domain errors for git and worktree operations.+///+/// 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.+///+/// # Usage+///+/// ```ignore+/// // Return a styled error for user display+/// return Err(GitError::DetachedHead { action: Some("merge".into()) }.styled_err());+///+/// // Return a typed error for pattern matching+/// return Err(GitError::BranchAlreadyExists { branch: "main".into() }.into());+///+/// // Pattern match on errors+/// if let Some(GitError::BranchAlreadyExists { branch }) = err.downcast_ref() {+/// println!("Branch {} exists", branch);+/// }+/// ```+#[derive(Debug, Clone, thiserror::Error)]+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,+ /// Branch currently using this path, if known+ occupant: Option<String>,+ },++ /// 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>,+ error: String,+ },++ /// Failed to remove worktree+ #[error("failed to remove worktree for '{branch}'")]+ WorktreeRemovalFailed {+ branch: String,+ path: PathBuf,+ error: String,+ },++ /// Failed to delete branch+ #[error("failed to delete branch '{branch}'")]+ BranchDeletionFailed { branch: String, error: String },++ // -------------------------------------------------------------------------+ // 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+ commits_formatted: String,+ /// Whether this error occurred during a merge operation (affects hint message)+ in_merge_context: bool,+ },++ /// 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,+ /// The stderr output from the command+ error: String,+ },++ /// 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 {+ 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!(+ "{ERROR_EMOJI} {ERROR}{message}{ERROR:#}\n\n{HINT_EMOJI} {HINT}Switch to a branch first with 'git switch <branch>'{HINT:#}"+ )+ }++ GitError::UncommittedChanges { action } => {+ let message = match action {+ Some(action) => {+ format!("Cannot {action}: working tree has uncommitted changes")+ }+ None => "Working tree has uncommitted changes".to_string(),+ };+ format!(+ "{ERROR_EMOJI} {ERROR}{message}{ERROR:#}\n\n{HINT_EMOJI} {HINT}Commit or stash them first{HINT:#}"+ )+ }++ GitError::BranchAlreadyExists { branch } => {+ format!(+ "{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!(+ "{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!(+ "{ERROR_EMOJI} {ERROR}No worktree found for branch {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR:#}"+ )+ }++ GitError::WorktreePathOccupied {+ branch,+ path,+ occupant,+ } => {+ let occupant_note = occupant+ .as_ref()+ .map(|b| format!(" (currently on {HINT_BOLD}{b}{HINT_BOLD:#}{HINT})"))+ .unwrap_or_default();+ format!(+ "{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+ )+ }++ GitError::WorktreePathExists { path } => {+ format!(+ "{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)+ )+ }++ GitError::WorktreeCreationFailed {+ branch,+ base_branch,+ error,+ } => {+ let base_suffix = base_branch+ .as_ref()+ .map(|base| {+ format!("{ERROR} from base {ERROR_BOLD}{base}{ERROR_BOLD:#}{ERROR}")+ })+ .unwrap_or_default();+ let header = format!(+ "{ERROR_EMOJI} {ERROR}Failed to create worktree for {ERROR_BOLD}{branch}{ERROR_BOLD:#}{base_suffix}{ERROR:#}"+ );+ format_error_block(header, error)+ }++ GitError::WorktreeRemovalFailed {+ branch,+ path,+ error,+ } => {+ let header = format!(+ "{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)+ }++ GitError::BranchDeletionFailed { branch, error } => {+ let header = format!(+ "{ERROR_EMOJI} {ERROR}Failed to delete branch {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR:#}"+ );+ format_error_block(header, error)+ }++ GitError::ConflictingChanges {+ files,+ worktree_path,+ } => {+ let mut msg = format!(+ "{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));+ }+ msg.push_str(&format!(+ "\n{HINT_EMOJI} {HINT}Commit or stash these changes in {} first{HINT:#}",+ format_path_for_display(worktree_path)+ ));+ msg+ }++ GitError::NotFastForward {+ target_branch,+ commits_formatted,+ in_merge_context,+ } => {+ let mut msg = format!(+ "{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));+ }+ // Context-appropriate hint+ let hint = if *in_merge_context {+ "Run 'wt merge' again to incorporate these changes".to_string()+ } 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+ }++ GitError::MergeCommitsFound => {+ format!(+ "{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:#}"+ )+ }++ GitError::RebaseConflict {+ target_branch,+ git_output,+ } => {+ let mut msg = format!(+ "{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));+ } else {+ msg.push_str(&format!(+ "\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)+ }++ GitError::NotInteractive => {+ format!(+ "{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:#}"+ )+ }++ GitError::LlmCommandFailed { command, error } => {+ 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 block+ let 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+ }++ GitError::ParseError { message } | GitError::Other { message } => {+ format!("{ERROR_EMOJI} {ERROR}{message}{ERROR:#}")+ }+ }+ }++ /// Convert to anyhow::Error with styled message.+ ///+ /// This wraps the error with its styled representation for user display.+ pub fn styled_err(self) -> anyhow::Error {+ anyhow::anyhow!("{}", self.styled())+ }+}++/// 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 { .. }))+}+/// Semantic errors that require special handling in main.rs////// Most errors use anyhow::bail! with formatted messages. This enum is only@@ -90,187 +475,113 @@ fn format_error_block(header: String, error: &str) -> String {}}-/// Generic formatted error message-pub fn error_message(msg: impl std::fmt::Display) -> anyhow::Error {- anyhow::anyhow!("{ERROR_EMOJI} {ERROR}{msg}{ERROR:#}")-}--/// Parse error-pub fn parse_error(msg: impl std::fmt::Display) -> anyhow::Error {- anyhow::anyhow!("{ERROR_EMOJI} {ERROR}{msg}{ERROR:#}")-}--/// Detached HEAD error-///-/// `action` describes what was blocked (e.g., "merge")-pub fn detached_head(action: Option<&str>) -> anyhow::Error {- let message = match action {- Some(action) => format!("Cannot {action}: not on a branch (detached HEAD)"),- None => "Not on a branch (detached HEAD)".to_string(),- };- anyhow::anyhow!(- "{ERROR_EMOJI} {ERROR}{message}{ERROR:#}\n\n{HINT_EMOJI} {HINT}Switch to a branch first with 'git switch <branch>'{HINT:#}"- )-}--/// Uncommitted changes error-///-/// `action` describes what was blocked (e.g., "remove worktree")-pub fn uncommitted_changes(action: Option<&str>) -> anyhow::Error {- let message = match action {- Some(action) => format!("Cannot {action}: working tree has uncommitted changes"),- None => "Working tree has uncommitted changes".to_string(),- };- anyhow::anyhow!(- "{ERROR_EMOJI} {ERROR}{message}{ERROR:#}\n\n{HINT_EMOJI} {HINT}Commit or stash them first{HINT:#}"- )-}--/// Branch already exists error-pub fn branch_already_exists(branch: &str) -> anyhow::Error {- anyhow::anyhow!(- "{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:#}"- )-}--/// Worktree missing error-pub fn worktree_missing(branch: &str) -> anyhow::Error {- anyhow::anyhow!(- "{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:#}"- )-}--/// No worktree found error-pub fn no_worktree_found(branch: &str) -> anyhow::Error {- anyhow::anyhow!(- "{ERROR_EMOJI} {ERROR}No worktree found for branch {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR:#}"- )-}--/// Worktree path occupied error-pub fn worktree_path_occupied(branch: &str, path: &Path, occupant: Option<&str>) -> anyhow::Error {- let occupant_note = occupant- .map(|b| format!(" (currently on {HINT_BOLD}{b}{HINT_BOLD:#}{HINT})"))- .unwrap_or_default();- anyhow::anyhow!(- "{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- )-}+// =============================================================================+// Tests+// =============================================================================-/// Conflicting changes error-pub fn conflicting_changes(files: &[String], worktree_path: &Path) -> anyhow::Error {- let mut msg = format!(- "{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));+#[cfg(test)]+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");}- msg.push_str(&format!(- "\n{HINT_EMOJI} {HINT}Commit or stash these changes in {} first{HINT:#}",- format_path_for_display(worktree_path)- ));- anyhow::anyhow!("{}", msg)-}-/// Merge commits found error-pub fn merge_commits_found() -> anyhow::Error {- anyhow::anyhow!(- "{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:#}"- )-}--/// Not interactive error-pub fn not_interactive() -> anyhow::Error {- anyhow::anyhow!(- "{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:#}"- )-}--/// Push failed error-pub fn push_failed(error: &str) -> anyhow::Error {- let header = format!("{ERROR_EMOJI} {ERROR}Push failed{ERROR:#}");- anyhow::anyhow!("{}", format_error_block(header, error))-}+ #[test]+ fn test_git_error_styled_contains_emoji() {+ let err = GitError::DetachedHead { action: None };+ let styled = err.styled();+ assert!(styled.contains("❌")); // ERROR_EMOJI+ assert!(styled.contains("detached HEAD"));+ assert!(styled.contains("💡")); // HINT_EMOJI+ }-/// Rebase conflict error-pub fn rebase_conflict(target_branch: &str, git_output: &str) -> anyhow::Error {- let mut msg = format!(- "{ERROR_EMOJI} {ERROR}Rebase onto {ERROR_BOLD}{target_branch}{ERROR_BOLD:#}{ERROR} incomplete{ERROR:#}"- );+ #[test]+ fn test_git_error_styled_includes_action() {+ let err = GitError::DetachedHead {+ action: Some("push".into()),+ };+ let styled = err.styled();+ assert!(styled.contains("Cannot push"));++ let err = GitError::UncommittedChanges {+ action: Some("remove worktree".into()),+ };+ let styled = err.styled();+ assert!(styled.contains("Cannot remove worktree"));+ }- if !git_output.is_empty() {- msg.push('\n');- msg.push_str(&format_with_gutter(git_output, "", None));- } else {- msg.push_str(&format!(- "\n\n{HINT_EMOJI} {HINT}Resolve conflicts and run 'git rebase --continue'{HINT:#}\n{HINT_EMOJI} {HINT}Or abort with 'git rebase --abort'{HINT:#}"- ));+ #[test]+ fn test_git_error_styled_err_conversion() {+ // styled_err() wraps the styled message in anyhow::Error+ let err = GitError::BranchAlreadyExists {+ branch: "main".into(),+ }+ .styled_err();+ let msg = err.to_string();+ assert!(msg.contains("❌")); // Should be styled+ assert!(msg.contains("main"));+ assert!(msg.contains("already exists"));}- anyhow::anyhow!("{}", msg)-}+ #[test]+ fn test_pattern_matching_with_into() {+ // .into() preserves type for pattern matching+ let err: anyhow::Error = GitError::BranchAlreadyExists {+ branch: "main".into(),+ }+ .into();-/// Worktree path exists error-pub fn worktree_path_exists(path: &Path) -> anyhow::Error {- anyhow::anyhow!(- "{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)- )-}+ if let Some(GitError::BranchAlreadyExists { branch }) = err.downcast_ref::<GitError>() {+ assert_eq!(branch, "main");+ } else {+ panic!("Failed to downcast and pattern match");+ }+ }-/// Worktree creation failed error-pub fn worktree_creation_failed(- branch: &str,- base_branch: Option<&str>,- error: &str,-) -> anyhow::Error {- let base_suffix = base_branch- .map(|base| format!("{ERROR} from base {ERROR_BOLD}{base}{ERROR_BOLD:#}{ERROR}"))- .unwrap_or_default();-- let header = format!(- "{ERROR_EMOJI} {ERROR}Failed to create worktree for {ERROR_BOLD}{branch}{ERROR_BOLD:#}{base_suffix}{ERROR:#}"- );- anyhow::anyhow!("{}", format_error_block(header, error))-}+ #[test]+ fn test_styled_err_loses_type() {+ // styled_err() wraps as string, cannot be pattern matched+ let err = GitError::BranchAlreadyExists {+ branch: "feature".into(),+ }+ .styled_err();+ assert!(+ err.downcast_ref::<GitError>().is_none(),+ "styled_err() wraps as string, cannot be pattern matched"+ );+ }-/// Worktree removal failed error-pub fn worktree_removal_failed(branch: &str, path: &Path, error: &str) -> anyhow::Error {- let header = format!(- "{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)- );- anyhow::anyhow!("{}", format_error_block(header, error))-}+ #[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));-/// Branch deletion failed error-pub fn branch_deletion_failed(branch: &str, error: &str) -> anyhow::Error {- let header = format!(- "{ERROR_EMOJI} {ERROR}Failed to delete branch {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR:#}"- );- anyhow::anyhow!("{}", format_error_block(header, error))-}+ let err: anyhow::Error = GitError::BranchAlreadyExists {+ branch: "test".into(),+ }+ .into();+ assert!(!is_detached_head(&err));+ assert!(is_branch_already_exists(&err));+ }-/// LLM command failed error-///-/// `command` is the full command string (e.g., "llm --model claude")-/// `error` is the stderr output from the command-pub fn llm_command_failed(command: &str, error: &str) -> anyhow::Error {- 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 block- // Trim trailing newlines since output system adds one via println!- let 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());-- anyhow::anyhow!("{}", msg)+ #[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"));+ }}diff --git a/src/git/mod.rs b/src/git/mod.rsindex 41212a3eb..88d2356d4 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -31,11 +31,16 @@ static HEAVY_OPS_SEMAPHORE: LazyLock<semaphore::Semaphore> =// Re-exports from submodulespub use diff::{DiffStats, LineDiff};pub use error::{- WorktrunkError, branch_already_exists, branch_deletion_failed, conflicting_changes,- detached_head, error_message, exit_code, is_command_not_approved, llm_command_failed,- merge_commits_found, no_worktree_found, not_interactive, parse_error, push_failed,- rebase_conflict, uncommitted_changes, worktree_creation_failed, worktree_missing,- worktree_path_exists, worktree_path_occupied, worktree_removal_failed,+ // Typed error enum+ GitError,+ // Special-handling error enum+ WorktrunkError,+ // Error inspection functions+ exit_code,+ is_branch_already_exists,+ is_command_not_approved,+ is_detached_head,+ is_git_error,};pub use repository::{Repository, set_base_path};@@ -116,7 +121,10 @@ impl WorktreeList {let worktrees: Vec<_> = raw_worktrees.into_iter().filter(|wt| !wt.bare).collect();if worktrees.is_empty() {- return Err(error_message("No worktrees found"));+ return Err(GitError::Other {+ message: "No worktrees found".into(),+ }+ .styled_err());}Ok(Self { worktrees })diff --git a/src/git/parse.rs b/src/git/parse.rsindex a68add38e..576833e8b 100644--- a/src/git/parse.rs+++ b/src/git/parse.rs@@ -2,9 +2,7 @@use std::path::PathBuf;-use anyhow::bail;--use super::{Worktree, finalize_worktree, parse_error};+use super::{GitError, Worktree, finalize_worktree};impl Worktree {pub(crate) fn parse_porcelain_list(output: &str) -> anyhow::Result<Vec<Self>> {@@ -27,7 +25,10 @@ impl Worktree {match key {"worktree" => {let Some(path) = value else {- return Err(parse_error("worktree line missing path"));+ return Err(GitError::ParseError {+ message: "worktree line missing path".into(),+ }+ .styled_err());};current = Some(Worktree {path: PathBuf::from(path),@@ -42,14 +43,20 @@ impl Worktree {key => match (key, current.as_mut()) {("HEAD", Some(wt)) => {let Some(sha) = value else {- return Err(parse_error("HEAD line missing SHA"));+ return Err(GitError::ParseError {+ message: "HEAD line missing SHA".into(),+ }+ .styled_err());};wt.head = sha.to_string();}("branch", Some(wt)) => {// Strip refs/heads/ prefix if presentlet Some(branch_ref) = value else {- return Err(parse_error("branch line missing ref"));+ return Err(GitError::ParseError {+ message: "branch line missing ref".into(),+ }+ .styled_err());};let branch = branch_ref.strip_prefix("refs/heads/")@@ -97,10 +104,10 @@ impl DefaultBranchName {let branch = trimmed.strip_prefix(&prefix).unwrap_or(trimmed);if branch.is_empty() {- bail!(- "{}",- parse_error(format!("Empty branch name from {}/HEAD", remote))- );+ return Err(GitError::ParseError {+ message: format!("Empty branch name from {}/HEAD", remote),+ }+ .styled_err());}Ok(Self(branch.to_string()))@@ -118,10 +125,10 @@ impl DefaultBranchName {}).map(Self).ok_or_else(|| {- anyhow::anyhow!(- "{}",- parse_error("Could not find symbolic ref in ls-remote output")- )+ GitError::ParseError {+ message: "Could not find symbolic ref in ls-remote output".into(),+ }+ .styled_err()})}diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 8ece037db..09555a9ae 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -6,8 +6,8 @@ use anyhow::{Context, bail};// Import types and functions from parent module (mod.rs)use super::{- BranchCategory, CompletionBranch, DefaultBranchName, DiffStats, LineDiff, SwitchHistory,- Worktree, WorktreeList, detached_head, error_message, parse_error, uncommitted_changes,+ BranchCategory, CompletionBranch, DefaultBranchName, DiffStats, GitError, LineDiff,+ SwitchHistory, Worktree, WorktreeList,};/// Global base path for repository operations, set by -C flag@@ -99,7 +99,12 @@ impl Repository {} else {git_common_dir.parent()- .ok_or_else(|| anyhow::anyhow!("{}", error_message("Invalid git directory")))?+ .ok_or_else(|| {+ GitError::Other {+ message: "Invalid git directory".into(),+ }+ .styled_err()+ })?.to_path_buf()};@@ -182,8 +187,12 @@ impl Repository {////// `action` describes what requires being on a branch (e.g., "merge").pub fn require_current_branch(&self, action: &str) -> anyhow::Result<String> {- self.current_branch()?- .ok_or_else(|| detached_head(Some(action)))+ self.current_branch()?.ok_or_else(|| {+ GitError::DetachedHead {+ action: Some(action.into()),+ }+ .styled_err()+ })}/// Read a user-defined status from `worktrunk.status.<branch>` in git config.@@ -258,7 +267,10 @@ impl Repository {pub fn resolve_worktree_name(&self, name: &str) -> anyhow::Result<String> {match name {"@" => self.current_branch()?.ok_or_else(|| {- anyhow::anyhow!("{}", detached_head(Some("resolve '@' to current branch")))+ GitError::DetachedHead {+ action: Some("resolve '@' to current branch".into()),+ }+ .styled_err()}),"-" => {// Read from worktrunk.history (recorded by wt switch operations)@@ -266,9 +278,12 @@ impl Repository {self.get_switch_history().and_then(|h| h.previous).ok_or_else(|| {- anyhow::anyhow!("{}", error_message(- "No previous branch found in history. Use 'wt list' to see available worktrees.",- ))+ GitError::Other {+ message:+ "No previous branch found in history. Use 'wt list' to see available worktrees."+ .into(),+ }+ .styled_err()})}"^" => self.default_branch(),@@ -356,12 +371,12 @@ impl Repository {}// 4. Give up - can't infer- bail!(- "{}",- error_message(+ Err(GitError::Other {+ message:"Could not infer default branch. Please specify target branch explicitly or set up a remote."- )- )+ .into(),+ }+ .styled_err())}/// List all local branches.@@ -428,7 +443,10 @@ impl Repository {/// `action` describes what was blocked (e.g., "remove worktree").pub fn ensure_clean_working_tree(&self, action: Option<&str>) -> anyhow::Result<()> {if self.is_dirty()? {- return Err(uncommitted_changes(action));+ return Err(GitError::UncommittedChanges {+ action: action.map(String::from),+ }+ .styled_err());}Ok(())}@@ -465,10 +483,10 @@ impl Repository {let stdout = self.run_command(&["rev-list", "--count", &range])?;stdout.trim().parse().map_err(|e| {- anyhow::anyhow!(- "{}",- parse_error(format!("Failed to parse commit count: {}", e))- )+ GitError::ParseError {+ message: format!("Failed to parse commit count: {}", e),+ }+ .styled_err()})}@@ -490,10 +508,10 @@ impl Repository {pub fn commit_timestamp(&self, commit: &str) -> anyhow::Result<i64> {let stdout = self.run_command(&["show", "-s", "--format=%ct", commit])?;stdout.trim().parse().map_err(|e| {- anyhow::anyhow!(- "{}",- parse_error(format!("Failed to parse timestamp: {}", e))- )+ GitError::ParseError {+ message: format!("Failed to parse timestamp: {}", e),+ }+ .styled_err()})}@@ -577,7 +595,10 @@ impl Repository {// git rev-list --left-right outputs left (base) first, then right (head)let parts: Vec<&str> = output.trim().split('\t').collect();if parts.len() != 2 {- bail!("Unexpected rev-list output format: {}", output);+ return Err(crate::git::GitError::ParseError {+ message: format!("Unexpected rev-list output format: {}", output),+ }+ .styled_err());}let behind: usize = parts[0].parse().context("Failed to parse behind count")?;@@ -749,7 +770,10 @@ impl Repository {// Validate that we got a SHA backif backup_sha.is_empty() {- bail!("git stash create returned empty SHA - no changes to backup");+ return Err(crate::git::GitError::Other {+ message: "git stash create returned empty SHA - no changes to backup".into(),+ }+ .styled_err());}// Get current branch name to use in the ref name@@ -1006,7 +1030,10 @@ impl Repository {/// Remove a worktree at the specified path.pub fn remove_worktree(&self, path: &std::path::Path) -> anyhow::Result<()> {let path_str = path.to_str().ok_or_else(|| {- anyhow::anyhow!("{}", error_message("Invalid UTF-8 in worktree path"))+ GitError::Other {+ message: "Invalid UTF-8 in worktree path".into(),+ }+ .styled_err()})?;self.run_command(&["worktree", "remove", path_str])?;Ok(())@@ -1115,7 +1142,10 @@ impl Repository {.file_name().and_then(|name| name.to_str()).ok_or_else(|| {- anyhow::anyhow!("{}", error_message("Could not determine repository name"))+ GitError::Other {+ message: "Could not determine repository name".into(),+ }+ .styled_err()})?;Ok(repo_name.to_string())diff --git a/src/llm.rs b/src/llm.rsindex db02378a8..84a635a93 100644--- a/src/llm.rs+++ b/src/llm.rs@@ -2,7 +2,7 @@ use std::io::Write;use std::path::{Path, PathBuf};use std::process::{self, Stdio};use worktrunk::config::CommitGenerationConfig;-use worktrunk::git::{Repository, llm_command_failed};+use worktrunk::git::Repository;use worktrunk::path::format_path_for_display;use minijinja::Environment;@@ -118,7 +118,10 @@ fn execute_llm_command(command: &str, args: &[String], prompt: &str) -> anyhow::let message = String::from_utf8_lossy(&output.stdout).trim().to_owned();if message.is_empty() {- anyhow::bail!("LLM returned empty message");+ return Err(worktrunk::git::GitError::Other {+ message: "LLM returned empty message".into(),+ }+ .styled_err());}Ok(message)@@ -137,11 +140,14 @@ fn build_commit_prompt((None, Some(path)) => {let expanded_path = PathBuf::from(shellexpand::tilde(path).as_ref());std::fs::read_to_string(&expanded_path).map_err(|e| {- anyhow::anyhow!(- "Failed to read template-file '{}': {}",- format_path_for_display(&expanded_path),- e- )+ worktrunk::git::GitError::Other {+ message: format!(+ "Failed to read template-file '{}': {}",+ format_path_for_display(&expanded_path),+ e+ ),+ }+ .styled_err()})?}(None, None) => DEFAULT_TEMPLATE.to_string(),@@ -152,7 +158,10 @@ fn build_commit_prompt(// Validate non-emptyif template.trim().is_empty() {- anyhow::bail!("Template is empty");+ return Err(worktrunk::git::GitError::Other {+ message: "Template is empty".into(),+ }+ .styled_err());}// Render template with minijinja@@ -182,11 +191,14 @@ fn build_squash_prompt((None, Some(path)) => {let expanded_path = PathBuf::from(shellexpand::tilde(path).as_ref());std::fs::read_to_string(&expanded_path).map_err(|e| {- anyhow::anyhow!(- "Failed to read squash-template-file '{}': {}",- format_path_for_display(&expanded_path),- e- )+ worktrunk::git::GitError::Other {+ message: format!(+ "Failed to read squash-template-file '{}': {}",+ format_path_for_display(&expanded_path),+ e+ ),+ }+ .styled_err()})?}(None, None) => DEFAULT_SQUASH_TEMPLATE.to_string(),@@ -199,7 +211,10 @@ fn build_squash_prompt(// Validate non-emptyif template.trim().is_empty() {- anyhow::bail!("Squash template is empty");+ return Err(worktrunk::git::GitError::Other {+ message: "Squash template is empty".into(),+ }+ .styled_err());}// Render template with minijinja@@ -228,7 +243,11 @@ pub fn generate_commit_message(let args = &commit_generation_config.args;// Commit generation is explicitly configured - fail if it doesn't workreturn try_generate_commit_message(command, args, commit_generation_config).map_err(|e| {- llm_command_failed(&format_command_display(command, args), &e.to_string())+ worktrunk::git::GitError::LlmCommandFailed {+ command: format_command_display(command, args),+ error: e.to_string(),+ }+ .styled_err()});}@@ -322,7 +341,11 @@ pub fn generate_squash_message(let prompt =build_squash_prompt(commit_generation_config, target_branch, subjects, &context)?;return execute_llm_command(command, args, &prompt).map_err(|e| {- llm_command_failed(&format_command_display(command, args), &e.to_string())+ worktrunk::git::GitError::LlmCommandFailed {+ command: format_command_display(command, args),+ error: e.to_string(),+ }+ .styled_err()});}@@ -439,7 +462,12 @@ mod tests {};let result = build_commit_prompt(&config, "diff", None, &context);assert!(result.is_err());- assert_eq!(result.unwrap_err().to_string(), "Template is empty");+ assert!(+ result+ .unwrap_err()+ .to_string()+ .contains("Template is empty")+ );}#[test]@@ -556,7 +584,12 @@ mod tests {};let result = build_squash_prompt(&config, "main", &[], &context);assert!(result.is_err());- assert_eq!(result.unwrap_err().to_string(), "Squash template is empty");+ assert!(+ result+ .unwrap_err()+ .to_string()+ .contains("Squash template is empty")+ );}#[test]diff --git a/src/main.rs b/src/main.rsindex 8e1f8cebc..a2c33b70a 100644--- a/src/main.rs+++ b/src/main.rs@@ -299,7 +299,10 @@ fn main() {// Exit with error if no shells configuredif scan_result.configured.is_empty() {- return Err(anyhow::anyhow!("No shell config files found"));+ return Err(worktrunk::git::GitError::Other {+ message: "No shell config files found".into(),+ }+ .styled_err());}// Summary@@ -656,7 +659,10 @@ fn main() {} => (|| -> anyhow::Result<()> {// Validate conflicting flagsif !delete_branch && force_delete {- anyhow::bail!("Cannot use --force-delete with --no-delete-branch");+ return Err(worktrunk::git::GitError::Other {+ message: "Cannot use --force-delete with --no-delete-branch".into(),+ }+ .styled_err());}let repo = Repository::current();diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 17569237e..17f87414a 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -3,7 +3,7 @@use crate::commands::process::spawn_detached;use crate::commands::worktree::{RemoveResult, SwitchResult};use crate::output::global::format_switch_success;-use worktrunk::git::{branch_deletion_failed, worktree_removal_failed};+use worktrunk::git::GitError;use worktrunk::path::format_path_for_display;use worktrunk::shell::Shell;use worktrunk::styling::{@@ -284,7 +284,11 @@ fn handle_branch_only_output(}Err(e) => {if strict_branch_deletion {- anyhow::bail!("{}", branch_deletion_failed(branch_name, &e.to_string()));+ return Err(GitError::BranchDeletionFailed {+ branch: branch_name.into(),+ error: e.to_string(),+ }+ .styled_err());}// If branch deletion fails in non-strict mode, show a warning but don't error@@ -381,10 +385,12 @@ fn handle_removed_worktree_output(// Track whether branch was actually deleted (will be computed based on deletion attempt)if let Err(err) = repo.remove_worktree(worktree_path) {- anyhow::bail!(- "{}",- worktree_removal_failed(branch_name, worktree_path, &err.to_string())- );+ return Err(GitError::WorktreeRemovalFailed {+ branch: branch_name.into(),+ path: worktree_path.to_path_buf(),+ error: err.to_string(),+ }+ .styled_err());}// Delete the branch (unless --no-delete-branch was specified)@@ -418,7 +424,11 @@ fn handle_removed_worktree_output(Ok(_) => true,Err(e) => {if strict_branch_deletion {- anyhow::bail!("{}", branch_deletion_failed(branch_name, &e.to_string()));+ return Err(GitError::BranchDeletionFailed {+ branch: branch_name.into(),+ error: e.to_string(),+ }+ .styled_err());}// If branch deletion fails in non-strict mode, show a warning but don't error@@ -495,12 +505,20 @@ pub(crate) fn execute_streaming(// Add more VERGEN_* variables here if we expand build.rs and hit similar issues..env_remove("VERGEN_GIT_DESCRIBE").spawn()- .map_err(|e| anyhow::anyhow!("Failed to execute command: {}", e))?;+ .map_err(|e| {+ worktrunk::git::GitError::Other {+ message: format!("Failed to execute command: {}", e),+ }+ .styled_err()+ })?;// Wait for command to complete- let status = child- .wait()- .map_err(|e| anyhow::anyhow!("Failed to wait for command: {}", e))?;+ let status = child.wait().map_err(|e| {+ worktrunk::git::GitError::Other {+ message: format!("Failed to wait for command: {}", e),+ }+ .styled_err()+ })?;// Check if child was killed by a signal (Unix only)// This handles Ctrl-C: when SIGINT is sent, the child receives it and terminates,diff --git a/tests/git_error_display.rs b/tests/git_error_display.rsindex b5ecaae53..708544201 100644--- a/tests/git_error_display.rs+++ b/tests/git_error_display.rs@@ -1,22 +1,23 @@use insta::assert_snapshot;-use worktrunk::git::{push_failed, worktree_removal_failed};+use std::path::PathBuf;+use worktrunk::git::GitError;#[test]fn display_worktree_removal_failed() {- let msg = worktree_removal_failed(- "feature-x",- std::path::Path::new("/tmp/repo.feature-x"),- "fatal: worktree is dirty\nerror: could not remove worktree",- );+ let err = GitError::WorktreeRemovalFailed {+ branch: "feature-x".into(),+ path: PathBuf::from("/tmp/repo.feature-x"),+ error: "fatal: worktree is dirty\nerror: could not remove worktree".into(),+ };- assert_snapshot!("worktree_removal_failed", msg);+ assert_snapshot!("worktree_removal_failed", err.styled());}#[test]fn display_push_failed() {- let msg = push_failed(- "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'",- );+ let err = GitError::PushFailed {+ 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", msg);+ assert_snapshot!("push_failed", err.styled());}