Skip to content

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.rs
index 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.rs
index 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.rs
index 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 branch
diff --git a/src/git/error.rs b/src/git/error.rs
index 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 applicable
pub 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 content
fn format_error_block(header: String, error: &str) -> String {
let trimmed = error.trim();
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 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.rs
index 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 Display
if 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 gutter
let msg = e.to_string();
diff --git a/tests/integration_tests/git_error_display.rs b/tests/integration_tests/git_error_display.rs
index 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.snap
index 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.rs
expression: err.to_string()
---
❌ pre-merge command failed: test: exit code 1
-
-πŸ’‘ Use --no-verify to skip pre-merge commands
diff --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.snap
new file mode 100644
index 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()
+---
+❌ pre-merge command failed: test: exit code 1
+
+πŸ’‘ Use --no-verify to skip pre-merge commands
diff --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.snap
index 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.rs
expression: err.to_string()
---
❌ post-create command failed: command not found
-
-πŸ’‘ Use --no-verify to skip post-create commands
diff --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.snap
index 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/null
GIT_EDITOR: ""
+ HOME: "[TEST_HOME]"
LANG: C
LC_ALL: C
+ PATH: "[PATH]"
SOURCE_DATE_EPOCH: "1735776000"
+ USERPROFILE: "[TEST_HOME]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
---
success: false
exit_code: 1