Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Wrap hook errors with --no-verify hint for applicable commands
Maximilian Roos4a89748fa0fc
diff --git a/src/commands/commit.rs b/src/commands/commit.rsindex 5f62a4f8d..e3dc224f5 100644--- a/src/commands/commit.rs+++ b/src/commands/commit.rs@@ -169,19 +169,23 @@ impl CommitOptions<'_> {// Run user pre-commit hooks first (no approval required)if let Some(user_config) = &self.ctx.config.pre_commit {- pipeline.run_sequential(- user_config,- HookType::PreCommit,- HookSource::User,- &extra_vars,- HookFailureStrategy::FailFast,- None,- )?;+ pipeline+ .run_sequential(+ user_config,+ HookType::PreCommit,+ HookSource::User,+ &extra_vars,+ HookFailureStrategy::FailFast,+ None,+ )+ .map_err(worktrunk::git::add_hook_skip_hint)?;}// Then run project pre-commit hooks (require approval)if let Some(ref config) = project_config {- pipeline.run_pre_commit(config, self.target_branch, None)?;+ pipeline+ .run_pre_commit(config, self.target_branch, None)+ .map_err(worktrunk::git::add_hook_skip_hint)?;}}diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex d20c561f2..40917da36 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -285,6 +285,7 @@ pub fn run_pre_merge_commands(HookFailureStrategy::FailFast,name_filter,)+ .map_err(worktrunk::git::add_hook_skip_hint)}/// Execute post-merge commands sequentially in the main worktree (blocking)@@ -308,6 +309,7 @@ pub fn execute_post_merge_commands(HookFailureStrategy::Warn,name_filter,)+ .map_err(worktrunk::git::add_hook_skip_hint)}/// Execute pre-remove commands sequentially in the worktree (blocking)@@ -330,4 +332,5 @@ pub fn execute_pre_remove_commands(HookFailureStrategy::FailFast,name_filter,)+ .map_err(worktrunk::git::add_hook_skip_hint)}diff --git a/src/commands/standalone.rs b/src/commands/standalone.rsindex 50694e310..96bf0cd86 100644--- a/src/commands/standalone.rs+++ b/src/commands/standalone.rs@@ -247,19 +247,23 @@ pub fn handle_squash(// Run user pre-commit hooks first (unless skipped)if !skip_pre_commit && let Some(user_config) = &ctx.config.pre_commit {use super::hooks::{HookFailureStrategy, HookSource};- pipeline.run_sequential(- user_config,- HookType::PreCommit,- HookSource::User,- &extra_vars,- HookFailureStrategy::FailFast,- None,- )?;+ pipeline+ .run_sequential(+ user_config,+ HookType::PreCommit,+ HookSource::User,+ &extra_vars,+ HookFailureStrategy::FailFast,+ None,+ )+ .map_err(worktrunk::git::add_hook_skip_hint)?;}// Then run project pre-commit hooks (unless skipped)if !skip_pre_commit && let Some(ref config) = project_config {- pipeline.run_pre_commit(config, Some(&target_branch), None)?;+ pipeline+ .run_pre_commit(config, Some(&target_branch), None)+ .map_err(worktrunk::git::add_hook_skip_hint)?;}// Get merge base with target branchdiff --git a/src/git/error.rs b/src/git/error.rsindex 3fb17c828..0ffa5b7a4 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -514,21 +514,22 @@ impl std::fmt::Display for WorktrunkError {error,..} => {- let err_msg = if let Some(name) = command_name {- error_message(cformat!(- "{hook_type} command failed: <bold>{name}</>: {error}"- ))+ // Note: Callers that support --no-verify should add the hint themselves+ if let Some(name) = command_name {+ write!(+ f,+ "{}",+ error_message(cformat!(+ "{hook_type} command failed: <bold>{name}</>: {error}"+ ))+ )} else {- error_message(format!("{hook_type} command failed: {error}"))- };- write!(- f,- "{}\n\n{}",- err_msg,- hint_message(cformat!(- "Use <bright-black>--no-verify</> to skip {hook_type} commands"- ))- )+ write!(+ f,+ "{}",+ error_message(format!("{hook_type} command failed: {error}"))+ )+ }}WorktrunkError::CommandNotApproved => {Ok(()) // on_skip callback handles the printing@@ -544,6 +545,10 @@ impl std::error::Error for WorktrunkError {}/// Extract exit code from WorktrunkError, if applicablepub fn exit_code(err: &anyhow::Error) -> Option<i32> {+ // Check for wrapped HookErrorWithHint first+ if let Some(wrapper) = err.downcast_ref::<HookErrorWithHint>() {+ return exit_code(&wrapper.inner);+ }err.downcast_ref::<WorktrunkError>().and_then(|e| match e {WorktrunkError::ChildProcessExited { code, .. } => Some(*code),WorktrunkError::HookCommandFailed { exit_code, .. } => *exit_code,@@ -558,6 +563,68 @@ pub fn is_command_not_approved(err: &anyhow::Error) -> bool {.is_some_and(|e| matches!(e, WorktrunkError::CommandNotApproved))}+/// If the error is a HookCommandFailed, wrap it to add a hint about using --no-verify.+///+/// ## When to use+///+/// Use this for commands where a hook runs as a side effect of the user's intent:+/// - `wt merge` - user wants to merge, hooks run as part of that+/// - `wt commit` - user wants to commit, pre-commit hooks run+/// - `wt switch --create` - user wants a worktree, post-create hooks run+///+/// ## When NOT to use+///+/// Don't use for `wt hook <type>` - the user explicitly asked to run hooks,+/// so suggesting `--no-verify` makes no sense.+pub fn add_hook_skip_hint(err: anyhow::Error) -> anyhow::Error {+ // Extract hook_type first (if applicable), then decide whether to wrap+ let hook_type = err+ .downcast_ref::<WorktrunkError>()+ .and_then(|wt_err| match wt_err {+ WorktrunkError::HookCommandFailed { hook_type, .. } => Some(*hook_type),+ _ => None,+ });++ match hook_type {+ Some(hook_type) => HookErrorWithHint {+ inner: err,+ hook_type,+ }+ .into(),+ None => err,+ }+}++/// Wrapper that displays a HookCommandFailed error with the --no-verify hint.+/// Created by `add_hook_skip_hint()` for commands that support `--no-verify`.+#[derive(Debug)]+pub struct HookErrorWithHint {+ inner: anyhow::Error,+ hook_type: HookType,+}++impl std::fmt::Display for HookErrorWithHint {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ // Display the original error (always HookCommandFailed - validated by add_hook_skip_hint)+ write!(f, "{}", self.inner)?;+ // Add the hint+ write!(+ f,+ "\n\n{}",+ hint_message(cformat!(+ "Use <bright-black>--no-verify</> to skip {} commands",+ self.hook_type+ ))+ )+ }+}++impl std::error::Error for HookErrorWithHint {+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {+ self.inner.source()+ }+}+/// Format an error with header and gutter contentfn format_error_block(header: String, error: &str) -> String {let trimmed = error.trim();diff --git a/src/git/mod.rs b/src/git/mod.rsindex 85b27e541..c312d8189 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -34,8 +34,10 @@ pub use error::{// Typed error enum (Display produces styled output)GitError,// Special-handling error enum (Display produces styled output)+ HookErrorWithHint,WorktrunkError,// Error inspection functions+ add_hook_skip_hint,exit_code,is_command_not_approved,};diff --git a/src/main.rs b/src/main.rsindex 4b24b654d..fc620c776 100644--- a/src/main.rs+++ b/src/main.rs@@ -1311,11 +1311,13 @@ fn main() {if let Err(e) = result {use worktrunk::styling::ERROR_EMOJI;- // GitError and WorktrunkError produce styled output via Display+ // GitError, WorktrunkError, and HookErrorWithHint produce styled output via Displayif let Some(err) = e.downcast_ref::<worktrunk::git::GitError>() {let _ = output::print(err.to_string());} else if let Some(err) = e.downcast_ref::<worktrunk::git::WorktrunkError>() {let _ = output::print(err.to_string());+ } else if let Some(err) = e.downcast_ref::<worktrunk::git::HookErrorWithHint>() {+ let _ = output::print(err.to_string());} else {// Anyhow error - format with emoji, multi-line root cause gets gutterlet msg = e.to_string();diff --git a/tests/integration_tests/git_error_display.rs b/tests/integration_tests/git_error_display.rsindex 9baf48050..d8cfb9d65 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};+use worktrunk::git::{GitError, HookType, WorktrunkError, add_hook_skip_hint};// ============================================================================// Worktree errors@@ -290,6 +290,27 @@ fn display_hook_command_failed_without_name() {assert_snapshot!("hook_command_failed_without_name", err.to_string());}+/// Test error display for commands that support --no-verify (merge, commit, etc.)+/// Shows the complete error with hint, as users would see it.+#[test]+fn display_hook_command_failed_with_skip_hint() {+ let err: anyhow::Error = WorktrunkError::HookCommandFailed {+ hook_type: HookType::PreMerge,+ command_name: Some("test".into()),+ error: "exit code 1".into(),+ exit_code: Some(1),+ }+ .into();++ // Wrap with hint (as done by commands supporting --no-verify)+ let err_with_hint = add_hook_skip_hint(err);++ assert_snapshot!(+ "hook_command_failed_with_skip_hint",+ err_with_hint.to_string()+ );+}+// ============================================================================// Integration test: verify error message includes command when git unavailable// ============================================================================diff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__hook_command_failed_with_name.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__hook_command_failed_with_name.snapindex 3e07ec863..9b7b8b37e 100644--- a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__hook_command_failed_with_name.snap+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__hook_command_failed_with_name.snap@@ -1,7 +1,5 @@----source: tests/git_error_display.rs+source: tests/integration_tests/git_error_display.rsexpression: err.to_string()---β [31mpre-merge command failed: [1mtest[22m: exit code 1[39m--π‘ [2mUse [90m--no-verify[39m to skip pre-merge commands[22mdiff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__hook_command_failed_with_skip_hint.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__hook_command_failed_with_skip_hint.snapnew file mode 100644index 000000000..ff34eb921--- /dev/null+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__hook_command_failed_with_skip_hint.snap@@ -0,0 +1,7 @@+---+source: tests/integration_tests/git_error_display.rs+expression: err_with_hint.to_string()+---+β [31mpre-merge command failed: [1mtest[22m: exit code 1[39m++π‘ [2mUse [90m--no-verify[39m to skip pre-merge commands[22mdiff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__hook_command_failed_without_name.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__hook_command_failed_without_name.snapindex 56d3d7763..e7fbb7407 100644--- a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__hook_command_failed_without_name.snap+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__hook_command_failed_without_name.snap@@ -1,7 +1,5 @@----source: tests/git_error_display.rs+source: tests/integration_tests/git_error_display.rsexpression: err.to_string()---β [31mpost-create command failed: command not found[39m--π‘ [2mUse [90m--no-verify[39m to skip post-create commands[22mdiff --git a/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_failure.snap b/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_failure.snapindex a443848c5..a91e12c1b 100644--- a/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_failure.snap+++ b/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_failure.snap@@ -7,6 +7,7 @@ info:- main- "--force"env:+ APPDATA: "[TEST_CONFIG_HOME]"CLICOLOR_FORCE: "1"COLUMNS: "150"GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"@@ -14,10 +15,14 @@ info:GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"GIT_CONFIG_SYSTEM: /dev/nullGIT_EDITOR: ""+ HOME: "[TEST_HOME]"LANG: CLC_ALL: C+ PATH: "[PATH]"SOURCE_DATE_EPOCH: "1735776000"+ USERPROFILE: "[TEST_HOME]"WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"---success: falseexit_code: 1