Skip to content

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

refactor: unify foreground execution of hooks and aliases (#2128)

Maximilian Roosdc365fbbc386
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index 6c117255b..1310f5fcc 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -1,40 +1,25 @@
//! Alias command implementation.
//!
//! Aliases are user-defined commands configured in `[aliases]` sections of user
-//! or project config. They share execution infrastructure with hooks:
-//! `execute_shell_command` (signal forwarding, ANSI reset, `Cmd` tracing),
-//! `CommandConfig` (pipeline steps), template expansion, and the approval system.
+//! or project config. They share the foreground execution path with hooks via
+//! `execute_pipeline_foreground` in `command_executor`, which handles pipeline
+//! structure, template expansion, concurrent steps, and error handling.
//!
//! ## Execution model
//!
-//! Aliases iterate `CommandConfig::steps()`, preserving pipeline structure:
-//! - `HookStep::Single` — serial execution, fail-fast
-//! - `HookStep::Concurrent` — commands spawn via `thread::scope`, all run to
-//! completion, first error propagated
+//! Aliases build `ForegroundStep`s from `CommandConfig::steps()`, preserving
+//! pipeline structure (`Single` vs `Concurrent`). All commands use lazy template
+//! expansion — `vars.*` references resolve from git config at execution time,
+//! so prior steps that set vars via `wt config state vars set` are visible to
+//! later steps.
//!
-//! Template expansion happens at execution time (not at a separate prep step),
-//! so `vars.*` references naturally read fresh values from git config — prior
-//! steps that set vars via `wt config state vars set` are visible to later steps.
+//! ## Why foreground and background execution differ
//!
-//! ## Why concurrent execution isn't shared with `run_pipeline`
-//!
-//! Both alias and background pipeline runners need "spawn N commands, wait for
-//! all". They use different primitives because their leaf executors differ:
-//!
-//! - Aliases call `execute_shell_command` (the unified streaming executor),
-//! which is *blocking* — it streams stdout/stderr to the terminal and only
-//! returns once the child exits. Concurrency therefore needs OS threads
-//! (`thread::scope`), one thread per command.
-//! - The background pipeline runner spawns shell processes directly with
-//! stdout/stderr redirected to per-command log files. The `Child` handle is
-//! the concurrency primitive — no threads needed.
-//!
-//! Bridging the two would require either making `execute_shell_command`
-//! return a non-blocking handle (invasive — entangles signal forwarding,
-//! ANSI reset, and `Cmd` streaming), or running background commands in
-//! threads they don't need. Neither pays for the abstraction. The pipeline
-//! summary formatter, on the other hand, is shared via
-//! `hooks::format_pipeline_summary_from_names`.
+//! Foreground execution (aliases + foreground hooks) uses `execute_shell_command`
+//! which streams stdout/stderr to the terminal. Concurrency needs OS threads
+//! (`thread::scope`), one per command. Background pipeline execution spawns
+//! shell processes with stdout/stderr redirected to log files — no threads
+//! needed. The two share preparation (`PreparedStep`) but not execution.
//!
//! ## Trust model
//!
@@ -45,23 +30,23 @@
//! the EXEC directive file is scrubbed so alias bodies cannot inject
//! arbitrary shell into the interactive session.
-use std::collections::{BTreeMap, HashMap};
+use std::collections::BTreeMap;
use anyhow::{Context, bail};
use color_print::cformat;
use worktrunk::config::{CommandConfig, HookStep, ProjectConfig, UserConfig, append_aliases};
-use worktrunk::git::{Repository, WorktrunkError};
+use worktrunk::git::Repository;
use worktrunk::styling::{
eprintln, format_bash_with_gutter, info_message, progress_message, warning_message,
};
use crate::commands::command_approval::approve_alias_commands;
use crate::commands::command_executor::{
- CommandContext, build_hook_context, expand_shell_template, wait_first_error,
+ CommandContext, CommandOrigin, FailureStrategy, ForegroundStep, PreparedCommand, PreparedStep,
+ build_hook_context, execute_pipeline_foreground, expand_shell_template,
};
-use crate::commands::force_serial_concurrent;
use crate::commands::hooks::format_pipeline_summary_from_names;
-use crate::output::{DirectivePassthrough, execute_shell_command};
+use crate::output::DirectivePassthrough;
/// Built-in `wt step` subcommand names. Aliases with these names are
/// shadowed by the built-in and will never run.
@@ -358,85 +343,53 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {
// CD passed through, EXEC scrubbed (see `output::global` for rationale).
let directives = DirectivePassthrough::inherit_from_env();
- let exec = AliasExecCtx {
- context_map: &context_map,
- repo: &repo,
- alias_name: &opts.name,
- wt_path: &wt_path,
- context_json: &context_json,
- directives: &directives,
+ // Build ForegroundSteps: all alias commands use lazy expansion so vars.*
+ // references resolved from git config at execution time are visible to
+ // later steps that set vars via `wt config state vars set`.
+ let origin = CommandOrigin::Alias {
+ name: opts.name.clone(),
};
-
- for step in cmd_config.steps() {
- match step {
- HookStep::Single(cmd) => exec.run(cmd)?,
- HookStep::Concurrent(cmds) => {
- if force_serial_concurrent() {
- // Test-only path: deterministic ordering for snapshots.
- for cmd in cmds {
- exec.run(cmd)?;
- }
- } else {
- std::thread::scope(|s| {
- let handles: Vec<_> =
- cmds.iter().map(|cmd| s.spawn(|| exec.run(cmd))).collect();
- wait_first_error(
- handles
- .into_iter()
- .map(|h| h.join().expect("alias command thread panicked")),
- )
- })?;
+ let foreground_steps: Vec<ForegroundStep> = cmd_config
+ .steps()
+ .iter()
+ .map(|step| {
+ let prepared = match step {
+ HookStep::Single(cmd) => {
+ PreparedStep::Single(alias_prepared_command(cmd, &context_json))
}
+ HookStep::Concurrent(cmds) => PreparedStep::Concurrent(
+ cmds.iter()
+ .map(|cmd| alias_prepared_command(cmd, &context_json))
+ .collect(),
+ ),
+ };
+ ForegroundStep {
+ step: prepared,
+ origin: origin.clone(),
}
- }
- }
-
- Ok(())
-}
+ })
+ .collect();
-/// Shared state for executing alias commands within a pipeline.
-struct AliasExecCtx<'a> {
- context_map: &'a HashMap<String, String>,
- repo: &'a Repository,
- alias_name: &'a str,
- wt_path: &'a std::path::Path,
- context_json: &'a str,
- directives: &'a DirectivePassthrough,
+ execute_pipeline_foreground(
+ &foreground_steps,
+ &repo,
+ &wt_path,
+ &directives,
+ FailureStrategy::FailFast,
+ true, // aliases support concurrent execution
+ )
}
-impl AliasExecCtx<'_> {
- /// Expand and execute a single alias command.
- ///
- /// `vars.*` references are resolved from git config at expansion time,
- /// so prior pipeline steps that set vars via `wt config state vars set`
- /// are visible to later steps without special lazy-expansion handling.
- fn run(&self, cmd: &worktrunk::config::Command) -> anyhow::Result<()> {
- let command =
- expand_shell_template(&cmd.template, self.context_map, self.repo, self.alias_name)?;
- if let Err(err) = execute_shell_command(
- self.wt_path,
- &command,
- Some(self.context_json),
- None,
- self.directives.clone(),
- ) {
- if let Some(WorktrunkError::ChildProcessExited { code, .. }) =
- err.downcast_ref::<WorktrunkError>()
- {
- return Err(WorktrunkError::AlreadyDisplayed { exit_code: *code }.into());
- }
- bail!("Failed to run alias '{}': {}", self.alias_name, err);
- }
- Ok(())
+/// Build a PreparedCommand for an alias, deferring template expansion to execution time.
+fn alias_prepared_command(cmd: &worktrunk::config::Command, context_json: &str) -> PreparedCommand {
+ PreparedCommand {
+ name: cmd.name.clone(),
+ expanded: cmd.template.clone(),
+ context_json: context_json.to_string(),
+ lazy_template: Some(cmd.template.clone()),
}
}
-/// Render `wt step` help and list any configured aliases.
-///
-/// Invoked when `wt step` is run with no subcommand — gives users one place
-/// to discover both built-in steps and aliases. Unlike `step_alias`, this
-/// tolerates running outside a repository: user-config aliases still list,
-/// project-config aliases just get skipped.
pub(crate) fn step_list() -> anyhow::Result<()> {
// Route through clap's own `-h` error path so styles, display_name, and
// global settings (`disable_help_subcommand`, etc.) are propagated from
@@ -638,58 +591,6 @@ test = "cargo test"
insta::assert_snapshot!(msg.ansi_strip(), @"Running alias check: build, test");
}
- #[test]
- fn test_format_alias_summary_single_command() {
- let cfg = cfg_from_toml(r#"cmd = "echo hello""#);
- assert_eq!(format_alias_summary(&cfg), "echo hello");
- }
-
- #[test]
- fn test_format_alias_summary_multiline_gets_ellipsis() {
- let cfg = cfg_from_toml(
- r#"cmd = """
-git fetch --all --prune
-git rebase @{u}
-""""#,
- );
- assert_eq!(format_alias_summary(&cfg), "git fetch --all --prune…");
- }
-
- #[test]
- fn test_format_alias_summary_pipeline_named() {
- let cfg = cfg_from_toml(
- r#"
-cmd = [
- { install = "npm install" },
- { build = "npm run build", lint = "npm run lint" },
-]
-"#,
- );
- assert_eq!(format_alias_summary(&cfg), "install; build, lint");
- }
-
- #[test]
- fn test_format_alias_summary_concurrent_named() {
- // Single-step concurrent form: `[aliases.check]\nbuild=…\ntest=…`
- // — one step, multiple commands. Must use the pipeline formatter,
- // not fall back to "show first command's template".
- let cfg = cfg_from_toml(
- r#"
-[cmd]
-build = "cargo build"
-test = "cargo test"
-"#,
- );
- assert_eq!(format_alias_summary(&cfg), "build, test");
- }
-
- #[test]
- fn test_format_alias_summary_pipeline_all_unnamed() {
- // Anonymous pipeline entries fall back to a step count.
- let cfg = cfg_from_toml(r#"cmd = ["echo a", "echo b"]"#);
- assert_eq!(format_alias_summary(&cfg), "<2 steps>");
- }
-
#[test]
fn test_format_alias_announcement_pipeline_named() {
// Pipeline: serial named step then concurrent named step.
@@ -1036,4 +937,56 @@ cmd = [
);
}
}
+
+ #[test]
+ fn test_format_alias_summary_single_command() {
+ let cfg = cfg_from_toml(r#"cmd = "echo hello""#);
+ assert_eq!(format_alias_summary(&cfg), "echo hello");
+ }
+
+ #[test]
+ fn test_format_alias_summary_multiline_gets_ellipsis() {
+ let cfg = cfg_from_toml(
+ r#"cmd = """
+git fetch --all --prune
+git rebase @{u}
+""""#,
+ );
+ assert_eq!(format_alias_summary(&cfg), "git fetch --all --prune…");
+ }
+
+ #[test]
+ fn test_format_alias_summary_pipeline_named() {
+ let cfg = cfg_from_toml(
+ r#"
+cmd = [
+ { install = "npm install" },
+ { build = "npm run build", lint = "npm run lint" },
+]
+"#,
+ );
+ assert_eq!(format_alias_summary(&cfg), "install; build, lint");
+ }
+
+ #[test]
+ fn test_format_alias_summary_concurrent_named() {
+ // Single-step concurrent form: `[aliases.check]\nbuild=…\ntest=…`
+ // — one step, multiple commands. Must use the pipeline formatter,
+ // not fall back to "show first command's template".
+ let cfg = cfg_from_toml(
+ r#"
+[cmd]
+build = "cargo build"
+test = "cargo test"
+"#,
+ );
+ assert_eq!(format_alias_summary(&cfg), "build, test");
+ }
+
+ #[test]
+ fn test_format_alias_summary_pipeline_all_unnamed() {
+ // Anonymous pipeline entries fall back to a step count.
+ let cfg = cfg_from_toml(r#"cmd = ["echo a", "echo b"]"#);
+ assert_eq!(format_alias_summary(&cfg), "<2 steps>");
+ }
}
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 0c02e3336..fcf33911c 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -1,14 +1,20 @@
-use anyhow::Result;
use std::collections::HashMap;
-use std::path::Path;
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result, bail};
+use color_print::cformat;
use worktrunk::HookType;
use worktrunk::config::{
Command, CommandConfig, HookStep, UserConfig, expand_template, template_references_var,
};
-use worktrunk::git::Repository;
-use worktrunk::path::to_posix_path;
+use worktrunk::git::{Repository, WorktrunkError};
+use worktrunk::path::{format_path_for_display, to_posix_path};
+use worktrunk::styling::{eprintln, error_message, format_bash_with_gutter, progress_message};
+use super::force_serial_concurrent;
+use super::format_command_label;
use super::hook_filter::HookSource;
+use crate::output::{DirectivePassthrough, execute_shell_command};
#[derive(Debug)]
pub struct PreparedCommand {
@@ -37,6 +43,37 @@ impl PreparedStep {
}
}
+/// Where a foreground command originated — determines announcement format,
+/// error wrapping, and log label.
+#[derive(Clone, Debug)]
+pub enum CommandOrigin {
+ /// Hook command with source attribution.
+ Hook {
+ source: HookSource,
+ hook_type: HookType,
+ /// Path shown in announcement when commands run in a different directory
+ /// than where the user invoked the command.
+ display_path: Option<PathBuf>,
+ },
+ /// Alias command.
+ Alias { name: String },
+}
+
+/// A pipeline step ready for foreground execution, with origin metadata.
+pub struct ForegroundStep {
+ pub step: PreparedStep,
+ pub origin: CommandOrigin,
+}
+
+/// Controls how foreground execution responds to command failures.
+#[derive(Clone, Copy)]
+pub enum FailureStrategy {
+ /// Stop on first failure and surface the error to the caller.
+ FailFast,
+ /// Log warnings and continue executing remaining commands.
+ Warn,
+}
+
#[derive(Clone, Copy, Debug)]
pub struct CommandContext<'a> {
pub repo: &'a Repository,
@@ -220,6 +257,232 @@ pub fn expand_shell_template(
Ok(expand_template(template, &vars, true, repo, label)?)
}
+/// Short summary name: "user:name" for named commands, "user" otherwise.
+pub(crate) fn command_summary_name(name: Option<&str>, source: HookSource) -> String {
+ match name {
+ Some(n) => format!("{source}:{n}"),
+ None => source.to_string(),
+ }
+}
+
+/// Execute a pipeline of prepared steps in the foreground.
+///
+/// This is the canonical foreground execution path for both hooks and aliases.
+/// Handles serial/concurrent step execution, per-command announcement, lazy
+/// template resolution, and origin-aware error handling.
+///
+/// When `concurrent` is true, `Concurrent` steps spawn threads via
+/// `thread::scope`. When false (foreground hooks), `Concurrent` steps execute
+/// serially — a compat fallback for the **deprecated** pre-hook table form.
+/// The canonical pre-* hook shape is a list of `Single` steps; concurrent
+/// execution is reserved for aliases and the background pipeline runner.
+///
+/// TODO(unify-hook-alias): this function centralized dispatch but left four
+/// per-origin branch points. Follow-ups to collapse them:
+/// 1. Unify the error type: one `CommandFailed { origin_label, exit_code,
+/// message }` lets `handle_command_error` drop its origin match.
+/// 2. Unify announcement policy (decide per-command vs single-summary for
+/// both); `announce_command`'s dispatch disappears.
+/// 3. Push log/expansion labels onto `PreparedCommand` at prep time so
+/// `command_log_label` / `expansion_label` go away.
+/// 4. Longer term: treat hooks as aliases bound to triggers so `hooks.rs`
+/// becomes a trigger-dispatcher + config loader over the alias machinery.
+pub fn execute_pipeline_foreground(
+ steps: &[ForegroundStep],
+ repo: &Repository,
+ wt_path: &Path,
+ directives: &DirectivePassthrough,
+ failure_strategy: FailureStrategy,
+ concurrent: bool,
+) -> anyhow::Result<()> {
+ for fg_step in steps {
+ match &fg_step.step {
+ PreparedStep::Single(cmd) => {
+ run_one_command(
+ cmd,
+ &fg_step.origin,
+ repo,
+ wt_path,
+ directives,
+ failure_strategy,
+ )?;
+ }
+ PreparedStep::Concurrent(cmds) => {
+ if !concurrent || force_serial_concurrent() {
+ for cmd in cmds {
+ run_one_command(
+ cmd,
+ &fg_step.origin,
+ repo,
+ wt_path,
+ directives,
+ failure_strategy,
+ )?;
+ }
+ } else {
+ std::thread::scope(|s| {
+ let origin = &fg_step.origin;
+ let handles: Vec<_> = cmds
+ .iter()
+ .map(|cmd| {
+ s.spawn(|| {
+ run_one_command(
+ cmd,
+ origin,
+ repo,
+ wt_path,
+ directives,
+ failure_strategy,
+ )
+ })
+ })
+ .collect();
+ wait_first_error(
+ handles
+ .into_iter()
+ .map(|h| h.join().expect("command thread panicked")),
+ )
+ })?;
+ }
+ }
+ }
+ }
+ Ok(())
+}
+
+/// Execute a single prepared command: announce, expand, run, handle errors.
+fn run_one_command(
+ cmd: &PreparedCommand,
+ origin: &CommandOrigin,
+ repo: &Repository,
+ wt_path: &Path,
+ directives: &DirectivePassthrough,
+ failure_strategy: FailureStrategy,
+) -> anyhow::Result<()> {
+ announce_command(cmd, origin);
+
+ let lazy_expanded;
+ let command_str = if let Some(template) = &cmd.lazy_template {
+ let label = expansion_label(cmd, origin);
+ let context: HashMap<String, String> = serde_json::from_str(&cmd.context_json)
+ .context("failed to deserialize context_json")?;
+ lazy_expanded = expand_shell_template(template, &context, repo, &label)?;
+ &lazy_expanded
+ } else {
+ &cmd.expanded
+ };
+
+ let log_label = command_log_label(cmd, origin);
+ let result = execute_shell_command(
+ wt_path,
+ command_str,
+ Some(&cmd.context_json),
+ log_label.as_deref(),
+ directives.clone(),
+ );
+
+ match result {
+ Ok(()) => Ok(()),
+ Err(err) => handle_command_error(err, cmd, origin, failure_strategy),
+ }
+}
+
+/// Announce a command before execution, formatted per origin.
+///
+/// Hooks get per-command announcements with the expanded command in a gutter.
+/// Aliases show a single summary line before the pipeline (in the caller),
+/// so no per-command announcement here.
+fn announce_command(cmd: &PreparedCommand, origin: &CommandOrigin) {
+ match origin {
+ CommandOrigin::Hook {
+ source,
+ hook_type,
+ display_path,
+ } => {
+ let summary = command_summary_name(cmd.name.as_deref(), *source);
+ let full_label = match &cmd.name {
+ Some(_) => format_command_label(&hook_type.to_string(), Some(&summary)),
+ None => format!("Running {hook_type} {summary} hook"),
+ };
+ let message = match display_path.as_deref() {
+ Some(path) => {
+ let path_display = format_path_for_display(path);
+ cformat!("{full_label} @ <bold>{path_display}</>")
+ }
+ None => full_label,
+ };
+ eprintln!("{}", progress_message(message));
+ eprintln!("{}", format_bash_with_gutter(&cmd.expanded));
+ }
+ CommandOrigin::Alias { .. } => {}
+ }
+}
+
+/// Log label for command tracing: "pre-merge user:foo" for hooks, None for aliases.
+fn command_log_label(cmd: &PreparedCommand, origin: &CommandOrigin) -> Option<String> {
+ match origin {
+ CommandOrigin::Hook {
+ source, hook_type, ..
+ } => {
+ let summary = command_summary_name(cmd.name.as_deref(), *source);
+ Some(format!("{hook_type} {summary}"))
+ }
+ CommandOrigin::Alias { .. } => None,
+ }
+}
+
+/// Label used for template expansion error messages.
+fn expansion_label(cmd: &PreparedCommand, origin: &CommandOrigin) -> String {
+ match origin {
+ CommandOrigin::Hook { source, .. } => command_summary_name(cmd.name.as_deref(), *source),
+ CommandOrigin::Alias { name } => name.clone(),
+ }
+}
+
+/// Handle a command execution error per origin and failure strategy.
+fn handle_command_error(
+ err: anyhow::Error,
+ cmd: &PreparedCommand,
+ origin: &CommandOrigin,
+ failure_strategy: FailureStrategy,
+) -> anyhow::Result<()> {
+ let (err_msg, exit_code) = if let Some(wt_err) = err.downcast_ref::<WorktrunkError>() {
+ match wt_err {
+ WorktrunkError::ChildProcessExited { message, code } => (message.clone(), Some(*code)),
+ _ => (err.to_string(), None),
+ }
+ } else {
+ (err.to_string(), None)
+ };
+
+ match failure_strategy {
+ FailureStrategy::FailFast => match origin {
+ CommandOrigin::Hook { hook_type, .. } => Err(WorktrunkError::HookCommandFailed {
+ hook_type: *hook_type,
+ command_name: cmd.name.clone(),
+ error: err_msg,
+ exit_code,
+ }
+ .into()),
+ CommandOrigin::Alias { name } => {
+ if let Some(code) = exit_code {
+ Err(WorktrunkError::AlreadyDisplayed { exit_code: code }.into())
+ } else {
+ bail!("Failed to run alias '{}': {}", name, err_msg)
+ }
+ }
+ },
+ FailureStrategy::Warn => {
+ let message = match &cmd.name {
+ Some(name) => cformat!("Command <bold>{name}</> failed: {err_msg}"),
+ None => format!("Command failed: {err_msg}"),
+ };
+ eprintln!("{}", error_message(message));
+ Ok(())
+ }
+ }
+}
+
/// Expand commands from a CommandConfig without approval.
///
/// When `lazy_enabled` is true, commands referencing `vars.` are validated but not
@@ -353,6 +616,179 @@ pub fn prepare_steps(
mod tests {
use super::*;
+ fn make_cmd(name: Option<&str>) -> PreparedCommand {
+ PreparedCommand {
+ name: name.map(String::from),
+ expanded: "echo test".to_string(),
+ context_json: "{}".to_string(),
+ lazy_template: None,
+ }
+ }
+
+ #[test]
+ fn test_handle_command_error_hook_failfast_child_process_exited() {
+ let err: anyhow::Error = WorktrunkError::ChildProcessExited {
+ code: 42,
+ message: "command failed".into(),
+ }
+ .into();
+ let cmd = make_cmd(Some("lint"));
+ let origin = CommandOrigin::Hook {
+ source: HookSource::User,
+ hook_type: HookType::PreMerge,
+ display_path: None,
+ };
+ let result = handle_command_error(err, &cmd, &origin, FailureStrategy::FailFast);
+ let err = result.unwrap_err();
+ let wt_err = err.downcast_ref::<WorktrunkError>().unwrap();
+ assert!(matches!(
+ wt_err,
+ WorktrunkError::HookCommandFailed {
+ exit_code: Some(42),
+ ..
+ }
+ ));
+ }
+
+ #[test]
+ fn test_handle_command_error_hook_failfast_non_child_worktrunk_error() {
+ // WorktrunkError that isn't ChildProcessExited (line 439 coverage)
+ let err: anyhow::Error = WorktrunkError::CommandNotApproved.into();
+ let cmd = make_cmd(Some("build"));
+ let origin = CommandOrigin::Hook {
+ source: HookSource::User,
+ hook_type: HookType::PreMerge,
+ display_path: None,
+ };
+ let result = handle_command_error(err, &cmd, &origin, FailureStrategy::FailFast);
+ let err = result.unwrap_err();
+ let wt_err = err.downcast_ref::<WorktrunkError>().unwrap();
+ assert!(matches!(
+ wt_err,
+ WorktrunkError::HookCommandFailed {
+ exit_code: None,
+ ..
+ }
+ ));
+ }
+
+ #[test]
+ fn test_handle_command_error_hook_failfast_other_error() {
+ let err = anyhow::anyhow!("something else");
+ let cmd = make_cmd(None);
+ let origin = CommandOrigin::Hook {
+ source: HookSource::Project,
+ hook_type: HookType::PreCommit,
+ display_path: None,
+ };
+ let result = handle_command_error(err, &cmd, &origin, FailureStrategy::FailFast);
+ let err = result.unwrap_err();
+ let wt_err = err.downcast_ref::<WorktrunkError>().unwrap();
+ assert!(matches!(
+ wt_err,
+ WorktrunkError::HookCommandFailed {
+ exit_code: None,
+ ..
+ }
+ ));
+ }
+
+ #[test]
+ fn test_handle_command_error_alias_failfast_child_process_exited() {
+ let err: anyhow::Error = WorktrunkError::ChildProcessExited {
+ code: 1,
+ message: "exit 1".into(),
+ }
+ .into();
+ let cmd = make_cmd(None);
+ let origin = CommandOrigin::Alias {
+ name: "deploy".into(),
+ };
+ let result = handle_command_error(err, &cmd, &origin, FailureStrategy::FailFast);
+ let err = result.unwrap_err();
+ let wt_err = err.downcast_ref::<WorktrunkError>().unwrap();
+ assert!(matches!(
+ wt_err,
+ WorktrunkError::AlreadyDisplayed { exit_code: 1 }
+ ));
+ }
+
+ #[test]
+ fn test_handle_command_error_alias_failfast_other_error() {
+ let err = anyhow::anyhow!("template error");
+ let cmd = make_cmd(None);
+ let origin = CommandOrigin::Alias {
+ name: "deploy".into(),
+ };
+ let result = handle_command_error(err, &cmd, &origin, FailureStrategy::FailFast);
+ let err_msg = result.unwrap_err().to_string();
+ assert!(err_msg.contains("Failed to run alias 'deploy'"));
+ assert!(err_msg.contains("template error"));
+ }
+
+ #[test]
+ fn test_handle_command_error_warn_continues() {
+ let err: anyhow::Error = WorktrunkError::ChildProcessExited {
+ code: 1,
+ message: "lint failed".into(),
+ }
+ .into();
+ let cmd = make_cmd(Some("lint"));
+ let origin = CommandOrigin::Hook {
+ source: HookSource::User,
+ hook_type: HookType::PostStart,
+ display_path: None,
+ };
+ let result = handle_command_error(err, &cmd, &origin, FailureStrategy::Warn);
+ assert!(result.is_ok());
+ }
+
+ #[test]
+ fn test_handle_command_error_warn_unnamed() {
+ let err = anyhow::anyhow!("unexpected failure");
+ let cmd = make_cmd(None);
+ let origin = CommandOrigin::Hook {
+ source: HookSource::User,
+ hook_type: HookType::PostStart,
+ display_path: None,
+ };
+ let result = handle_command_error(err, &cmd, &origin, FailureStrategy::Warn);
+ assert!(result.is_ok());
+ }
+
+ #[test]
+ fn test_command_log_label() {
+ let cmd = make_cmd(Some("lint"));
+ let hook_origin = CommandOrigin::Hook {
+ source: HookSource::User,
+ hook_type: HookType::PreMerge,
+ display_path: None,
+ };
+ assert_eq!(
+ command_log_label(&cmd, &hook_origin),
+ Some("pre-merge user:lint".to_string())
+ );
+
+ let alias_origin = CommandOrigin::Alias {
+ name: "deploy".into(),
+ };
+ assert_eq!(command_log_label(&cmd, &alias_origin), None);
+ }
+
+ #[test]
+ fn test_expansion_label() {
+ let cmd = make_cmd(Some("build"));
+ let hook_origin = CommandOrigin::Hook {
+ source: HookSource::Project,
+ hook_type: HookType::PreStart,
+ display_path: None,
+ };
+ assert_eq!(expansion_label(&cmd, &hook_origin), "project:build");
+
+ let alias_origin = CommandOrigin::Alias { name: "ci".into() };
+ assert_eq!(expansion_label(&cmd, &alias_origin), "ci");
+ }
+
#[test]
fn test_template_references_var_for_vars() {
// Real vars references
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index b504840a1..1917aac47 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -7,9 +7,8 @@ use worktrunk::styling::{
};
use super::command_executor::CommandContext;
-use super::hooks::{
- HookCommandSpec, HookFailureStrategy, prepare_background_hooks, spawn_hook_pipeline,
-};
+use super::command_executor::FailureStrategy;
+use super::hooks::{HookCommandSpec, prepare_background_hooks, spawn_hook_pipeline};
use super::repository_ext::warn_about_untracked_files;
// Re-export StageMode from config for use by CLI
@@ -189,7 +188,7 @@ impl CommitOptions<'_> {
name_filters: &[],
display_path: crate::output::pre_hook_display_path(self.ctx.worktree_path),
},
- HookFailureStrategy::FailFast,
+ FailureStrategy::FailFast,
)
.map_err(worktrunk::git::add_hook_skip_hint)?;
}
diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rs
index ac5f0e83b..3c65457c8 100644
--- a/src/commands/handle_switch.rs
+++ b/src/commands/handle_switch.rs
@@ -13,8 +13,9 @@ use worktrunk::styling::{eprintln, info_message};
use crate::cli::SwitchFormat;
use super::command_approval::approve_hooks;
+use super::command_executor::FailureStrategy;
use super::command_executor::{CommandContext, build_hook_context};
-use super::hooks::{HookFailureStrategy, execute_hook};
+use super::hooks::execute_hook;
use super::worktree::{
SwitchBranchInfo, SwitchPlan, SwitchResult, execute_switch, offer_bare_repo_worktree_path_fix,
path_mismatch, plan_switch,
@@ -147,7 +148,7 @@ pub(crate) fn run_pre_switch_hooks(
&pre_ctx,
HookType::PreSwitch,
&extra_vars,
- HookFailureStrategy::FailFast,
+ FailureStrategy::FailFast,
&[],
crate::output::pre_hook_display_path(pre_ctx.worktree_path),
)?;
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index 04d23ec93..4b001da55 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -25,12 +25,12 @@ use super::command_approval::approve_hooks_filtered;
use super::command_executor::build_hook_context;
use super::command_executor::CommandContext;
+use super::command_executor::{FailureStrategy, command_summary_name};
use super::context::CommandEnv;
use super::hook_filter::{HookSource, ParsedFilter};
use super::hooks::{
- HookCommandSpec, HookFailureStrategy, check_name_filter_matched, command_summary_name,
- count_sourced_commands, prepare_background_hooks, prepare_sourced_steps, run_hook_with_filter,
- spawn_hook_pipeline,
+ HookCommandSpec, check_name_filter_matched, count_sourced_commands, prepare_background_hooks,
+ prepare_sourced_steps, run_hook_with_filter, spawn_hook_pipeline,
};
use super::project_config::collect_commands_for_hooks;
@@ -41,7 +41,7 @@ fn run_filtered_hook(
hook_type: HookType,
extra_vars: &[(&str, &str)],
name_filters: &[String],
- failure_strategy: HookFailureStrategy,
+ failure_strategy: FailureStrategy,
) -> anyhow::Result<()> {
run_hook_with_filter(
ctx,
@@ -103,7 +103,7 @@ fn run_post_hook(
hook_type,
extra_vars,
name_filters,
- HookFailureStrategy::Warn,
+ FailureStrategy::Warn,
)
}
@@ -370,7 +370,7 @@ pub fn run_hook(
hook_type,
&extra_vars,
name_filters,
- HookFailureStrategy::FailFast,
+ FailureStrategy::FailFast,
),
HookType::PostStart
| HookType::PostSwitch
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index bc3771628..91e568f92 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -4,60 +4,15 @@ use anyhow::Context;
use color_print::cformat;
use worktrunk::HookType;
use worktrunk::config::CommandConfig;
-use worktrunk::git::WorktrunkError;
use worktrunk::path::format_path_for_display;
-use worktrunk::styling::{
- eprintln, error_message, format_bash_with_gutter, progress_message, warning_message,
-};
+use worktrunk::styling::{eprintln, progress_message, warning_message};
use super::command_executor::{
- CommandContext, PreparedCommand, PreparedStep, expand_shell_template, prepare_steps,
+ CommandContext, CommandOrigin, FailureStrategy, ForegroundStep, PreparedCommand, PreparedStep,
+ execute_pipeline_foreground, prepare_steps,
};
use crate::commands::process::{HookLog, spawn_detached_exec};
-use crate::output::{DirectivePassthrough, execute_shell_command};
-
-/// Short summary name: "user:name" for named commands, "user" otherwise.
-pub(crate) fn command_summary_name(name: Option<&str>, source: HookSource) -> String {
- match name {
- Some(n) => format!("{source}:{n}"),
- None => source.to_string(),
- }
-}
-
-/// Announce a hook command before execution.
-///
-/// Format: "Running pre-merge user:foo" for named, "Running pre-start user hook" for unnamed.
-/// When `display_path` is set, appends "@ path" to show where the command runs.
-fn announce_hook_command(
- cmd: &PreparedCommand,
- source: HookSource,
- hook_type: HookType,
- display_path: Option<&Path>,
-) {
- let summary = command_summary_name(cmd.name.as_deref(), source);
- let full_label = match &cmd.name {
- Some(_) => crate::commands::format_command_label(&hook_type.to_string(), Some(&summary)),
- None => format!("Running {hook_type} {summary} hook"),
- };
- let message = match display_path {
- Some(path) => {
- let path_display = format_path_for_display(path);
- cformat!("{full_label} @ <bold>{path_display}</>")
- }
- None => full_label,
- };
- eprintln!("{}", progress_message(message));
- eprintln!("{}", format_bash_with_gutter(&cmd.expanded));
-}
-
-/// Controls how hook execution should respond to failures.
-#[derive(Clone, Copy)]
-pub enum HookFailureStrategy {
- /// Stop on first failure and surface a `HookCommandFailed` error.
- FailFast,
- /// Log warnings and continue executing remaining commands.
- Warn,
-}
+use crate::output::DirectivePassthrough;
// Re-export for backward compatibility with existing imports
pub use super::hook_filter::{HookSource, ParsedFilter};
@@ -523,7 +478,7 @@ pub(crate) fn check_name_filter_matched(
pub fn run_hook_with_filter(
ctx: &CommandContext,
spec: HookCommandSpec<'_, '_, '_, '_>,
- failure_strategy: HookFailureStrategy,
+ failure_strategy: FailureStrategy,
) -> anyhow::Result<()> {
let sourced_steps = prepare_sourced_steps(ctx, spec)?;
let HookCommandSpec {
@@ -544,91 +499,34 @@ pub fn run_hook_with_filter(
return Ok(());
}
- // CD passed through, EXEC scrubbed (see `output::global` for rationale).
let directives = DirectivePassthrough::inherit_from_env();
- // Foreground hooks always execute serially, even when the prepared step is
- // `Concurrent`. The documented contract is "for pre-* hooks, commands in a
- // table run sequentially" (`src/cli/mod.rs`). Concurrent execution is
- // reserved for the background pipeline runner (`run_pipeline.rs`).
- for sourced in sourced_steps {
- let display_path_ref = sourced.display_path.as_deref();
- for cmd in &sourced.step.into_commands() {
- announce_hook_command(cmd, sourced.source, sourced.hook_type, display_path_ref);
- execute_one_hook_command(
- ctx,
- cmd,
- sourced.source,
- sourced.hook_type,
- &directives,
- failure_strategy,
- )?;
- }
- }
-
- Ok(())
-}
-
-/// Execute a single prepared hook command (caller has already announced it).
-fn execute_one_hook_command(
- ctx: &CommandContext,
- cmd: &PreparedCommand,
- source: HookSource,
- hook_type: HookType,
- directives: &DirectivePassthrough,
- failure_strategy: HookFailureStrategy,
-) -> anyhow::Result<()> {
- let summary = command_summary_name(cmd.name.as_deref(), source);
-
- let lazy_expanded;
- let command_str = if let Some(template) = &cmd.lazy_template {
- let context: std::collections::HashMap<String, String> =
- serde_json::from_str(&cmd.context_json)
- .context("failed to deserialize context_json")?;
- lazy_expanded = expand_shell_template(template, &context, ctx.repo, &summary)?;
- &lazy_expanded
- } else {
- &cmd.expanded
- };
-
- let log_label = format!("{hook_type} {summary}");
+ // Convert SourcedSteps → ForegroundSteps for the shared executor.
+ let foreground_steps: Vec<ForegroundStep> = sourced_steps
+ .into_iter()
+ .map(|sourced| ForegroundStep {
+ step: sourced.step,
+ origin: CommandOrigin::Hook {
+ source: sourced.source,
+ hook_type: sourced.hook_type,
+ display_path: sourced.display_path,
+ },
+ })
+ .collect();
- let Err(err) = execute_shell_command(
+ // Foreground hooks always execute serially, even when the prepared step is
+ // `Concurrent`. That input shape is the deprecated pre-hook table form — we
+ // still accept it but run it sequentially ("for pre-* hooks, commands in a
+ // table run sequentially", `src/cli/mod.rs`). Concurrent execution is
+ // reserved for aliases and the background pipeline runner (`run_pipeline.rs`).
+ execute_pipeline_foreground(
+ &foreground_steps,
+ ctx.repo,
ctx.worktree_path,
- command_str,
- Some(&cmd.context_json),
- Some(&log_label),
- directives.clone(),
- ) else {
- return Ok(());
- };
-
- let (err_msg, exit_code) = if let Some(wt_err) = err.downcast_ref::<WorktrunkError>() {
- match wt_err {
- WorktrunkError::ChildProcessExited { message, code } => (message.clone(), Some(*code)),
- _ => (err.to_string(), None),
- }
- } else {
- (err.to_string(), None)
- };
-
- match failure_strategy {
- HookFailureStrategy::FailFast => Err(WorktrunkError::HookCommandFailed {
- hook_type,
- command_name: cmd.name.clone(),
- error: err_msg,
- exit_code,
- }
- .into()),
- HookFailureStrategy::Warn => {
- let message = match &cmd.name {
- Some(name) => cformat!("Command <bold>{name}</> failed: {err_msg}"),
- None => format!("Command failed: {err_msg}"),
- };
- eprintln!("{}", error_message(message));
- Ok(())
- }
- }
+ &directives,
+ failure_strategy,
+ false,
+ )
}
/// Look up user and project configs for a given hook type.
@@ -656,7 +554,7 @@ pub fn execute_hook(
ctx: &CommandContext,
hook_type: HookType,
extra_vars: &[(&str, &str)],
- failure_strategy: HookFailureStrategy,
+ failure_strategy: FailureStrategy,
name_filters: &[String],
display_path: Option<&Path>,
) -> anyhow::Result<()> {
@@ -740,14 +638,14 @@ mod tests {
}
#[test]
- fn test_hook_failure_strategy_copy() {
- let strategy = HookFailureStrategy::FailFast;
+ fn test_failure_strategy_copy() {
+ let strategy = FailureStrategy::FailFast;
let copied = strategy; // Copy trait
- assert!(matches!(copied, HookFailureStrategy::FailFast));
+ assert!(matches!(copied, FailureStrategy::FailFast));
- let warn = HookFailureStrategy::Warn;
+ let warn = FailureStrategy::Warn;
let copied_warn = warn;
- assert!(matches!(copied_warn, HookFailureStrategy::Warn));
+ assert!(matches!(copied_warn, FailureStrategy::Warn));
}
#[test]
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 54888bddc..3d59ccafc 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -6,11 +6,10 @@ 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::context::CommandEnv;
-use super::hooks::{
- HookFailureStrategy, execute_hook, prepare_background_hooks, spawn_hook_pipeline,
-};
+use super::hooks::{execute_hook, prepare_background_hooks, spawn_hook_pipeline};
use super::project_config::{ApprovableCommand, collect_commands_for_hooks};
use super::repository_ext::{
RepositoryCliExt, check_not_default_branch, compute_integration_reason, is_primary_worktree,
@@ -239,7 +238,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
&ctx,
HookType::PreMerge,
&extra,
- HookFailureStrategy::FailFast,
+ FailureStrategy::FailFast,
&[],
crate::output::pre_hook_display_path(ctx.worktree_path),
)?;
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index d27272ab8..676035503 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -24,12 +24,11 @@ use skim::reader::CommandCollector;
use worktrunk::git::{Repository, current_or_recover};
use super::branch_deletion::delete_branch_if_safe;
+use super::command_executor::FailureStrategy;
use super::handle_switch::{
approve_switch_hooks, run_pre_switch_hooks, spawn_switch_background_hooks, switch_extra_vars,
};
-use super::hooks::{
- HookFailureStrategy, execute_hook, prepare_background_hooks, spawn_hook_pipeline,
-};
+use super::hooks::{execute_hook, prepare_background_hooks, spawn_hook_pipeline};
use super::list::collect;
use super::repository_ext::{RemoveTarget, RepositoryCliExt};
use super::worktree::hooks::PostRemoveContext;
@@ -116,7 +115,7 @@ impl PickerCollector {
&pre_ctx,
worktrunk::HookType::PreRemove,
&extra_vars,
- HookFailureStrategy::FailFast,
+ FailureStrategy::FailFast,
&[],
None, // no display path in TUI context
)?;
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index 4348026ca..a37c03efd 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -35,11 +35,11 @@ use worktrunk::styling::{
};
use super::command_approval::approve_hooks;
+use super::command_executor::FailureStrategy;
use super::commit::{CommitGenerator, CommitOptions, StageMode};
use super::context::CommandEnv;
use super::hooks::{
- HookCommandSpec, HookFailureStrategy, prepare_background_hooks, run_hook_with_filter,
- spawn_hook_pipeline,
+ HookCommandSpec, prepare_background_hooks, run_hook_with_filter, spawn_hook_pipeline,
};
use super::repository_ext::{RemoveTarget, RepositoryCliExt};
use super::worktree::BranchDeletionMode;
@@ -210,7 +210,7 @@ pub fn handle_squash(
name_filters: &[],
display_path: crate::output::pre_hook_display_path(ctx.worktree_path),
},
- HookFailureStrategy::FailFast,
+ FailureStrategy::FailFast,
)
.map_err(worktrunk::git::add_hook_skip_hint)?;
}
diff --git a/src/commands/worktree/hooks.rs b/src/commands/worktree/hooks.rs
index 1e9766f39..f803ac86e 100644
--- a/src/commands/worktree/hooks.rs
+++ b/src/commands/worktree/hooks.rs
@@ -10,7 +10,8 @@ use worktrunk::git::Repository;
use worktrunk::path::to_posix_path;
use crate::commands::command_executor::CommandContext;
-use crate::commands::hooks::{HookFailureStrategy, execute_hook};
+use crate::commands::command_executor::FailureStrategy;
+use crate::commands::hooks::execute_hook;
impl<'a> CommandContext<'a> {
/// Execute pre-start commands sequentially (blocking)
@@ -25,7 +26,7 @@ impl<'a> CommandContext<'a> {
self,
HookType::PreStart,
extra_vars,
- HookFailureStrategy::FailFast,
+ FailureStrategy::FailFast,
&[],
crate::output::post_hook_display_path(self.worktree_path),
)
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 347a345b6..90edb9828 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -11,9 +11,9 @@ use worktrunk::styling::{eprint, format_bash_with_gutter, stderr};
use crate::commands::branch_deletion::{BranchDeletionOutcome, BranchDeletionResult};
use crate::commands::command_executor::CommandContext;
+use crate::commands::command_executor::FailureStrategy;
use crate::commands::hooks::{
- HookFailureStrategy, announce_and_spawn_background_hooks, execute_hook,
- prepare_background_hooks,
+ announce_and_spawn_background_hooks, execute_hook, prepare_background_hooks,
};
use crate::commands::process::{
HookLog, InternalOp, build_remove_command, build_remove_command_staged, spawn_detached,
@@ -1179,7 +1179,7 @@ fn execute_pre_remove_hooks_if_needed(
&command_ctx,
worktrunk::HookType::PreRemove,
&extra_vars,
- HookFailureStrategy::FailFast,
+ FailureStrategy::FailFast,
&[],
display_path,
)