Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(commit): suppress spurious "(--no-hooks)" line after declined approval (#2485)

Maximilian Roosb34ab4dcaacc
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index 13ca4ace5..da9956d7d 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -17,11 +17,43 @@ use super::template_vars::TemplateVars;
// Re-export StageMode from config for use by CLI
pub use worktrunk::config::StageMode;
+/// Whether pre/post-commit hooks run, and — if not — whether to print the skip message.
+/// Two distinct paths disable hooks: `--no-hooks` (we own the skip message) and declined
+/// approval (the caller already printed its own message).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum HookGate {
+ /// Run pre-commit and post-commit hooks normally.
+ Run,
+ /// Skip hooks because the user passed `--no-hooks`. `commit()` prints the skip message.
+ NoHooksFlag,
+ /// Skip hooks silently — caller has already explained why.
+ Silent,
+}
+
+impl HookGate {
+ /// Whether pre/post-commit hooks should execute.
+ pub(crate) fn run(self) -> bool {
+ matches!(self, Self::Run)
+ }
+
+ /// Build from an entry-point `verify` flag plus an approval-prompt result.
+ /// `verify=false` → `NoHooksFlag`; declined → `Silent`; approved → `Run`.
+ pub(crate) fn from_approval(verify: bool, approved: bool) -> Self {
+ if !verify {
+ Self::NoHooksFlag
+ } else if approved {
+ Self::Run
+ } else {
+ Self::Silent
+ }
+ }
+}
+
/// Options for committing current changes.
pub struct CommitOptions<'a> {
pub ctx: &'a CommandContext<'a>,
pub target_branch: Option<&'a str>,
- pub verify: bool,
+ pub hooks: HookGate,
pub stage_mode: StageMode,
pub warn_about_untracked: bool,
pub show_no_squash_note: bool,
@@ -33,7 +65,7 @@ impl<'a> CommitOptions<'a> {
Self {
ctx,
target_branch: None,
- verify: true,
+ hooks: HookGate::Run,
stage_mode: StageMode::All,
warn_about_untracked: true,
show_no_squash_note: false,
@@ -173,8 +205,10 @@ impl CommitOptions<'_> {
);
let any_hooks_exist = user_cfg.is_some() || proj_cfg.is_some();
- // Show skip message
- if !self.verify && any_hooks_exist {
+ // Only print "Skipping pre-commit hooks (--no-hooks)" when --no-hooks was actually
+ // passed. If hooks are disabled because the caller declined an approval prompt
+ // (HookGate::Silent), the caller has already printed its own message.
+ if self.hooks == HookGate::NoHooksFlag && any_hooks_exist {
eprintln!("{}", info_message("Skipping pre-commit hooks (--no-hooks)"));
}
@@ -182,7 +216,7 @@ impl CommitOptions<'_> {
.target_branch
.map_or_else(TemplateVars::new, |t| TemplateVars::new().with_target(t));
- if self.verify {
+ if self.hooks.run() {
// Run pre-commit hooks (user first, then project).
execute_hook(
self.ctx,
@@ -230,7 +264,7 @@ impl CommitOptions<'_> {
)?;
// Spawn post-commit hooks in background (respects --no-hooks).
- if self.verify {
+ if self.hooks.run() {
let extra_vars = template_vars.as_extra_vars();
let pipelines =
prepare_background_pipelines(self.ctx, HookType::PostCommit, &extra_vars, None)?;
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index fcce18a9b..9187d6451 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -7,7 +7,7 @@ use worktrunk::styling::{eprintln, info_message};
use super::command_approval::approve_command_batch;
use super::command_executor::CommandContext;
use super::command_executor::FailureStrategy;
-use super::commit::CommitOptions;
+use super::commit::{CommitOptions, HookGate};
use super::context::CommandEnv;
use super::hooks::{HookAnnouncer, execute_hook};
use super::project_config::{ApprovableCommand, collect_commands_for_hooks};
@@ -188,8 +188,14 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
let approvals = Approvals::load().context("Failed to load approvals")?;
let approved = approve_command_batch(&all_commands, &project_id, &approvals, yes, false)?;
- // If commands were declined, skip hooks but continue with merge
- // Shadow verify to gate all subsequent hook execution on approval
+ // Commit-phase gate uses the original `verify` (before the shadow below) so it can
+ // distinguish --no-hooks from declined-approval; CommitOptions and handle_squash
+ // need that distinction to suppress a duplicate "(--no-hooks)" line.
+ let commit_hooks = HookGate::from_approval(verify, approved);
+
+ // If commands were declined, skip hooks but continue with merge.
+ // Shadow verify to gate all subsequent hook execution (pre-merge, post-merge,
+ // pre-remove, post-switch) on approval.
let verify = if approved {
verify
} else {
@@ -211,7 +217,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
let ctx = env.context(yes);
let mut options = CommitOptions::new(&ctx);
options.target_branch = Some(&target_branch);
- options.verify = verify;
+ options.hooks = commit_hooks;
options.stage_mode = stage_mode;
options.warn_about_untracked = stage_mode == super::commit::StageMode::All;
options.show_no_squash_note = true;
@@ -223,13 +229,15 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
false // No dirty changes or --no-commit
};
- // Squash commits if enabled - track whether squashing occurred
+ // Squash commits if enabled - track whether squashing occurred.
+ // Pass `commit_hooks` (not the shadowed `verify`) so handle_squash gets the
+ // --no-hooks vs declined-approval distinction.
let squashed = if squash_enabled {
matches!(
super::step_commands::handle_squash(
Some(&target_branch),
yes,
- verify,
+ commit_hooks,
Some(stage_mode),
Some(&mut announcer),
)?,
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index e55f98ca1..cd341232b 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -37,7 +37,7 @@ use worktrunk::styling::{
use super::command_approval::approve_or_skip;
use super::command_executor::FailureStrategy;
-use super::commit::{CommitGenerator, CommitOptions, StageMode};
+use super::commit::{CommitGenerator, CommitOptions, HookGate, StageMode};
use super::context::CommandEnv;
use super::hooks::{
HookAnnouncer, execute_hook, prepare_background_pipelines, run_hooks_background,
@@ -82,17 +82,18 @@ pub fn step_commit(
// CLI flag overrides config value
let stage_mode = stage.unwrap_or(env.resolved().commit.stage());
- // "Approve at the Gate": approve commit hooks upfront (unless --no-hooks)
- // Shadow verify: if user declines approval, skip hooks but continue commit
- let verify = verify
+ // "Approve at the Gate": prompt for approval upfront (when hooks are enabled) so
+ // hook execution downstream is fully gated.
+ let approved = verify
&& approve_or_skip(
&ctx,
&[HookType::PreCommit, HookType::PostCommit],
"Commands declined, committing without hooks",
)?;
+ let hooks = HookGate::from_approval(verify, approved);
let mut options = CommitOptions::new(&ctx);
- options.verify = verify;
+ options.hooks = hooks;
options.stage_mode = stage_mode;
options.show_no_squash_note = false;
// Only warn about untracked if we're staging all
@@ -117,7 +118,9 @@ pub enum SquashResult {
/// Handle shared squash workflow (used by `wt step squash` and `wt merge`)
///
/// # Arguments
-/// * `verify` - If true, run pre-commit hooks (false when --no-hooks flag is passed)
+/// * `hooks` - Whether to run pre-commit hooks. `Run` triggers an internal approval
+/// prompt; `NoHooksFlag` skips with a "(--no-hooks)" message; `Silent` skips silently
+/// (used when the caller already declined approval upstream and announced it).
/// * `stage` - CLI-provided stage mode. If None, uses the effective config default.
/// * `parent_announcer` - When `Some`, post-commit hooks register on the
/// caller's announcer so they share an announce line with later phases
@@ -126,7 +129,7 @@ pub enum SquashResult {
pub fn handle_squash(
target: Option<&str>,
yes: bool,
- verify: bool,
+ hooks: HookGate,
stage: Option<StageMode>,
parent_announcer: Option<&mut HookAnnouncer<'_>>,
) -> anyhow::Result<SquashResult> {
@@ -156,20 +159,29 @@ pub fn handle_squash(
);
let any_hooks_exist = user_cfg.is_some() || proj_cfg.is_some();
- // "Approve at the Gate": approve commit hooks upfront (unless --no-hooks)
- // Shadow verify: if user declines approval, skip hooks but continue squash
- let verify = if verify {
- approve_or_skip(
- &ctx,
- &[HookType::PreCommit, HookType::PostCommit],
- "Commands declined, squashing without hooks",
- )?
- } else {
- // Show skip message when --no-hooks was passed and hooks exist
- if any_hooks_exist {
- eprintln!("{}", info_message("Skipping pre-commit hooks (--no-hooks)"));
+ // Resolve the hook gate: Run triggers an approval prompt and downgrades to Silent
+ // on decline (approve_or_skip prints its own message). NoHooksFlag prints the skip
+ // message itself; Silent stays quiet so the upstream caller's decline message isn't
+ // followed by a spurious "(--no-hooks)" line.
+ let hooks = match hooks {
+ HookGate::Run => {
+ if approve_or_skip(
+ &ctx,
+ &[HookType::PreCommit, HookType::PostCommit],
+ "Commands declined, squashing without hooks",
+ )? {
+ HookGate::Run
+ } else {
+ HookGate::Silent
+ }
+ }
+ HookGate::NoHooksFlag => {
+ if any_hooks_exist {
+ eprintln!("{}", info_message("Skipping pre-commit hooks (--no-hooks)"));
+ }
+ HookGate::NoHooksFlag
}
- false // --no-hooks was passed
+ HookGate::Silent => HookGate::Silent,
};
// Get and validate target ref (any commit-ish for merge-base calculation)
@@ -193,7 +205,7 @@ pub fn handle_squash(
}
// Run pre-commit hooks (user first, then project).
- if verify {
+ if hooks.run() {
execute_hook(
&ctx,
HookType::PreCommit,
@@ -349,7 +361,7 @@ pub fn handle_squash(
);
// Spawn post-commit hooks in background (respects --no-hooks).
- if verify {
+ if hooks.run() {
let extra_vars = template_vars.as_extra_vars();
let pipelines =
prepare_background_pipelines(&ctx, HookType::PostCommit, &extra_vars, None)?;
diff --git a/src/main.rs b/src/main.rs
index 2555c0950..45266bb7a 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -41,6 +41,7 @@ pub(crate) use invocation::{
pub(crate) use crate::cli::OutputFormat;
+use commands::commit::HookGate;
#[cfg(unix)]
use commands::handle_picker;
use commands::repository_ext::RepositoryCliExt;
@@ -215,7 +216,12 @@ fn handle_step_command(action: StepCommand, yes: bool) -> anyhow::Result<()> {
commands::step_show_squash_prompt(args.target.as_deref())
} else {
// Approval is handled inside handle_squash (like step_commit)
- handle_squash(args.target.as_deref(), yes, verify, args.stage, None).map(|result| {
+ let hooks = if verify {
+ HookGate::Run
+ } else {
+ HookGate::NoHooksFlag
+ };
+ handle_squash(args.target.as_deref(), yes, hooks, args.stage, None).map(|result| {
match result {
SquashResult::Squashed | SquashResult::NoNetChanges => {}
SquashResult::NoCommitsAhead(branch) => {
diff --git a/tests/integration_tests/approval_pty.rs b/tests/integration_tests/approval_pty.rs
index 375ca0dca..6d4943147 100644
--- a/tests/integration_tests/approval_pty.rs
+++ b/tests/integration_tests/approval_pty.rs
@@ -53,6 +53,16 @@ fn approval_pty_settings(repo: &TestRepo) -> insta::Settings {
settings
}
+/// Decline-path regression: a declined approval prompt prints its own "Commands declined,
+/// …" line; the downstream commit/squash phase must not also print
+/// "Skipping pre-commit hooks (--no-hooks)" — the user didn't pass that flag.
+fn assert_no_spurious_no_hooks(output: &str) {
+ assert!(
+ !output.contains("--no-hooks"),
+ "Declined approval should not produce a spurious '(--no-hooks)' line. Output:\n{output}"
+ );
+}
+
/// Get test env vars with shell integration configured.
///
/// This adds SHELL=/bin/zsh to the env vars, which is needed because:
@@ -459,6 +469,7 @@ command = "cat >/dev/null && echo 'feat: test commit message'"
output.contains("committing without hooks"),
"Should indicate commit proceeds without hooks. Output:\n{output}"
);
+ assert_no_spurious_no_hooks(&output);
}
#[rstest]
@@ -501,6 +512,47 @@ command = "cat >/dev/null && echo 'feat: squashed commit message'"
output.contains("squashing without hooks"),
"Should indicate squash proceeds without hooks. Output:\n{output}"
);
+ assert_no_spurious_no_hooks(&output);
+}
+
+/// `wt merge` with a pre-commit hook + dirty worktree: declining the approval
+/// prompt should print only "Commands declined, continuing merge", not also
+/// "Skipping pre-commit hooks (--no-hooks)" from the commit phase.
+#[rstest]
+fn test_approval_prompt_merge_decline_no_spurious_skip(mut repo: TestRepo) {
+ // Remove origin so worktrunk uses directory name as project identifier
+ repo.run_git(&["remote", "remove", "origin"]);
+
+ // Add pre-commit hook to project config and commit it
+ repo.write_project_config(r#"pre-commit = "echo 'pre-commit hook'""#);
+ repo.commit("Add pre-commit config");
+
+ // Create a feature worktree with a dirty change so the merge runs the commit phase
+ let feature_wt = repo.add_worktree("feature-merge-decline");
+ std::fs::write(feature_wt.join("new-file.txt"), "new content").unwrap();
+
+ // Configure LLM commit generation so the commit phase has a message to use
+ repo.write_test_config(
+ r#"
+[commit.generation]
+command = "cat >/dev/null && echo 'feat: test commit message'"
+"#,
+ );
+
+ let env_vars = test_env_vars_with_shell(&repo);
+
+ // Decline the approval prompt
+ let (output, exit_code) = exec_wt_in_pty_cwd(&feature_wt, &["merge"], &env_vars, "n\n");
+
+ assert_eq!(
+ exit_code, 0,
+ "Merge should succeed even when hooks declined. Output:\n{output}"
+ );
+ assert!(
+ output.contains("Commands declined, continuing merge"),
+ "Should show merge-specific decline message. Output:\n{output}"
+ );
+ assert_no_spurious_no_hooks(&output);
}
/// `wt config approvals add` accepts the prompt — covers the success branch of