Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: improve push error message formatting
Maximilian Roosa610cd73ce5d
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex dd7deb943..bfafb8dfc 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -192,7 +192,7 @@ impl RepositoryCliExt for Repository {let worktree_root = self.worktree_root()?;let current_branch = self.current_branch()?- .ok_or_else(|| GitError::CommandFailed("Not on a branch".to_string()))?;+ .ok_or_else(|| GitError::message("Not on a branch"))?;let worktrees = self.list_worktrees()?;let primary_worktree_dir = worktrees.worktrees[0].path.clone();diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 03b2ff31b..7dae6b999 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -202,9 +202,9 @@ pub fn handle_switch(let repo_name = repo_root.file_name()- .ok_or_else(|| GitError::CommandFailed("Invalid repository path".to_string()))?+ .ok_or_else(|| GitError::message("Invalid repository path"))?.to_str()- .ok_or_else(|| GitError::CommandFailed("Invalid UTF-8 in path".to_string()))?;+ .ok_or_else(|| GitError::message("Invalid UTF-8 in path"))?;let worktree_path = repo_root.join(config.format_path(repo_name, &resolved_branch));@@ -575,6 +575,7 @@ pub fn handle_push(if let Some(stash) = target_worktree_stash.take() {stash.restore()?;}+ // CommandFailed contains raw git output, wrap in PushFailed for proper formattingreturn Err(GitError::PushFailed {error: e.to_string(),});diff --git a/src/git/error.rs b/src/git/error.rsindex 32f21fac7..4a8c5fc96 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -74,21 +74,26 @@ pub enum GitError {BranchDeletionFailed { branch: String, error: String },}+impl GitError {+ /// Create a formatted user-facing error message with emoji and styling.+ ///+ /// Use this for application errors (not raw git output).+ /// For raw git stderr, use `CommandFailed` directly.+ pub fn message(msg: impl Into<String>) -> Self {+ use crate::styling::{ERROR, ERROR_EMOJI};+ let msg = msg.into();+ GitError::CommandFailed(format!("{ERROR_EMOJI} {ERROR}{msg}{ERROR:#}"))+ }+}+impl std::fmt::Display for GitError {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {use crate::styling::{ERROR, ERROR_BOLD, ERROR_EMOJI, HINT, HINT_EMOJI};match self {- // Generic error - format with emoji and styling- // Skip formatting if message already contains ANSI codes (from nested error formatting)- GitError::CommandFailed(msg) => {- if msg.contains("\x1b[") || msg.contains("[31m") || msg.contains("[0m") {- // Already formatted, just pass through- write!(f, "{}", msg)- } else {- write!(f, "{ERROR_EMOJI} {ERROR}{msg}{ERROR:#}")- }- }+ // Generic error - raw passthrough, no formatting+ // Specific error variants should be used for git command failures that need formatting+ GitError::CommandFailed(msg) => write!(f, "{}", msg),// ParseError messages need formattingGitError::ParseError(msg) => {@@ -232,7 +237,8 @@ impl std::fmt::Display for GitError {// Push failedGitError::PushFailed { error } => {- write!(f, "{ERROR_EMOJI} {ERROR}Push failed: {error}{ERROR:#}")+ let header = format!("{ERROR_EMOJI} {ERROR}Push failed{ERROR:#}");+ write!(f, "{}", format_error_block(header, error))}// Rebase conflictdiff --git a/src/git/mod.rs b/src/git/mod.rsindex a79395cb7..afe78aa55 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -64,7 +64,7 @@ impl WorktreeList {let worktrees: Vec<_> = raw_worktrees.into_iter().filter(|wt| !wt.bare).collect();if worktrees.is_empty() {- return Err(GitError::CommandFailed("No worktrees found".to_string()));+ return Err(GitError::message("No worktrees found"));}Ok(Self { worktrees })diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 25912575b..4f3b52bbb 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -39,11 +39,19 @@ pub trait GitResultExt<T> {impl<T, E: std::fmt::Display> GitResultExt<T> for Result<T, E> {fn git_context(self, context: &str) -> Result<T, GitError> {- self.map_err(|e| GitError::CommandFailed(format!("{}: {}", context, e)))+ use crate::styling::{ERROR, ERROR_EMOJI, format_with_gutter};+ self.map_err(|e| {+ let error_str = e.to_string();+ let header = format!("{ERROR_EMOJI} {ERROR}{context}{ERROR:#}");+ // External errors always use gutter formatting (canonical path)+ let formatted = format!("{}\n\n{}", header, format_with_gutter(&error_str, "", None));+ GitError::CommandFailed(formatted)+ })}fn git_err(self) -> Result<T, GitError> {- self.map_err(|e| GitError::CommandFailed(e.to_string()))+ use crate::styling::{ERROR, ERROR_EMOJI};+ self.map_err(|e| GitError::CommandFailed(format!("{ERROR_EMOJI} {ERROR}{e}{ERROR:#}")))}}@@ -116,7 +124,7 @@ impl Repository {} else {git_common_dir.parent()- .ok_or_else(|| GitError::CommandFailed("Invalid git directory".to_string()))?+ .ok_or_else(|| GitError::message("Invalid git directory"))?.to_path_buf()};@@ -239,8 +247,8 @@ impl Repository {let output = self.run_command(&["rev-parse", "--abbrev-ref", "@{-1}"]).map_err(|_| {- GitError::CommandFailed(- "No previous branch found in reflog. Use 'wt list' to see available worktrees.".to_string(),+ GitError::message(+ "No previous branch found in reflog. Use 'wt list' to see available worktrees.")})?;Ok(output.trim().to_string())@@ -673,7 +681,7 @@ impl Repository {pub fn remove_worktree(&self, path: &std::path::Path) -> Result<(), GitError> {let path_str = path.to_str()- .ok_or_else(|| GitError::CommandFailed("Invalid UTF-8 in worktree path".to_string()))?;+ .ok_or_else(|| GitError::message("Invalid UTF-8 in worktree path"))?;self.run_command(&["worktree", "remove", path_str])?;Ok(())}@@ -769,9 +777,7 @@ impl Repository {let repo_name = repo_root.file_name().and_then(|name| name.to_str())- .ok_or_else(|| {- GitError::CommandFailed("Could not determine repository name".to_string())- })?;+ .ok_or_else(|| GitError::message("Could not determine repository name"))?;Ok(repo_name.to_string())}diff --git a/tests/git_error_display.rs b/tests/git_error_display.rsindex 6c8a7d012..eea36200c 100644--- a/tests/git_error_display.rs+++ b/tests/git_error_display.rs@@ -11,3 +11,13 @@ fn display_worktree_removal_failed() {assert_snapshot!("worktree_removal_failed", err.to_string());}++#[test]+fn display_push_failed() {+ 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'"+ .to_string(),+ };++ assert_snapshot!("push_failed", err.to_string());+}diff --git a/tests/snapshots/git_error_display__push_failed.snap b/tests/snapshots/git_error_display__push_failed.snapnew file mode 100644index 000000000..77c73ccf2--- /dev/null+++ b/tests/snapshots/git_error_display__push_failed.snap@@ -0,0 +1,9 @@+---+source: tests/git_error_display.rs+expression: err.to_string()+---+❌ [31mPush failed[0m++[40m [0m To /Users/user/workspace/repo/.git+[40m [0m ! [remote rejected] HEAD -> main (Up-to-date check failed)+[40m [0m error: failed to push some refs to '/Users/user/workspace/repo/.git'diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snap b/tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snapindex 4e539e260..a481bcdee 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snap@@ -17,16 +17,17 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpqAffJF/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpaewYd9/test-config.toml---success: falseexit_code: 1----- stdout ---------- stderr ------❌ [31mFailed to load project config: Failed to parse TOML: TOML parse error at line 1, column 39- |-1 | post-create-command = [invalid syntax- | ^-unclosed array, expected `]`-[0m+❌ [31mFailed to load project config[0m++[40m [0m Failed to parse TOML: TOML parse error at line 1, column 39+[40m [0m |+[40m [0m 1 | post-create-command = [invalid syntax+[40m [0m | ^+[40m [0m unclosed array, expected `]`diff --git a/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_no_history.snap b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_no_history.snapindex 8247ea281..a63287722 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_no_history.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_previous_branch_no_history.snap@@ -16,7 +16,7 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpqoKTZ5/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpnq1lig/test-config.toml---success: falseexit_code: 1