Skip to content

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

Run post-start/post-switch hooks concurrently via wt hook (#319)

Maximilian Roos8b568155be90
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 4950574ab..dd415b81b 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -263,6 +263,51 @@ impl<'a> HookPipeline<'a> {
}
}
+/// A single hook command failure (for concurrent execution).
+#[derive(Debug, Clone)]
+struct HookFailure {
+ name: Option<String>,
+ error: String,
+ exit_code: Option<i32>,
+}
+
+/// Check if a name filter was provided but no commands matched.
+/// Returns an error listing available command names if so.
+fn check_name_filter_matched(
+ name_filter: Option<&str>,
+ total_commands_run: usize,
+ user_config: Option<&CommandConfig>,
+ project_config: Option<&CommandConfig>,
+) -> anyhow::Result<()> {
+ if let Some(name) = name_filter
+ && total_commands_run == 0
+ {
+ let mut available = Vec::new();
+ if let Some(config) = user_config {
+ available.extend(
+ config
+ .commands()
+ .iter()
+ .filter_map(|c| c.name.as_ref().map(|n| format!("user:{n}"))),
+ );
+ }
+ if let Some(config) = project_config {
+ available.extend(
+ config
+ .commands()
+ .iter()
+ .filter_map(|c| c.name.as_ref().map(|n| format!("project:{n}"))),
+ );
+ }
+ return Err(worktrunk::git::GitError::HookCommandNotFound {
+ name: name.to_string(),
+ available,
+ }
+ .into());
+ }
+ Ok(())
+}
+
/// Run user and project hooks for a given hook type.
///
/// This is the canonical implementation for running hooks from both sources.
@@ -304,30 +349,168 @@ pub fn run_hook_with_filter(
)?;
}
- // If name filter was provided but no commands matched, error with available names
- if let Some(name) = name_filter
- && total_commands_run == 0
- {
- let mut available = Vec::new();
- if let Some(config) = user_config {
- available.extend(
- config
- .commands()
- .iter()
- .filter_map(|c| c.name.as_ref().map(|n| format!("user:{n}"))),
- );
- }
- if let Some(config) = project_config {
- available.extend(
- config
- .commands()
- .iter()
- .filter_map(|c| c.name.as_ref().map(|n| format!("project:{n}"))),
- );
- }
- return Err(worktrunk::git::GitError::HookCommandNotFound {
- name: name.to_string(),
- available,
+ check_name_filter_matched(name_filter, total_commands_run, user_config, project_config)
+}
+
+/// Run user and project hooks concurrently (for hook types that normally run in background).
+///
+/// All commands from both sources run in parallel together. Collects all failures and returns
+/// a combined error at the end. Handles name filtering and returns an error if a name
+/// filter was provided but no matching command found.
+pub fn run_hook_concurrent_with_filter(
+ ctx: &CommandContext,
+ user_config: Option<&CommandConfig>,
+ project_config: Option<&CommandConfig>,
+ hook_type: HookType,
+ extra_vars: &[(&str, &str)],
+ name_filter: Option<&str>,
+) -> anyhow::Result<()> {
+ use std::process::Stdio;
+ use std::thread;
+ use worktrunk::shell_exec::ShellConfig;
+
+ let pipeline = HookPipeline::new(*ctx);
+
+ // Prepare all commands from both sources upfront
+ let mut all_commands: Vec<(PreparedCommand, String)> = Vec::new();
+
+ if let Some(config) = user_config {
+ let label = HookSource::User.format_label(hook_type);
+ let commands = prepare_commands(config, &pipeline.ctx, extra_vars, hook_type)?;
+ let filtered = HookPipeline::filter_by_name(commands, name_filter);
+ all_commands.extend(filtered.into_iter().map(|c| (c, label.clone())));
+ }
+
+ if let Some(config) = project_config {
+ let label = HookSource::Project.format_label(hook_type);
+ let commands = prepare_commands(config, &pipeline.ctx, extra_vars, hook_type)?;
+ let filtered = HookPipeline::filter_by_name(commands, name_filter);
+ all_commands.extend(filtered.into_iter().map(|c| (c, label.clone())));
+ }
+
+ let total_commands_run = all_commands.len();
+ check_name_filter_matched(name_filter, total_commands_run, user_config, project_config)?;
+
+ if all_commands.is_empty() {
+ return Ok(());
+ }
+
+ // Announce all commands upfront
+ for (prepared, label) in &all_commands {
+ pipeline.announce_command(label, prepared)?;
+ }
+ crate::output::flush()?;
+
+ // Reset ANSI codes to prevent color bleeding from our output into command output
+ use std::io::Write;
+ use worktrunk::styling::{eprint, stderr};
+ eprint!("{}", anstyle::Reset);
+ stderr().flush().ok();
+
+ // Spawn all commands in parallel together.
+ //
+ // Note: Unlike sequential execution (execute_streaming), we don't use process_group(0)
+ // or sophisticated signal forwarding here. Children inherit the foreground process group,
+ // so Ctrl+C sends SIGINT to all of them together. This simpler behavior is acceptable for
+ // "best effort" concurrent hooks - if the user interrupts, everything stops.
+ //
+ // Adding proper signal forwarding would require either spawning all children from the main
+ // thread (not worker threads) or sharing child PIDs across threads with a coordinating
+ // signal handler. The complexity isn't warranted for this use case.
+ let shell = ShellConfig::get();
+ let worktree_path = pipeline.ctx.worktree_path.to_path_buf();
+
+ let handles: Vec<_> = all_commands
+ .into_iter()
+ .map(|(prepared, _label)| {
+ let shell = shell.clone();
+ let worktree_path = worktree_path.clone();
+
+ thread::spawn(move || {
+ use std::io::Write;
+
+ let mut cmd = shell.command(&prepared.expanded);
+ cmd.current_dir(&worktree_path)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::from(std::io::stderr()))
+ .stderr(Stdio::inherit())
+ .env_remove(worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR);
+
+ let mut child = match cmd.spawn() {
+ Ok(child) => child,
+ Err(e) => {
+ return Some(HookFailure {
+ name: prepared.name.clone(),
+ error: e.to_string(),
+ exit_code: None,
+ });
+ }
+ };
+
+ // Pipe context JSON to stdin (same as sequential execution)
+ if let Some(mut stdin) = child.stdin.take() {
+ // Ignore write errors - command may not read stdin
+ let _ = stdin.write_all(prepared.context_json.as_bytes());
+ }
+
+ match child.wait() {
+ Ok(status) if status.success() => None,
+ Ok(status) => Some(HookFailure {
+ name: prepared.name.clone(),
+ error: format!("exit status: {}", status.code().unwrap_or(-1)),
+ exit_code: status.code(),
+ }),
+ Err(e) => Some(HookFailure {
+ name: prepared.name.clone(),
+ error: e.to_string(),
+ exit_code: None,
+ }),
+ }
+ })
+ })
+ .collect();
+
+ // Wait for all and collect failures
+ let all_failures: Vec<HookFailure> = handles
+ .into_iter()
+ .filter_map(|h| match h.join() {
+ Ok(result) => result,
+ Err(_) => {
+ // Thread panicked - treat as failure (command name context is lost)
+ Some(HookFailure {
+ name: None,
+ error: "thread panicked".to_string(),
+ exit_code: None,
+ })
+ }
+ })
+ .collect();
+
+ // Report all failures at the end
+ if !all_failures.is_empty() {
+ let first = &all_failures[0];
+ let error_msg = if all_failures.len() == 1 {
+ match &first.name {
+ Some(name) => format!("{}: {}", name, first.error),
+ None => first.error.clone(),
+ }
+ } else {
+ let names: Vec<_> = all_failures
+ .iter()
+ .map(|f| f.name.as_deref().unwrap_or("(unnamed)"))
+ .collect();
+ format!(
+ "{} commands failed: {}",
+ all_failures.len(),
+ names.join(", ")
+ )
+ };
+
+ return Err(WorktrunkError::HookCommandFailed {
+ hook_type,
+ command_name: first.name.clone(),
+ error: error_msg,
+ exit_code: first.exit_code,
}
.into());
}
diff --git a/src/commands/standalone.rs b/src/commands/standalone.rs
index 23177489b..fba87ef36 100644
--- a/src/commands/standalone.rs
+++ b/src/commands/standalone.rs
@@ -13,7 +13,9 @@ use worktrunk::styling::{
use super::command_executor::CommandContext;
use super::commit::{CommitGenerator, CommitOptions};
use super::context::CommandEnv;
-use super::hooks::{HookFailureStrategy, HookPipeline, run_hook_with_filter};
+use super::hooks::{
+ HookFailureStrategy, HookPipeline, run_hook_concurrent_with_filter, run_hook_with_filter,
+};
use super::merge::{
execute_post_merge_commands, execute_pre_remove_commands, run_pre_merge_commands,
};
@@ -90,34 +92,34 @@ pub fn run_hook(hook_type: HookType, yes: bool, name_filter: Option<&str>) -> an
)
}
HookType::PostStart => {
+ // post-start hooks run concurrently (matching their normal background behavior)
let user_config = user_hook!(post_start);
let project_config = project_config
.as_ref()
.and_then(|c| c.hooks.post_start.as_ref());
require_hooks(user_config, project_config, hook_type)?;
- run_hook_with_filter(
+ run_hook_concurrent_with_filter(
&ctx,
user_config,
project_config,
hook_type,
&[],
- HookFailureStrategy::FailFast,
name_filter,
)
}
HookType::PostSwitch => {
+ // post-switch hooks run concurrently (matching their normal background behavior)
let user_config = user_hook!(post_switch);
let project_config = project_config
.as_ref()
.and_then(|c| c.hooks.post_switch.as_ref());
require_hooks(user_config, project_config, hook_type)?;
- run_hook_with_filter(
+ run_hook_concurrent_with_filter(
&ctx,
user_config,
project_config,
hook_type,
&[],
- HookFailureStrategy::FailFast,
name_filter,
)
}
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index 1a5a49f4f..ffc2b987f 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -833,3 +833,196 @@ fn test_standalone_hook_no_hooks_configured(repo: TestRepo) {
"Error should mention no hook configured, got: {stderr}"
);
}
+
+// ============================================================================
+// Concurrent Hook Execution Tests (post-start, post-switch)
+// ============================================================================
+
+/// Test that a single failing concurrent hook reports the failure
+#[rstest]
+fn test_concurrent_hook_single_failure(repo: TestRepo) {
+ // Write project config with a failing post-start hook
+ repo.write_project_config(r#"post-start = "exit 1""#);
+
+ let mut cmd = crate::common::wt_command();
+ cmd.current_dir(repo.root_path());
+ cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
+ cmd.args(["hook", "post-start", "--yes"]);
+
+ let output = cmd.output().unwrap();
+ assert!(
+ !output.status.success(),
+ "wt hook post-start should fail when hook exits with error"
+ );
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("exit status: 1"),
+ "Error should mention exit status, got: {stderr}"
+ );
+}
+
+/// Test that multiple failing concurrent hooks report all failures
+#[rstest]
+fn test_concurrent_hook_multiple_failures(repo: TestRepo) {
+ // Write project config with multiple named failing hooks (table format)
+ repo.write_project_config(
+ r#"[post-start]
+first = "exit 1"
+second = "exit 2"
+"#,
+ );
+
+ let mut cmd = crate::common::wt_command();
+ cmd.current_dir(repo.root_path());
+ cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
+ cmd.args(["hook", "post-start", "--yes"]);
+
+ let output = cmd.output().unwrap();
+ assert!(
+ !output.status.success(),
+ "wt hook post-start should fail when hooks exit with error"
+ );
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ // Should report multiple failures
+ assert!(
+ stderr.contains("2 commands failed"),
+ "Error should mention 2 commands failed, got: {stderr}"
+ );
+ assert!(
+ stderr.contains("first") && stderr.contains("second"),
+ "Error should list both failed command names, got: {stderr}"
+ );
+}
+
+/// Test that user and project post-start hooks both run concurrently
+#[rstest]
+fn test_concurrent_hook_user_and_project(repo: TestRepo) {
+ // Write user config with post-start hook (using table format for named hook)
+ repo.write_test_config(
+ r#"[post-start]
+user = "echo 'USER_HOOK' > user_hook_ran.txt"
+"#,
+ );
+
+ // Write project config with post-start hook
+ repo.write_project_config(r#"post-start = "echo 'PROJECT_HOOK' > project_hook_ran.txt""#);
+
+ let mut cmd = crate::common::wt_command();
+ cmd.current_dir(repo.root_path());
+ cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
+ cmd.args(["hook", "post-start", "--yes"]);
+
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "wt hook post-start should succeed, stderr: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ // Both hooks should have run
+ let user_marker = repo.root_path().join("user_hook_ran.txt");
+ let project_marker = repo.root_path().join("project_hook_ran.txt");
+
+ assert!(user_marker.exists(), "user post-start hook should have run");
+ assert!(
+ project_marker.exists(),
+ "project post-start hook should have run"
+ );
+
+ let user_content = fs::read_to_string(&user_marker).unwrap();
+ let project_content = fs::read_to_string(&project_marker).unwrap();
+ assert!(user_content.contains("USER_HOOK"));
+ assert!(project_content.contains("PROJECT_HOOK"));
+}
+
+/// Test that post-switch hooks also run concurrently
+#[rstest]
+fn test_concurrent_hook_post_switch(repo: TestRepo) {
+ // Write project config with post-switch hook
+ repo.write_project_config(r#"post-switch = "echo 'POST_SWITCH' > hook_ran.txt""#);
+
+ let mut cmd = crate::common::wt_command();
+ cmd.current_dir(repo.root_path());
+ cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
+ cmd.args(["hook", "post-switch", "--yes"]);
+
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "wt hook post-switch should succeed"
+ );
+
+ // Hook should have run
+ let marker = repo.root_path().join("hook_ran.txt");
+ assert!(marker.exists(), "post-switch hook should have run");
+ let content = fs::read_to_string(&marker).unwrap();
+ assert!(content.contains("POST_SWITCH"));
+}
+
+/// Test that concurrent hooks work with name filter
+#[rstest]
+fn test_concurrent_hook_with_name_filter(repo: TestRepo) {
+ // Write project config with multiple named hooks
+ repo.write_project_config(
+ r#"[post-start]
+first = "echo 'FIRST' > first.txt"
+second = "echo 'SECOND' > second.txt"
+"#,
+ );
+
+ // Run only the "first" hook by name
+ let mut cmd = crate::common::wt_command();
+ cmd.current_dir(repo.root_path());
+ cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
+ cmd.args(["hook", "post-start", "--yes", "first"]);
+
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "wt hook post-start --name first should succeed, stderr: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ // Only the first hook should have run
+ let first_marker = repo.root_path().join("first.txt");
+ let second_marker = repo.root_path().join("second.txt");
+
+ assert!(first_marker.exists(), "first hook should have run");
+ assert!(!second_marker.exists(), "second hook should NOT have run");
+}
+
+/// Test that concurrent hooks with invalid name filter return error
+#[rstest]
+fn test_concurrent_hook_invalid_name_filter(repo: TestRepo) {
+ // Write project config with named hooks
+ repo.write_project_config(
+ r#"[post-start]
+first = "echo 'FIRST'"
+"#,
+ );
+
+ // Try to run a non-existent hook by name
+ let mut cmd = crate::common::wt_command();
+ cmd.current_dir(repo.root_path());
+ cmd.env("WORKTRUNK_CONFIG_PATH", repo.test_config_path());
+ cmd.args(["hook", "post-start", "--yes", "nonexistent"]);
+
+ let output = cmd.output().unwrap();
+ assert!(
+ !output.status.success(),
+ "wt hook post-start --name nonexistent should fail"
+ );
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("nonexistent") && stderr.contains("No command named"),
+ "Error should mention command not found, got: {stderr}"
+ );
+ // Should list available commands
+ assert!(
+ stderr.contains("project:first"),
+ "Error should list available commands, got: {stderr}"
+ );
+}