Skip to content

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

feat: allow running individual named hook commands (#114)

Maximilian Roos34e8e25b30d4
diff --git a/src/cli.rs b/src/cli.rs
index 8b8e37594..c84c62ee7 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -614,6 +614,10 @@ pub enum StepCommand {
/// Run post-create hook
PostCreate {
+ /// Run only this command from hook config
+ #[arg(add = crate::completion::hook_command_name_completer())]
+ name: Option<String>,
+
/// Skip approval prompts
#[arg(short, long)]
force: bool,
@@ -621,6 +625,10 @@ pub enum StepCommand {
/// Run post-start hook
PostStart {
+ /// Run only this command from hook config
+ #[arg(add = crate::completion::hook_command_name_completer())]
+ name: Option<String>,
+
/// Skip approval prompts
#[arg(short, long)]
force: bool,
@@ -628,6 +636,10 @@ pub enum StepCommand {
/// Run pre-commit hook
PreCommit {
+ /// Run only this command from hook config
+ #[arg(add = crate::completion::hook_command_name_completer())]
+ name: Option<String>,
+
/// Skip approval prompts
#[arg(short, long)]
force: bool,
@@ -635,6 +647,10 @@ pub enum StepCommand {
/// Run pre-merge hook
PreMerge {
+ /// Run only this command from hook config
+ #[arg(add = crate::completion::hook_command_name_completer())]
+ name: Option<String>,
+
/// Skip approval prompts
#[arg(short, long)]
force: bool,
@@ -642,6 +658,10 @@ pub enum StepCommand {
/// Run post-merge hook
PostMerge {
+ /// Run only this command from hook config
+ #[arg(add = crate::completion::hook_command_name_completer())]
+ name: Option<String>,
+
/// Skip approval prompts
#[arg(short, long)]
force: bool,
@@ -649,6 +669,10 @@ pub enum StepCommand {
/// Run pre-remove hook
PreRemove {
+ /// Run only this command from hook config
+ #[arg(add = crate::completion::hook_command_name_completer())]
+ name: Option<String>,
+
/// Skip approval prompts
#[arg(short, long)]
force: bool,
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index bbb0acb12..3ab67e3a5 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -150,7 +150,7 @@ impl CommitOptions<'_> {
)))?;
} else if let Some(ref config) = project_config {
let pipeline = HookPipeline::new(*self.ctx);
- pipeline.run_pre_commit(config, self.target_branch, self.auto_trust)?;
+ pipeline.run_pre_commit(config, self.target_branch, self.auto_trust, None)?;
}
if self.warn_about_untracked && self.stage_mode == StageMode::All {
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index d983ef915..2e3eba6bf 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -1,7 +1,7 @@
use color_print::cformat;
use worktrunk::HookType;
use worktrunk::config::{CommandConfig, CommandPhase, ProjectConfig};
-use worktrunk::git::WorktrunkError;
+use worktrunk::git::{GitError, WorktrunkError};
use worktrunk::styling::{format_bash_with_gutter, progress_message, warning_message};
use super::command_executor::{CommandContext, PreparedCommand, prepare_project_commands};
@@ -33,8 +33,35 @@ impl<'a> HookPipeline<'a> {
phase: CommandPhase,
auto_trust: bool,
extra_vars: &[(&str, &str)],
+ name_filter: Option<&str>,
) -> anyhow::Result<Vec<PreparedCommand>> {
- prepare_project_commands(command_config, &self.ctx, auto_trust, extra_vars, phase)
+ let commands =
+ prepare_project_commands(command_config, &self.ctx, auto_trust, extra_vars, phase)?;
+
+ // Filter by name if specified
+ match name_filter {
+ Some(name) => {
+ // Collect available names before consuming the iterator
+ let available: Vec<String> =
+ commands.iter().filter_map(|cmd| cmd.name.clone()).collect();
+
+ let filtered: Vec<_> = commands
+ .into_iter()
+ .filter(|cmd| cmd.name.as_deref() == Some(name))
+ .collect();
+
+ if filtered.is_empty() {
+ return Err(GitError::HookCommandNotFound {
+ name: name.to_string(),
+ available,
+ }
+ .into());
+ }
+
+ Ok(filtered)
+ }
+ None => Ok(commands),
+ }
}
/// Run hook commands sequentially, using the provided failure strategy.
@@ -48,8 +75,10 @@ impl<'a> HookPipeline<'a> {
label_prefix: &str,
hook_type: HookType,
failure_strategy: HookFailureStrategy,
+ name_filter: Option<&str>,
) -> anyhow::Result<()> {
- let commands = self.prepare_commands(command_config, phase, auto_trust, extra_vars)?;
+ let commands =
+ self.prepare_commands(command_config, phase, auto_trust, extra_vars, name_filter)?;
if commands.is_empty() {
return Ok(());
}
@@ -128,6 +157,7 @@ impl<'a> HookPipeline<'a> {
}
/// Spawn hook commands in the background (used for post-start hooks).
+ #[allow(clippy::too_many_arguments)]
pub fn spawn_detached(
&self,
command_config: &CommandConfig,
@@ -135,8 +165,10 @@ impl<'a> HookPipeline<'a> {
auto_trust: bool,
extra_vars: &[(&str, &str)],
label_prefix: &str,
+ name_filter: Option<&str>,
) -> anyhow::Result<()> {
- let commands = self.prepare_commands(command_config, phase, auto_trust, extra_vars)?;
+ let commands =
+ self.prepare_commands(command_config, phase, auto_trust, extra_vars, name_filter)?;
if commands.is_empty() {
return Ok(());
}
@@ -175,6 +207,7 @@ impl<'a> HookPipeline<'a> {
project_config: &ProjectConfig,
target_branch: Option<&str>,
auto_trust: bool,
+ name_filter: Option<&str>,
) -> anyhow::Result<()> {
let Some(pre_commit_config) = &project_config.pre_commit else {
return Ok(());
@@ -193,6 +226,7 @@ impl<'a> HookPipeline<'a> {
"pre-commit",
HookType::PreCommit,
HookFailureStrategy::FailFast,
+ name_filter,
)
}
}
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 84024d39b..dd7ad2936 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -173,7 +173,7 @@ pub fn handle_merge(
// Do this after commit/squash/rebase to validate the final state that will be pushed
if verify && let Some(project_config) = repo.load_project_config()? {
let ctx = env.context(force);
- run_pre_merge_commands(&project_config, &ctx, &target_branch, true)?;
+ run_pre_merge_commands(&project_config, &ctx, &target_branch, true, None)?;
}
// Fast-forward push to target branch with commit/squash/rebase info for consolidated message
@@ -239,7 +239,7 @@ pub fn handle_merge(
&destination_repo_root,
force,
);
- execute_post_merge_commands(&ctx, &target_branch, true)?;
+ execute_post_merge_commands(&ctx, &target_branch, true, None)?;
}
Ok(())
@@ -267,6 +267,7 @@ pub fn run_pre_merge_commands(
ctx: &CommandContext,
target_branch: &str,
auto_trust: bool,
+ name_filter: Option<&str>,
) -> anyhow::Result<()> {
let Some(pre_merge_config) = &project_config.pre_merge else {
return Ok(());
@@ -282,6 +283,7 @@ pub fn run_pre_merge_commands(
"pre-merge",
HookType::PreMerge,
HookFailureStrategy::FailFast,
+ name_filter,
)
}
@@ -294,6 +296,7 @@ pub fn execute_post_merge_commands(
ctx: &CommandContext,
target_branch: &str,
auto_trust: bool,
+ name_filter: Option<&str>,
) -> anyhow::Result<()> {
// Load project config from the main worktree path directly
let project_config = match ctx.repo.load_project_config()? {
@@ -315,6 +318,7 @@ pub fn execute_post_merge_commands(
"post-merge",
HookType::PostMerge,
HookFailureStrategy::Warn,
+ name_filter,
)
}
@@ -325,7 +329,11 @@ pub fn execute_post_merge_commands(
/// # Arguments
/// * `ctx` - Command context pointing to the worktree being removed
/// * `auto_trust` - When true, skip approval prompts
-pub fn execute_pre_remove_commands(ctx: &CommandContext, auto_trust: bool) -> anyhow::Result<()> {
+pub fn execute_pre_remove_commands(
+ ctx: &CommandContext,
+ auto_trust: bool,
+ name_filter: Option<&str>,
+) -> anyhow::Result<()> {
let project_config = match ctx.repo.load_project_config()? {
Some(cfg) => cfg,
None => return Ok(()),
@@ -345,5 +353,6 @@ pub fn execute_pre_remove_commands(ctx: &CommandContext, auto_trust: bool) -> an
"pre-remove",
HookType::PreRemove,
HookFailureStrategy::FailFast,
+ name_filter,
)
}
diff --git a/src/commands/standalone.rs b/src/commands/standalone.rs
index 7af054749..6fa56fe72 100644
--- a/src/commands/standalone.rs
+++ b/src/commands/standalone.rs
@@ -16,7 +16,11 @@ use super::project_config::collect_commands_for_hooks;
use super::repository_ext::RepositoryCliExt;
/// Handle `wt step hook` command
-pub fn handle_standalone_run_hook(hook_type: HookType, force: bool) -> anyhow::Result<()> {
+pub fn handle_standalone_run_hook(
+ hook_type: HookType,
+ force: bool,
+ name_filter: Option<&str>,
+) -> anyhow::Result<()> {
// Derive context from current environment
let env = CommandEnv::for_action(&format!("run {hook_type} hook"))?;
let repo = &env.repo;
@@ -32,39 +36,100 @@ pub fn handle_standalone_run_hook(hook_type: HookType, force: bool) -> anyhow::R
match hook_type {
HookType::PostCreate => {
check_hook_configured(&project_config.post_create, hook_type)?;
- ctx.execute_post_create_commands()
+ run_hook_with_filter(
+ &ctx,
+ &project_config.post_create,
+ hook_type,
+ &[],
+ name_filter,
+ )
}
HookType::PostStart => {
check_hook_configured(&project_config.post_start, hook_type)?;
- ctx.execute_post_start_commands_sequential()
+ run_hook_with_filter(
+ &ctx,
+ &project_config.post_start,
+ hook_type,
+ &[],
+ name_filter,
+ )
}
HookType::PreCommit => {
check_hook_configured(&project_config.pre_commit, hook_type)?;
// Pre-commit hook can optionally use target branch context
let target_branch = repo.default_branch().ok();
- HookPipeline::new(ctx).run_pre_commit(&project_config, target_branch.as_deref(), false)
+ let extra_vars: Vec<(&str, &str)> = target_branch
+ .as_deref()
+ .into_iter()
+ .map(|t| ("target", t))
+ .collect();
+ run_hook_with_filter(
+ &ctx,
+ &project_config.pre_commit,
+ hook_type,
+ &extra_vars,
+ name_filter,
+ )
}
HookType::PreMerge => {
check_hook_configured(&project_config.pre_merge, hook_type)?;
// Use current branch as target - when running standalone, the "target"
// represents what branch we're on (vs. in `wt merge` where it's the
// branch being merged into)
- run_pre_merge_commands(&project_config, &ctx, &env.branch, false)
+ run_pre_merge_commands(&project_config, &ctx, &env.branch, false, name_filter)
}
HookType::PostMerge => {
check_hook_configured(&project_config.post_merge, hook_type)?;
// Use current branch as target - when running standalone, the "target"
// represents what branch we're on (vs. in `wt merge` where it's the
// branch being merged into)
- execute_post_merge_commands(&ctx, &env.branch, false)
+ execute_post_merge_commands(&ctx, &env.branch, false, name_filter)
}
HookType::PreRemove => {
check_hook_configured(&project_config.pre_remove, hook_type)?;
- execute_pre_remove_commands(&ctx, false)
+ execute_pre_remove_commands(&ctx, false, name_filter)
}
}
}
+/// Run a hook with optional name filter (used by standalone hook commands)
+fn run_hook_with_filter(
+ ctx: &super::command_executor::CommandContext,
+ config: &Option<worktrunk::config::CommandConfig>,
+ hook_type: HookType,
+ extra_vars: &[(&str, &str)],
+ name_filter: Option<&str>,
+) -> anyhow::Result<()> {
+ use super::hooks::{HookFailureStrategy, HookPipeline};
+ use worktrunk::config::CommandPhase;
+
+ let Some(command_config) = config else {
+ return Ok(());
+ };
+
+ let pipeline = HookPipeline::new(*ctx);
+ let phase = match hook_type {
+ HookType::PostCreate => CommandPhase::PostCreate,
+ HookType::PostStart => CommandPhase::PostStart,
+ HookType::PreCommit => CommandPhase::PreCommit,
+ HookType::PreMerge => CommandPhase::PreMerge,
+ HookType::PostMerge => CommandPhase::PostMerge,
+ HookType::PreRemove => CommandPhase::PreRemove,
+ };
+ let label = hook_type.to_string().to_lowercase().replace(' ', "-");
+
+ pipeline.run_sequential(
+ command_config,
+ phase,
+ false, // auto_trust=false, require approval for standalone
+ extra_vars,
+ &label,
+ hook_type,
+ HookFailureStrategy::FailFast,
+ name_filter,
+ )
+}
+
fn check_hook_configured<T>(hook: &Option<T>, hook_type: HookType) -> anyhow::Result<()> {
if hook.is_none() {
return Err(worktrunk::git::GitError::Other {
@@ -158,7 +223,7 @@ pub fn handle_squash(
"Skipping pre-commit hook (<bright-black>--no-verify</>)"
)))?;
} else if let Some(ref config) = project_config {
- HookPipeline::new(ctx).run_pre_commit(config, Some(&target_branch), auto_trust)?;
+ HookPipeline::new(ctx).run_pre_commit(config, Some(&target_branch), auto_trust, None)?;
}
// Get merge base with target branch
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index ab817478c..8897dc31c 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -621,6 +621,7 @@ impl<'a> CommandContext<'a> {
"post-create",
HookType::PostCreate,
HookFailureStrategy::Warn,
+ None,
)
}
@@ -642,29 +643,7 @@ impl<'a> CommandContext<'a> {
false,
&[],
"post-start",
- )
- }
-
- /// Execute post-start commands sequentially (blocking) - for testing
- pub fn execute_post_start_commands_sequential(&self) -> anyhow::Result<()> {
- let project_config = match self.repo.load_project_config()? {
- Some(cfg) => cfg,
- None => return Ok(()),
- };
-
- let Some(post_start_config) = &project_config.post_start else {
- return Ok(());
- };
-
- let pipeline = HookPipeline::new(*self);
- pipeline.run_sequential(
- post_start_config,
- CommandPhase::PostStart,
- false,
- &[],
- "post-start",
- HookType::PostStart,
- HookFailureStrategy::Warn,
+ None,
)
}
}
diff --git a/src/completion.rs b/src/completion.rs
index 2afc3e68d..0414fac96 100644
--- a/src/completion.rs
+++ b/src/completion.rs
@@ -7,6 +7,7 @@ use clap_complete::env::CompleteEnv;
use crate::cli;
use crate::display::format_relative_time_short;
+use worktrunk::config::ProjectConfig;
use worktrunk::git::{BranchCategory, Repository};
/// Handle shell-initiated completion requests via `COMPLETE=$SHELL wt`
@@ -51,6 +52,95 @@ pub fn local_branches_completer() -> ArgValueCompleter {
})
}
+/// Hook command name completion for `wt step <hook-type> <name>`.
+/// Completes with command names from the project config for the hook type being invoked.
+pub fn hook_command_name_completer() -> ArgValueCompleter {
+ ArgValueCompleter::new(HookCommandCompleter)
+}
+
+#[derive(Clone, Copy)]
+struct HookCommandCompleter;
+
+impl ValueCompleter for HookCommandCompleter {
+ fn complete(&self, current: &OsStr) -> Vec<CompletionCandidate> {
+ // If user is typing an option (starts with -), don't suggest command names
+ if current.to_str().is_some_and(|s| s.starts_with('-')) {
+ return Vec::new();
+ }
+
+ let prefix = current.to_string_lossy();
+ complete_hook_commands()
+ .into_iter()
+ .filter(|candidate| {
+ candidate
+ .get_value()
+ .to_string_lossy()
+ .starts_with(&*prefix)
+ })
+ .collect()
+ }
+}
+
+fn complete_hook_commands() -> Vec<CompletionCandidate> {
+ // Get the hook type from the command line context
+ let hook_type = CONTEXT.with(|ctx| {
+ ctx.borrow().as_ref().and_then(|ctx| {
+ // Look for the hook subcommand in the args
+ for hook in &[
+ "post-create",
+ "post-start",
+ "pre-commit",
+ "pre-merge",
+ "post-merge",
+ "pre-remove",
+ ] {
+ if ctx.contains(hook) {
+ return Some(*hook);
+ }
+ }
+ None
+ })
+ });
+
+ let Some(hook_type) = hook_type else {
+ return Vec::new();
+ };
+
+ // Load project config
+ let repo = Repository::current();
+ let repo_root = match repo.worktree_root() {
+ Ok(root) => root,
+ Err(_) => return Vec::new(),
+ };
+
+ let project_config = match ProjectConfig::load(&repo_root) {
+ Ok(Some(config)) => config,
+ _ => return Vec::new(),
+ };
+
+ // Get command names for the hook type
+ let command_config = match hook_type {
+ "post-create" => &project_config.post_create,
+ "post-start" => &project_config.post_start,
+ "pre-commit" => &project_config.pre_commit,
+ "pre-merge" => &project_config.pre_merge,
+ "post-merge" => &project_config.post_merge,
+ "pre-remove" => &project_config.pre_remove,
+ _ => return Vec::new(),
+ };
+
+ let Some(config) = command_config else {
+ return Vec::new();
+ };
+
+ config
+ .commands()
+ .iter()
+ .filter_map(|cmd| cmd.name.as_ref())
+ .map(|name| CompletionCandidate::new(name.clone()))
+ .collect()
+}
+
#[derive(Clone, Copy)]
struct BranchCompleter {
suppress_with_create: bool,
@@ -198,5 +288,12 @@ fn adjust_completion_command(cmd: Command) -> Command {
.mut_subcommand("rebase", |rebase| {
rebase.mut_arg("target", |arg| arg.last(true))
})
+ // Hook subcommands - allow name after --force
+ .mut_subcommand("post-create", |c| c.mut_arg("name", |arg| arg.last(true)))
+ .mut_subcommand("post-start", |c| c.mut_arg("name", |arg| arg.last(true)))
+ .mut_subcommand("pre-commit", |c| c.mut_arg("name", |arg| arg.last(true)))
+ .mut_subcommand("pre-merge", |c| c.mut_arg("name", |arg| arg.last(true)))
+ .mut_subcommand("post-merge", |c| c.mut_arg("name", |arg| arg.last(true)))
+ .mut_subcommand("pre-remove", |c| c.mut_arg("name", |arg| arg.last(true)))
})
}
diff --git a/src/git/error.rs b/src/git/error.rs
index 5ce7fe636..397ce1df4 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -111,6 +111,10 @@ pub enum GitError {
// Validation/other errors
NotInteractive,
+ HookCommandNotFound {
+ name: String,
+ available: Vec<String>,
+ },
ParseError {
message: String,
},
@@ -416,6 +420,31 @@ impl std::fmt::Display for GitError {
)
}
+ GitError::HookCommandNotFound { name, available } => {
+ if available.is_empty() {
+ write!(
+ f,
+ "{}",
+ error_message(cformat!(
+ "No command named <bold>{name}</> (hook has no named commands)"
+ ))
+ )
+ } else {
+ let available_str = available
+ .iter()
+ .map(|s| cformat!("<bold>{s}</>"))
+ .collect::<Vec<_>>()
+ .join(", ");
+ write!(
+ f,
+ "{}",
+ error_message(cformat!(
+ "No command named <bold>{name}</> (available: {available_str})"
+ ))
+ )
+ }
+ }
+
GitError::LlmCommandFailed { command, error } => {
let error_header = error_message("Commit generation command failed");
let error_block = format_error_block(error_header, error);
diff --git a/src/main.rs b/src/main.rs
index c21233889..b2e33237f 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -821,23 +821,23 @@ fn main() {
}
})
}
- StepCommand::PostCreate { force } => {
- handle_standalone_run_hook(HookType::PostCreate, force)
+ StepCommand::PostCreate { name, force } => {
+ handle_standalone_run_hook(HookType::PostCreate, force, name.as_deref())
}
- StepCommand::PostStart { force } => {
- handle_standalone_run_hook(HookType::PostStart, force)
+ StepCommand::PostStart { name, force } => {
+ handle_standalone_run_hook(HookType::PostStart, force, name.as_deref())
}
- StepCommand::PreCommit { force } => {
- handle_standalone_run_hook(HookType::PreCommit, force)
+ StepCommand::PreCommit { name, force } => {
+ handle_standalone_run_hook(HookType::PreCommit, force, name.as_deref())
}
- StepCommand::PreMerge { force } => {
- handle_standalone_run_hook(HookType::PreMerge, force)
+ StepCommand::PreMerge { name, force } => {
+ handle_standalone_run_hook(HookType::PreMerge, force, name.as_deref())
}
- StepCommand::PostMerge { force } => {
- handle_standalone_run_hook(HookType::PostMerge, force)
+ StepCommand::PostMerge { name, force } => {
+ handle_standalone_run_hook(HookType::PostMerge, force, name.as_deref())
}
- StepCommand::PreRemove { force } => {
- handle_standalone_run_hook(HookType::PreRemove, force)
+ StepCommand::PreRemove { name, force } => {
+ handle_standalone_run_hook(HookType::PreRemove, force, name.as_deref())
}
},
#[cfg(unix)]
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index d5f9dd797..006fb73ca 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -483,7 +483,7 @@ fn handle_removed_worktree_output(
main_path,
false, // force=false, prompt for approval
);
- execute_pre_remove_commands(&ctx, false)?;
+ execute_pre_remove_commands(&ctx, false, None)?;
}
// Handle detached HEAD case (no branch known)
diff --git a/tests/integration_tests/approval_ui.rs b/tests/integration_tests/approval_ui.rs
index 69188fd8f..fac945c4a 100644
--- a/tests/integration_tests/approval_ui.rs
+++ b/tests/integration_tests/approval_ui.rs
@@ -443,3 +443,136 @@ fn test_step_pre_merge_target_is_current_branch() {
"{{ target }} should be current branch, not default branch"
);
}
+
+/// Test running a specific named hook command
+#[test]
+fn test_step_hook_run_named_command() {
+ let repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Config with multiple named commands
+ repo.write_project_config(
+ r#"[pre-merge]
+test = "echo 'running test' > test.txt"
+lint = "echo 'running lint' > lint.txt"
+build = "echo 'running build' > build.txt"
+"#,
+ );
+ repo.commit("Add pre-merge hooks");
+
+ // Run only the "lint" command with --force to skip approval
+ let output = Command::new(env!("CARGO_BIN_EXE_wt"))
+ .args(["step", "pre-merge", "lint", "--force"])
+ .current_dir(repo.root_path())
+ .env("NO_COLOR", "1")
+ .output()
+ .expect("Failed to run wt step pre-merge lint");
+
+ assert!(
+ output.status.success(),
+ "wt step pre-merge lint failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ // Only lint.txt should exist
+ assert!(
+ repo.root_path().join("lint.txt").exists(),
+ "lint.txt should exist (lint command ran)"
+ );
+ assert!(
+ !repo.root_path().join("test.txt").exists(),
+ "test.txt should NOT exist (test command should not have run)"
+ );
+ assert!(
+ !repo.root_path().join("build.txt").exists(),
+ "build.txt should NOT exist (build command should not have run)"
+ );
+}
+
+/// Test error message when named hook command doesn't exist
+#[test]
+fn test_step_hook_unknown_name_error() {
+ let repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Config with multiple named commands
+ repo.write_project_config(
+ r#"[pre-merge]
+test = "echo 'test'"
+lint = "echo 'lint'"
+"#,
+ );
+ repo.commit("Add pre-merge hooks");
+
+ // Run with a name that doesn't exist
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ let mut cmd = make_snapshot_cmd(
+ &repo,
+ "step",
+ &["pre-merge", "nonexistent", "--force"],
+ None,
+ );
+ assert_cmd_snapshot!("step_hook_unknown_name_error", cmd);
+ });
+}
+
+/// Test error message when hook has no named commands
+#[test]
+fn test_step_hook_name_filter_on_unnamed_command() {
+ let repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Config with a single unnamed command (no table)
+ repo.write_project_config(r#"pre-merge = "echo 'test'""#);
+ repo.commit("Add pre-merge hook");
+
+ // Run with a name filter on a hook that has no named commands
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ let mut cmd = make_snapshot_cmd(&repo, "step", &["pre-merge", "test", "--force"], None);
+ assert_cmd_snapshot!("step_hook_name_filter_on_unnamed", cmd);
+ });
+}
+
+/// Test running all hooks (no name filter) still works
+#[test]
+fn test_step_hook_run_all_commands() {
+ let repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Config with multiple named commands
+ repo.write_project_config(
+ r#"[pre-merge]
+first = "echo 'first' >> output.txt"
+second = "echo 'second' >> output.txt"
+third = "echo 'third' >> output.txt"
+"#,
+ );
+ repo.commit("Add pre-merge hooks");
+
+ // Run without name filter (all commands should run)
+ let output = Command::new(env!("CARGO_BIN_EXE_wt"))
+ .args(["step", "pre-merge", "--force"])
+ .current_dir(repo.root_path())
+ .env("NO_COLOR", "1")
+ .output()
+ .expect("Failed to run wt step pre-merge");
+
+ assert!(
+ output.status.success(),
+ "wt step pre-merge failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ // All three commands should have written to output.txt
+ let output_file = repo.root_path().join("output.txt");
+ let content = fs::read_to_string(&output_file).expect("output.txt should exist");
+ let lines: Vec<&str> = content.lines().collect();
+
+ assert_eq!(
+ lines,
+ vec!["first", "second", "third"],
+ "All commands should have run in order"
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__approval_ui__step_hook_name_filter_on_unnamed.snap b/tests/snapshots/integration__integration_tests__approval_ui__step_hook_name_filter_on_unnamed.snap
new file mode 100644
index 000000000..560d96a1d
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__approval_ui__step_hook_name_filter_on_unnamed.snap
@@ -0,0 +1,28 @@
+---
+source: tests/integration_tests/approval_ui.rs
+info:
+ program: wt
+ args:
+ - step
+ - pre-merge
+ - test
+ - "--force"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1735776000"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+❌ No command named test (hook has no named commands)
diff --git a/tests/snapshots/integration__integration_tests__approval_ui__step_hook_unknown_name_error.snap b/tests/snapshots/integration__integration_tests__approval_ui__step_hook_unknown_name_error.snap
new file mode 100644
index 000000000..87d89ee74
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__approval_ui__step_hook_unknown_name_error.snap
@@ -0,0 +1,28 @@
+---
+source: tests/integration_tests/approval_ui.rs
+info:
+ program: wt
+ args:
+ - step
+ - pre-merge
+ - nonexistent
+ - "--force"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1735776000"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+❌ No command named nonexistent (available: test, lint)