Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(git): Add detailed GitError variants
Maximilian Roos89f6ffba193c
diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 5109ba6ef..9380f62ec 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -1,6 +1,6 @@use worktrunk::HookType;use worktrunk::config::{Command, CommandPhase, ProjectConfig};-use worktrunk::git::{GitError, GitResultExt, Repository};+use worktrunk::git::{GitError, Repository};use worktrunk::styling::{CYAN, CYAN_BOLD, ERROR, ERROR_EMOJI, GREEN_BOLD, HINT, HINT_EMOJI};use super::command_approval::approve_command_batch;@@ -181,9 +181,15 @@ pub fn handle_merge(crate::output::progress(format!("{CYAN}Switching to {CYAN_BOLD}{target_branch}{CYAN_BOLD:#}{CYAN}...{CYAN:#}"))?;- primary_repo- .run_command(&["switch", &target_branch])- .git_context(&format!("Failed to switch to '{}'", target_branch))?;+ if let Err(err) = primary_repo.run_command(&["switch", &target_branch]) {+ return Err(match err {+ GitError::CommandFailed(msg) => GitError::SwitchFailed {+ branch: target_branch.clone(),+ error: msg,+ },+ other => other,+ });+ }}// STEP 3: Remove worktree via shared remove output handler so final message matches wt removediff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 32632256e..c3e9e1fbd 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -261,7 +261,14 @@ pub fn handle_switch(}}// Fall back to generic error with context- return Err(e).git_context("Failed to create worktree");+ return Err(match e {+ GitError::CommandFailed(msg) => GitError::WorktreeCreationFailed {+ branch: resolved_branch.clone(),+ base_branch: base_for_creation.clone(),+ error: msg,+ },+ other => other,+ });}// Canonicalize the path to resolve any .. components@@ -371,8 +378,15 @@ fn remove_current_worktree(}// Switch to default branch- repo.run_command(&["switch", &default_branch])- .git_context(&format!("Failed to switch to '{}'", default_branch))?;+ if let Err(err) = repo.run_command(&["switch", &default_branch]) {+ return Err(match err {+ GitError::CommandFailed(msg) => GitError::SwitchFailed {+ branch: default_branch.clone(),+ error: msg,+ },+ other => other,+ });+ }Ok(RemoveResult::SwitchedToDefault(default_branch))}diff --git a/src/git/error.rs b/src/git/error.rsindex 1ce08d697..ebd2e871b 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -56,6 +56,22 @@ pub enum GitError {},/// Worktree path already exists on filesystemWorktreePathExists { path: PathBuf },+ /// Creating a worktree failed+ WorktreeCreationFailed {+ branch: String,+ base_branch: Option<String>,+ error: String,+ },+ /// Switching branches failed+ SwitchFailed { branch: String, error: String },+ /// Removing a worktree directory failed+ WorktreeRemovalFailed {+ branch: String,+ path: PathBuf,+ error: String,+ },+ /// Deleting a branch failed+ BranchDeletionFailed { branch: String, error: String },}impl std::fmt::Display for GitError {@@ -254,10 +270,62 @@ impl std::fmt::Display for GitError {path.display())}++ GitError::WorktreeCreationFailed {+ branch,+ base_branch,+ error,+ } => {+ let header = match base_branch {+ Some(base) => format!(+ "{ERROR_EMOJI} {ERROR}Failed to create worktree for {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR} from base {ERROR_BOLD}{base}{ERROR_BOLD:#}{ERROR:#}"+ ),+ None => format!(+ "{ERROR_EMOJI} {ERROR}Failed to create worktree for {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR:#}"+ ),+ };+ write!(f, "{}", format_error_block(header, error))+ }++ GitError::SwitchFailed { branch, error } => {+ let header = format!(+ "{ERROR_EMOJI} {ERROR}Failed to switch to {ERROR_BOLD}{branch}{ERROR_BOLD:#}{ERROR:#}"+ );+ write!(f, "{}", 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:#}",+ path.display()+ );+ write!(f, "{}", 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:#}"+ );+ write!(f, "{}", format_error_block(header, error))+ }}}}+fn format_error_block(header: String, error: &str) -> String {+ use crate::styling::format_with_gutter;+ let trimmed = error.trim();+ if trimmed.is_empty() {+ header+ } else {+ format!("{header}\n\n{}", format_with_gutter(trimmed, "", None))+ }+}+impl std::error::Error for GitError {}// Automatic conversion from io::Error to GitErrordiff --git a/src/output/handlers.rs b/src/output/handlers.rsindex a601d9e85..4d84f7166 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -2,7 +2,8 @@use crate::commands::worktree::{RemoveResult, SwitchResult};use crate::output::global::format_switch_success;-use worktrunk::git::{GitError, GitResultExt};+use worktrunk::git::GitError;+use worktrunk::styling::{GREEN, GREEN_BOLD, WARNING, WARNING_BOLD, format_with_gutter};/// Format message for switch operation (mode-specific via output system)fn format_switch_message(result: &SwitchResult, branch: &str) -> String {@@ -30,8 +31,6 @@ fn format_remove_message(branch: Option<&str>,branch_deleted: bool,) -> String {- use worktrunk::styling::{GREEN, GREEN_BOLD};-match result {RemoveResult::AlreadyOnDefault(branch) => {format!("{GREEN}Already on default branch {GREEN_BOLD}{branch}{GREEN_BOLD:#}{GREEN:#}")@@ -144,8 +143,16 @@ pub fn handle_remove_output(// 2. Do the deletion (shell already changed directory if needed)// Progress message already shown at start of handle_remove()let repo = worktrunk::git::Repository::current();- repo.remove_worktree(worktree_path)- .git_context("Failed to remove worktree")?;+ if let Err(err) = repo.remove_worktree(worktree_path) {+ return Err(match err {+ GitError::CommandFailed(msg) => GitError::WorktreeRemovalFailed {+ branch: branch_name.clone(),+ path: worktree_path.clone(),+ error: msg,+ },+ other => other,+ });+ }// 3. Delete the branch (unless --no-delete-branch was specified)// Returns true if branch was successfully deleted, false otherwise@@ -160,14 +167,16 @@ pub fn handle_remove_output(Ok(_) => true,Err(e) => {if strict_branch_deletion {- return Err(GitError::CommandFailed(format!(- "Failed to delete branch '{branch_name}': {e}"- )));+ return Err(match e {+ GitError::CommandFailed(msg) => GitError::BranchDeletionFailed {+ branch: branch_name.clone(),+ error: msg,+ },+ other => other,+ });}// If branch deletion fails in non-strict mode, show a warning but don't error- use worktrunk::styling::{WARNING, WARNING_BOLD, format_with_gutter};-// Show the warning message with branch namesuper::warning(format!("{WARNING}Could not delete branch {WARNING_BOLD}{branch_name}{WARNING_BOLD:#}{WARNING:#}"diff --git a/tests/git_error_display.rs b/tests/git_error_display.rsnew file mode 100644index 000000000..6c8a7d012--- /dev/null+++ b/tests/git_error_display.rs@@ -0,0 +1,13 @@+use insta::assert_snapshot;+use worktrunk::git::GitError;++#[test]+fn display_worktree_removal_failed() {+ let err = GitError::WorktreeRemovalFailed {+ branch: "feature-x".to_string(),+ path: std::path::PathBuf::from("/tmp/repo.feature-x"),+ error: "fatal: worktree is dirty\nerror: could not remove worktree".to_string(),+ };++ assert_snapshot!("worktree_removal_failed", err.to_string());+}diff --git a/tests/integration_tests/directives.rs b/tests/integration_tests/directives.rsindex 8ff2a6ee6..dfb616a00 100644--- a/tests/integration_tests/directives.rs+++ b/tests/integration_tests/directives.rs@@ -29,8 +29,9 @@ fn test_switch_internal_directive() {----- stdout ---------- stderr ------ Failed to create worktree: β [31mfatal: invalid reference: my-feature- [0m+ β [31mFailed to create worktree for [1m[31mmy-feature[0m[0m++ [40m [0m fatal: invalid reference: my-feature");});}@@ -57,8 +58,9 @@ fn test_switch_without_internal() {----- stdout ---------- stderr ------ Failed to create worktree: β [31mfatal: invalid reference: my-feature- [0m+ β [31mFailed to create worktree for [1m[31mmy-feature[0m[0m++ [40m [0m fatal: invalid reference: my-feature");});}diff --git a/tests/snapshots/git_error_display__worktree_removal_failed.snap b/tests/snapshots/git_error_display__worktree_removal_failed.snapnew file mode 100644index 000000000..6ce69c2d5--- /dev/null+++ b/tests/snapshots/git_error_display__worktree_removal_failed.snap@@ -0,0 +1,9 @@+---+source: tests/git_error_display.rs+assertion_line: 12+expression: err.to_string()+---+β [31mFailed to remove worktree for [1m[31mfeature-x[0m[31m at [1m[31m/tmp/repo.feature-x[0m[0m++[40m [0m fatal: worktree is dirty+[40m [0m error: could not remove worktreediff --git a/tests/snapshots/integration__integration_tests__merge__merge_primary_on_different_branch_dirty.snap b/tests/snapshots/integration__integration_tests__merge__merge_primary_on_different_branch_dirty.snapindex 2c76a41e7..ef95fb38e 100644--- a/tests/snapshots/integration__integration_tests__merge__merge_primary_on_different_branch_dirty.snap+++ b/tests/snapshots/integration__integration_tests__merge__merge_primary_on_different_branch_dirty.snap@@ -1,5 +1,6 @@---source: tests/integration_tests/merge.rs+assertion_line: 11info:program: wtargs:@@ -15,7 +16,7 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp2Zehen/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpEnmt5J/test-config.toml---success: falseexit_code: 1@@ -31,8 +32,9 @@ exit_code: 1π [36mSwitching to [1m[36mmain[0m[36m...[0m----- stderr ------Failed to switch to 'main': β [31merror: Your local changes to the following files would be overwritten by checkout:- file.txt-Please commit your changes or stash them before you switch branches.-Aborting-[0m+β [31mFailed to switch to [1m[31mmain[0m[0m++[40m [0m error: Your local changes to the following files would be overwritten by checkout:+[40m [0m file.txt+[40m [0m Please commit your changes or stash them before you switch branches.+[40m [0m Abortingdiff --git a/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snap b/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snapindex 50473c94c..d84eb5a31 100644--- a/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snap+++ b/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snap@@ -24,5 +24,6 @@ exit_code: 1----- stdout ---------- stderr ------Failed to create worktree: β [31mfatal: invalid reference: __WORKTRUNK_EXEC__echo PWNED > /tmp/hacked6-[0m+β [31mFailed to create worktree for [1m[31m__WORKTRUNK_EXEC__echo PWNED > /tmp/hacked6[0m[0m++[40m [0m fatal: invalid reference: __WORKTRUNK_EXEC__echo PWNED > /tmp/hacked6