Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(error): display failed commands in bash-highlighted gutter (#1001)
Maximilian Roos9282805b36e0
diff --git a/.claude/skills/writing-user-outputs/SKILL.md b/.claude/skills/writing-user-outputs/SKILL.mdindex 181e7bd0e..c2666902b 100644--- a/.claude/skills/writing-user-outputs/SKILL.md+++ b/.claude/skills/writing-user-outputs/SKILL.md@@ -346,13 +346,16 @@ naturally come after the action.| "Created new worktree for feature" | "Already on worktree for feature" || "Commands approved & saved" | "All commands already approved" |-**Hint vs Info:** Hints suggest user action. Info acknowledges what happened.--| Hint ↳ | Info ○ |-| ----------------------------------- | ------------------------------------- |-| "To continue, run `wt merge`" | "Already up to date with main" |-| "Commit or stash changes first" | "Skipping hooks (--no-verify)" |-| "Branch can be deleted" | "Worktree preserved (main worktree)" |+**Hint vs Info:** Hints suggest user action or provide additional non-essential+context (supplementary details the user doesn't need but may find useful). Info+acknowledges state without changing anything.++| Hint ↳ | Info ○ |+| ------------------------------------------------ | ------------------------------------- |+| "To continue, run `wt merge`" | "Already up to date with main" |+| "Commit or stash changes first" | "Skipping hooks (--no-verify)" |+| "Branch can be deleted" | "Worktree preserved (main worktree)" |+| "Failed command, exit code 128:" | |**Warning placement:** When something unexpected happens, warn somewhere. Wheredepends on the nature of the issue:diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 383bdb657..46ac83d3a 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -574,18 +574,15 @@ fn setup_fork_branch(// Create worktree (delayed streaming: silent if fast, shows progress if slow)// Use -- to prevent branch names starting with - from being interpreted as flagslet worktree_path_str = worktree_path.to_string_lossy();+ let git_args = ["worktree", "add", "--", worktree_path_str.as_ref(), branch];repo.run_command_delayed_stream(- &["worktree", "add", "--", worktree_path_str.as_ref(), branch],+ &git_args,Repository::SLOW_OPERATION_DELAY_MS,Some(progress_message(cformat!("Creating worktree for <bold>{}</>...", branch)).to_string(),),)- .map_err(|e| GitError::WorktreeCreationFailed {- branch: branch.to_string(),- base_branch: None,- error: e.to_string(),- })?;+ .map_err(|e| worktree_creation_error(&e, branch.to_string(), None))?;Ok(())}@@ -773,11 +770,11 @@ pub fn execute_switch(Repository::SLOW_OPERATION_DELAY_MS,progress_msg,) {- return Err(GitError::WorktreeCreationFailed {- branch: branch.clone(),- base_branch: base_branch.clone(),- error: e.to_string(),- }+ return Err(worktree_creation_error(+ &e,+ branch.clone(),+ base_branch.clone(),+ ).into());}@@ -924,3 +921,17 @@ pub fn execute_switch(}}}++fn worktree_creation_error(+ err: &anyhow::Error,+ branch: String,+ base_branch: Option<String>,+) -> GitError {+ let (output, command) = Repository::extract_failed_command(err);+ GitError::WorktreeCreationFailed {+ branch,+ base_branch,+ error: output,+ command,+ }+}diff --git a/src/git/error.rs b/src/git/error.rsindex ffef2e097..1a336bf10 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -18,8 +18,8 @@ use shell_escape::escape;use super::HookType;use crate::path::format_path_for_display;use crate::styling::{- ERROR_SYMBOL, HINT_SYMBOL, error_message, format_with_gutter, hint_message, info_message,- suggest_command,+ ERROR_SYMBOL, HINT_SYMBOL, error_message, format_bash_with_gutter, format_with_gutter,+ hint_message, info_message, suggest_command,};/// Platform-specific reference type (PR vs MR).@@ -93,6 +93,18 @@ pub trait RefContext {fn source_ref(&self) -> String;}+/// Information about a failed command, for display in error messages.+///+/// Separates the command string from exit information so Display impls+/// can style each part differently (bold command, gray exit code).+#[derive(Debug, Clone)]+pub struct FailedCommand {+ /// The full command string, e.g., "git worktree add /path -b fix main"+ pub command: String,+ /// Exit information, e.g., "exit code 255" or "killed by signal"+ pub exit_info: String,+}+/// Domain errors for git and worktree operations.////// This enum provides structured error data that can be pattern-matched and tested.@@ -163,6 +175,8 @@ pub enum GitError {branch: String,base_branch: Option<String>,error: String,+ /// The git command that failed, shown separately from git output+ command: Option<FailedCommand>,},WorktreeRemovalFailed {branch: String,@@ -441,6 +455,7 @@ impl std::fmt::Display for GitError {branch,base_branch,error,+ command,} => {let header = if let Some(base) = base_branch {error_message(cformat!(@@ -449,7 +464,19 @@ impl std::fmt::Display for GitError {} else {error_message(cformat!("Failed to create worktree for <bold>{branch}</>"))};- write!(f, "{}", format_error_block(header, error))+ write!(f, "{}", format_error_block(header, error))?;+ if let Some(cmd) = command {+ write!(+ f,+ "\n{}\n{}",+ hint_message(cformat!(+ "Failed command, <bright-black>{}</>:",+ cmd.exit_info+ )),+ format_bash_with_gutter(&cmd.command)+ )?;+ }+ Ok(())}GitError::WorktreeRemovalFailed {@@ -1150,6 +1177,7 @@ mod tests {branch: "feature".into(),base_branch: Some("main".into()),error: "git error".into(),+ command: None,};let display = err.to_string();assert!(display.contains("feature"));@@ -1161,9 +1189,26 @@ mod tests {branch: "feature".into(),base_branch: None,error: "git error".into(),+ command: None,};let display = err.to_string();assert!(display.contains("feature"));++ // With command info+ let err = GitError::WorktreeCreationFailed {+ branch: "feature".into(),+ base_branch: Some("main".into()),+ error: "fatal: ref exists".into(),+ command: Some(FailedCommand {+ command: "git worktree add /path -b feature main".into(),+ exit_info: "exit code 128".into(),+ }),+ };+ let display = err.to_string();+ assert!(display.contains("fatal: ref exists"));+ assert!(display.contains("worktree add"));+ assert!(display.contains("Failed command"));+ assert!(display.contains("exit code 128"));}#[test]diff --git a/src/git/mod.rs b/src/git/mod.rsindex 086036ad4..e5836ccc4 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -33,6 +33,8 @@ static HEAVY_OPS_SEMAPHORE: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::nepub(crate) use diff::DiffStats;pub use diff::{LineDiff, parse_numstat_line};pub use error::{+ // Structured command failure info+ FailedCommand,// Typed error enum (Display produces styled output)GitError,// Special-handling error enum (Display produces styled output)diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 1542baa29..789e0dcb4 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -56,6 +56,30 @@ pub use branch::Branch;pub use working_tree::WorkingTree;pub(super) use working_tree::path_to_logging_context;+/// Structured error from [`Repository::run_command_delayed_stream`].+///+/// Separates command output from command identity so callers can format+/// each part with appropriate styling (e.g., bold command, gray exit code).+#[derive(Debug)]+pub(crate) struct StreamCommandError {+ /// Lines of output from the command (may be empty)+ pub output: String,+ /// The command string, e.g., "git worktree add /path -b fix main"+ pub command: String,+ /// Exit information, e.g., "exit code 255" or "killed by signal"+ pub exit_info: String,+}++impl std::fmt::Display for StreamCommandError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ // Callers use Repository::extract_failed_command() to access fields directly.+ // This Display impl exists only to satisfy the Error trait bound.+ write!(f, "{}", self.output)+ }+}++impl std::error::Error for StreamCommandError {}+// ============================================================================// Repository Cache// ============================================================================@@ -655,11 +679,12 @@ impl Repository {.code().map(|c| format!("exit code {c}")).unwrap_or_else(|| "killed by signal".to_string());- if lines.is_empty() {- bail!("{cmd_str} failed ({exit_info})");- } else {- bail!("{}\n({cmd_str} failed, {exit_info})", lines.join("\n"));+ return Err(StreamCommandError {+ output: lines.join("\n"),+ command: cmd_str,+ exit_info,}+ .into());}Ok(None) => {// Still running - check if we should switch to streaming (skip if delay_ms < 0)@@ -696,6 +721,25 @@ impl Repository {.run().with_context(|| format!("Failed to execute: git {}", args.join(" ")))}++ /// Extract structured failure info from a [`Repository::run_command_delayed_stream`] error.+ ///+ /// Returns `(output, Some(FailedCommand))` if the error is a `StreamCommandError`,+ /// or `(error_string, None)` for other error types (e.g., spawn failures).+ pub fn extract_failed_command(+ err: &anyhow::Error,+ ) -> (String, Option<super::error::FailedCommand>) {+ match err.downcast_ref::<StreamCommandError>() {+ Some(e) => (+ e.output.clone(),+ Some(super::error::FailedCommand {+ command: e.command.clone(),+ exit_info: e.exit_info.clone(),+ }),+ ),+ None => (err.to_string(), None),+ }+ }}#[cfg(test)]diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rsindex 77bbdafc5..392bf5201 100644--- a/src/git/repository/tests.rs+++ b/src/git/repository/tests.rs@@ -399,3 +399,30 @@ fn test_default_branch_name_display() {assert_eq!(branch, expected);}}++#[test]+fn extract_failed_command_from_stream_error() {+ use super::StreamCommandError;++ let err: anyhow::Error = StreamCommandError {+ output: "fatal: ref exists".into(),+ command: "git worktree add /path".into(),+ exit_info: "exit code 128".into(),+ }+ .into();++ let (output, cmd) = super::Repository::extract_failed_command(&err);+ assert_eq!(output, "fatal: ref exists");+ let cmd = cmd.unwrap();+ assert_eq!(cmd.command, "git worktree add /path");+ assert_eq!(cmd.exit_info, "exit code 128");+}++#[test]+fn extract_failed_command_from_other_error() {+ let err = anyhow::anyhow!("some other error");++ let (output, cmd) = super::Repository::extract_failed_command(&err);+ assert_eq!(output, "some other error");+ assert!(cmd.is_none());+}diff --git a/tests/integration_tests/git_error_display.rs b/tests/integration_tests/git_error_display.rsindex 8d61baac7..6ea43182d 100644--- a/tests/integration_tests/git_error_display.rs+++ b/tests/integration_tests/git_error_display.rs@@ -1,6 +1,6 @@use insta::assert_snapshot;use std::path::PathBuf;-use worktrunk::git::{GitError, HookType, WorktrunkError, add_hook_skip_hint};+use worktrunk::git::{FailedCommand, GitError, HookType, WorktrunkError, add_hook_skip_hint};// ============================================================================// Worktree errors@@ -23,11 +23,28 @@ fn display_worktree_creation_failed() {branch: "feature-y".into(),base_branch: Some("main".into()),error: "fatal: '/tmp/repo.feature-y' already exists".into(),+ command: None,};assert_snapshot!("worktree_creation_failed", err.to_string());}+#[test]+fn display_worktree_creation_failed_with_command() {+ let err = GitError::WorktreeCreationFailed {+ branch: "fix".into(),+ base_branch: Some("main".into()),+ error: "Preparing worktree (new branch 'fix')\nfatal: cannot lock ref 'refs/heads/fix'"+ .into(),+ command: Some(FailedCommand {+ command: "git worktree add /tmp/repo.fix -b fix main".into(),+ exit_info: "exit code 128".into(),+ }),+ };++ assert_snapshot!("worktree_creation_failed_with_command", err.to_string());+}+#[test]fn display_worktree_missing() {let err = GitError::WorktreeMissing {diff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_creation_failed_with_command.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_creation_failed_with_command.snapnew file mode 100644index 000000000..e6cc9323c--- /dev/null+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_creation_failed_with_command.snap@@ -0,0 +1,9 @@+---+source: tests/integration_tests/git_error_display.rs+expression: err.to_string()+---+[31m✗[39m [31mFailed to create worktree for [1mfix[22m from base [1mmain[22m[39m+[107m [0m Preparing worktree (new branch 'fix')+[107m [0m fatal: cannot lock ref 'refs/heads/fix'+[2m↳[22m [2mFailed command, [90mexit code 128[39m:[22m+[107m [0m [2m[0m[2m[34mgit[0m[2m worktree add /tmp/repo.fix [0m[2m[36m-b[0m[2m fix main[0mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_dwim_ambiguous_remotes.snap b/tests/snapshots/integration__integration_tests__switch__switch_dwim_ambiguous_remotes.snapindex 0b0329284..9889e51ca 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_dwim_ambiguous_remotes.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_dwim_ambiguous_remotes.snap@@ -40,4 +40,5 @@ exit_code: 1----- stderr -----[31m✗[39m [31mFailed to create worktree for [1mshared-feature[22m[39m[107m [0m fatal: invalid reference: shared-feature-[107m [0m (git worktree add _REPO_.shared-feature shared-feature failed, exit code 128)+[2m↳[22m [2mFailed command, [90mexit code 128[39m:[22m+[107m [0m [2m[0m[2m[34mgit[0m[2m worktree add _REPO_.shared-feature shared-feature