Skip to content

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

Run post-start/post-switch hooks concurrently

Maximilian Roos15e37539ab99
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index 716998e07..abd7830df 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -8,7 +8,7 @@ use worktrunk::styling::{
};
use super::command_executor::CommandContext;
-use super::hooks::{HookFailureStrategy, HookPipeline, HookSource};
+use super::hooks::HookFailureStrategy;
use super::repository_ext::RepositoryCliExt;
// Re-export StageMode from config for use by CLI
@@ -160,33 +160,25 @@ impl CommitOptions<'_> {
}
if !self.no_verify {
- let pipeline = HookPipeline::new(*self.ctx);
let extra_vars: Vec<(&str, &str)> = self
.target_branch
.into_iter()
.map(|target| ("target", target))
.collect();
- // Run user pre-commit hooks first (no approval required)
- if let Some(user_config) = &self.ctx.config.hooks.pre_commit {
- pipeline
- .run_sequential(
- user_config,
- HookType::PreCommit,
- HookSource::User,
- &extra_vars,
- HookFailureStrategy::FailFast,
- None,
- )
- .map_err(worktrunk::git::add_hook_skip_hint)?;
- }
-
- // Then run project pre-commit hooks (require approval)
- if let Some(ref config) = project_config {
- pipeline
- .run_pre_commit(config, self.target_branch, None)
- .map_err(worktrunk::git::add_hook_skip_hint)?;
- }
+ // Run pre-commit hooks (user first, then project)
+ super::hooks::run_hook_with_filter(
+ self.ctx,
+ self.ctx.config.hooks.pre_commit.as_ref(),
+ project_config
+ .as_ref()
+ .and_then(|c| c.hooks.pre_commit.as_ref()),
+ HookType::PreCommit,
+ &extra_vars,
+ HookFailureStrategy::FailFast,
+ None,
+ )
+ .map_err(worktrunk::git::add_hook_skip_hint)?;
}
if self.warn_about_untracked && self.stage_mode == StageMode::All {
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index dd415b81b..c936865d6 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -14,7 +14,7 @@
use color_print::cformat;
use worktrunk::HookType;
-use worktrunk::config::{CommandConfig, ProjectConfig};
+use worktrunk::config::CommandConfig;
use worktrunk::git::WorktrunkError;
use worktrunk::styling::{format_bash_with_gutter, progress_message, warning_message};
@@ -22,6 +22,25 @@ use super::command_executor::{CommandContext, PreparedCommand, prepare_commands}
use crate::commands::process::spawn_detached;
use crate::output::execute_command_in_worktree;
+/// A prepared command with its source information.
+pub struct SourcedCommand {
+ pub prepared: PreparedCommand,
+ pub source: HookSource,
+ /// Display label like "user post-start" or "project pre-merge"
+ pub label: String,
+}
+
+impl SourcedCommand {
+ /// Announce this command before execution.
+ fn announce(&self) -> anyhow::Result<()> {
+ let full_label =
+ crate::commands::format_command_label(&self.label, self.prepared.name.as_deref());
+ crate::output::print(progress_message(format!("{full_label}:")))?;
+ crate::output::gutter(format_bash_with_gutter(&self.prepared.expanded))?;
+ Ok(())
+ }
+}
+
/// Controls how hook execution should respond to failures.
#[derive(Clone, Copy)]
pub enum HookFailureStrategy {
@@ -36,7 +55,7 @@ pub enum HookFailureStrategy {
///
/// Approval for project hooks is handled at the gate (command entry point),
/// not during hook execution.
-#[derive(strum::Display)]
+#[derive(Clone, Copy, strum::Display)]
#[strum(serialize_all = "kebab-case")]
pub enum HookSource {
/// User hooks from ~/.config/worktrunk/config.toml (no approval required)
@@ -47,220 +66,106 @@ pub enum HookSource {
impl HookSource {
/// Format a label for display: "user pre-merge" or "project pre-merge"
- fn format_label(&self, hook_type: HookType) -> String {
+ pub fn format_label(&self, hook_type: HookType) -> String {
format!("{} {}", self, hook_type)
}
}
-/// Helper for preparing and executing hook commands.
-pub struct HookPipeline<'a> {
- ctx: CommandContext<'a>,
-}
+/// Prepare hook commands from both user and project configs.
+///
+/// Collects commands from user config first, then project config, applying the name filter.
+/// Returns a flat list of commands with source information for execution.
+pub fn prepare_hook_commands(
+ ctx: &CommandContext,
+ user_config: Option<&CommandConfig>,
+ project_config: Option<&CommandConfig>,
+ hook_type: HookType,
+ extra_vars: &[(&str, &str)],
+ name_filter: Option<&str>,
+) -> anyhow::Result<Vec<SourcedCommand>> {
+ let mut commands = Vec::new();
-impl<'a> HookPipeline<'a> {
- pub fn new(ctx: CommandContext<'a>) -> Self {
- Self { ctx }
+ if let Some(config) = user_config {
+ let prepared = prepare_commands(config, ctx, extra_vars, hook_type)?;
+ let filtered = filter_by_name(prepared, name_filter);
+ let label = HookSource::User.format_label(hook_type);
+ commands.extend(filtered.into_iter().map(|p| SourcedCommand {
+ prepared: p,
+ source: HookSource::User,
+ label: label.clone(),
+ }));
}
- fn prepare_commands(
- &self,
- command_config: &CommandConfig,
- hook_type: HookType,
- _source: &HookSource,
- extra_vars: &[(&str, &str)],
- name_filter: Option<&str>,
- ) -> anyhow::Result<Vec<PreparedCommand>> {
- let commands = prepare_commands(command_config, &self.ctx, extra_vars, hook_type)?;
- Ok(Self::filter_by_name(commands, name_filter))
+ if let Some(config) = project_config {
+ let prepared = prepare_commands(config, ctx, extra_vars, hook_type)?;
+ let filtered = filter_by_name(prepared, name_filter);
+ let label = HookSource::Project.format_label(hook_type);
+ commands.extend(filtered.into_iter().map(|p| SourcedCommand {
+ prepared: p,
+ source: HookSource::Project,
+ label: label.clone(),
+ }));
}
- fn announce_command(
- &self,
- label_prefix: &str,
- prepared: &PreparedCommand,
- ) -> anyhow::Result<()> {
- let label = crate::commands::format_command_label(label_prefix, prepared.name.as_deref());
- crate::output::print(progress_message(format!("{label}:")))?;
- crate::output::gutter(format_bash_with_gutter(&prepared.expanded))?;
- Ok(())
- }
+ Ok(commands)
+}
- /// Filter commands by name (returns empty vec if name not found - caller decides if that's an error)
- fn filter_by_name(
- commands: Vec<PreparedCommand>,
- name_filter: Option<&str>,
- ) -> Vec<PreparedCommand> {
- match name_filter {
- Some(name) => commands
- .into_iter()
- .filter(|cmd| cmd.name.as_deref() == Some(name))
- .collect(),
- None => commands,
- }
+/// Filter commands by name (returns empty vec if name not found).
+fn filter_by_name(
+ commands: Vec<PreparedCommand>,
+ name_filter: Option<&str>,
+) -> Vec<PreparedCommand> {
+ match name_filter {
+ Some(name) => commands
+ .into_iter()
+ .filter(|cmd| cmd.name.as_deref() == Some(name))
+ .collect(),
+ None => commands,
}
+}
- /// Run hook commands sequentially, using the provided failure strategy.
- /// Returns the number of commands that were run.
- pub fn run_sequential(
- &self,
- command_config: &CommandConfig,
- hook_type: HookType,
- source: HookSource,
- extra_vars: &[(&str, &str)],
- failure_strategy: HookFailureStrategy,
- name_filter: Option<&str>,
- ) -> anyhow::Result<usize> {
- let commands =
- self.prepare_commands(command_config, hook_type, &source, extra_vars, name_filter)?;
- if commands.is_empty() {
- return Ok(0);
- }
- let command_count = commands.len();
-
- // Track first failure for Warn strategy (to propagate exit code after all commands run)
- let mut first_failure: Option<(String, Option<String>, i32)> = None;
-
- let label_prefix = source.format_label(hook_type);
-
- for prepared in commands {
- self.announce_command(&label_prefix, &prepared)?;
-
- if let Err(err) = execute_command_in_worktree(
- self.ctx.worktree_path,
- &prepared.expanded,
- Some(&prepared.context_json),
- ) {
- // Extract raw message and exit code from error
- 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 => {
- return Err(WorktrunkError::HookCommandFailed {
- hook_type,
- command_name: prepared.name.clone(),
- error: err_msg,
- exit_code,
- }
- .into());
- }
- HookFailureStrategy::Warn => {
- let message = match &prepared.name {
- Some(name) => {
- cformat!("Command <bold>{name}</> failed: {err_msg}")
- }
- None => format!("Command failed: {err_msg}"),
- };
- crate::output::print(warning_message(message))?;
-
- // Track first failure to propagate exit code later (only for PostMerge)
- if first_failure.is_none() && hook_type == HookType::PostMerge {
- first_failure =
- Some((err_msg, prepared.name.clone(), exit_code.unwrap_or(1)));
- }
- }
- }
- }
- }
-
- crate::output::flush()?;
-
- // For Warn strategy with PostMerge: if any command failed, propagate the exit code
- // This matches git's behavior: post-hooks can't stop the operation but affect exit status
- if let Some((error, command_name, exit_code)) = first_failure {
- return Err(WorktrunkError::HookCommandFailed {
- hook_type,
- command_name,
- error,
- exit_code: Some(exit_code),
- }
- .into());
- }
-
- Ok(command_count)
+/// Spawn hook commands as background (detached) processes.
+///
+/// Used for post-start and post-switch hooks during normal worktree operations.
+/// Commands are spawned and immediately detached - we don't wait for them.
+pub fn spawn_hook_commands_background(
+ ctx: &CommandContext,
+ commands: Vec<SourcedCommand>,
+ hook_type: HookType,
+) -> anyhow::Result<()> {
+ if commands.is_empty() {
+ return Ok(());
}
- /// Spawn hook commands in the background (used for post-start hooks).
- pub fn spawn_background(
- &self,
- command_config: &CommandConfig,
- hook_type: HookType,
- source: HookSource,
- extra_vars: &[(&str, &str)],
- name_filter: Option<&str>,
- ) -> anyhow::Result<()> {
- let commands =
- self.prepare_commands(command_config, hook_type, &source, extra_vars, name_filter)?;
- if commands.is_empty() {
- return Ok(());
+ let operation_prefix = hook_type.to_string();
+
+ for cmd in commands {
+ cmd.announce()?;
+
+ let name = cmd.prepared.name.as_deref().unwrap_or("cmd");
+ // Include source in operation name to prevent log file collisions between
+ // user and project hooks with the same name
+ let operation = format!("{}-{}-{}", cmd.source, operation_prefix, name);
+
+ if let Err(err) = spawn_detached(
+ ctx.repo,
+ ctx.worktree_path,
+ &cmd.prepared.expanded,
+ ctx.branch_or_head(),
+ &operation,
+ Some(&cmd.prepared.context_json),
+ ) {
+ let err_msg = err.to_string();
+ let message = match &cmd.prepared.name {
+ Some(name) => format!("Failed to spawn \"{name}\": {err_msg}"),
+ None => format!("Failed to spawn command: {err_msg}"),
+ };
+ crate::output::print(warning_message(message))?;
}
-
- // Derive operation name from hook type (e.g., "post-start")
- let operation_prefix = hook_type.to_string();
- let label_prefix = source.format_label(hook_type);
-
- for prepared in commands {
- self.announce_command(&label_prefix, &prepared)?;
-
- let name = prepared.name.as_deref().unwrap_or("cmd");
- // Include source in operation name to prevent log file collisions between
- // user and project hooks with the same name
- let operation = format!("{}-{}-{}", source, operation_prefix, name);
- if let Err(err) = spawn_detached(
- self.ctx.repo,
- self.ctx.worktree_path,
- &prepared.expanded,
- self.ctx.branch_or_head(),
- &operation,
- Some(&prepared.context_json),
- ) {
- let err_msg = err.to_string();
- let message = match &prepared.name {
- Some(name) => format!("Failed to spawn \"{name}\": {err_msg}"),
- None => format!("Failed to spawn command: {err_msg}"),
- };
- crate::output::print(warning_message(message))?;
- }
- }
-
- crate::output::flush()?;
- Ok(())
}
- pub fn run_pre_commit(
- &self,
- project_config: &ProjectConfig,
- target_branch: Option<&str>,
- name_filter: Option<&str>,
- ) -> anyhow::Result<()> {
- let Some(pre_commit_config) = &project_config.hooks.pre_commit else {
- return Ok(());
- };
-
- let extra_vars: Vec<(&str, &str)> = target_branch
- .into_iter()
- .map(|target| ("target", target))
- .collect();
-
- self.run_sequential(
- pre_commit_config,
- HookType::PreCommit,
- HookSource::Project,
- &extra_vars,
- HookFailureStrategy::FailFast,
- name_filter,
- )?;
- Ok(())
- }
+ crate::output::flush()?;
+ Ok(())
}
/// A single hook command failure (for concurrent execution).
@@ -311,8 +216,8 @@ fn check_name_filter_matched(
/// Run user and project hooks for a given hook type.
///
/// This is the canonical implementation for running hooks from both sources.
-/// Runs user hooks first, then project hooks. Handles name filtering and
-/// returns an error if a name filter was provided but no matching command found.
+/// Runs user hooks first, then project hooks sequentially. Handles name filtering
+/// and returns an error if a name filter was provided but no matching command found.
pub fn run_hook_with_filter(
ctx: &CommandContext,
user_config: Option<&CommandConfig>,
@@ -322,34 +227,87 @@ pub fn run_hook_with_filter(
failure_strategy: HookFailureStrategy,
name_filter: Option<&str>,
) -> anyhow::Result<()> {
- let pipeline = HookPipeline::new(*ctx);
- let mut total_commands_run = 0;
+ let commands = prepare_hook_commands(
+ ctx,
+ user_config,
+ project_config,
+ hook_type,
+ extra_vars,
+ name_filter,
+ )?;
+
+ check_name_filter_matched(name_filter, commands.len(), user_config, project_config)?;
+
+ if commands.is_empty() {
+ return Ok(());
+ }
- // Run user hooks first (no approval required)
- if let Some(config) = user_config {
- total_commands_run += pipeline.run_sequential(
- config,
- hook_type,
- HookSource::User,
- extra_vars,
- failure_strategy,
- name_filter,
- )?;
+ // Track first failure for Warn strategy (to propagate exit code after all commands run)
+ let mut first_failure: Option<(String, Option<String>, i32)> = None;
+
+ for cmd in commands {
+ cmd.announce()?;
+
+ if let Err(err) = execute_command_in_worktree(
+ ctx.worktree_path,
+ &cmd.prepared.expanded,
+ Some(&cmd.prepared.context_json),
+ ) {
+ // Extract raw message and exit code from error
+ 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 => {
+ crate::output::flush()?;
+ return Err(WorktrunkError::HookCommandFailed {
+ hook_type,
+ command_name: cmd.prepared.name.clone(),
+ error: err_msg,
+ exit_code,
+ }
+ .into());
+ }
+ HookFailureStrategy::Warn => {
+ let message = match &cmd.prepared.name {
+ Some(name) => cformat!("Command <bold>{name}</> failed: {err_msg}"),
+ None => format!("Command failed: {err_msg}"),
+ };
+ crate::output::print(warning_message(message))?;
+
+ // Track first failure to propagate exit code later (only for PostMerge)
+ if first_failure.is_none() && hook_type == HookType::PostMerge {
+ first_failure =
+ Some((err_msg, cmd.prepared.name.clone(), exit_code.unwrap_or(1)));
+ }
+ }
+ }
+ }
}
- // Then run project hooks (approval handled at gate)
- if let Some(config) = project_config {
- total_commands_run += pipeline.run_sequential(
- config,
+ crate::output::flush()?;
+
+ // For Warn strategy with PostMerge: if any command failed, propagate the exit code
+ // This matches git's behavior: post-hooks can't stop the operation but affect exit status
+ if let Some((error, command_name, exit_code)) = first_failure {
+ return Err(WorktrunkError::HookCommandFailed {
hook_type,
- HookSource::Project,
- extra_vars,
- failure_strategy,
- name_filter,
- )?;
+ command_name,
+ error,
+ exit_code: Some(exit_code),
+ }
+ .into());
}
- check_name_filter_matched(name_filter, total_commands_run, user_config, project_config)
+ Ok(())
}
/// Run user and project hooks concurrently (for hook types that normally run in background).
@@ -369,35 +327,24 @@ pub fn run_hook_concurrent_with_filter(
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 commands = prepare_hook_commands(
+ ctx,
+ user_config,
+ project_config,
+ hook_type,
+ extra_vars,
+ name_filter,
+ )?;
- let total_commands_run = all_commands.len();
- check_name_filter_matched(name_filter, total_commands_run, user_config, project_config)?;
+ check_name_filter_matched(name_filter, commands.len(), user_config, project_config)?;
- if all_commands.is_empty() {
+ if commands.is_empty() {
return Ok(());
}
// Announce all commands upfront
- for (prepared, label) in &all_commands {
- pipeline.announce_command(label, prepared)?;
+ for cmd in &commands {
+ cmd.announce()?;
}
crate::output::flush()?;
@@ -418,25 +365,27 @@ pub fn run_hook_concurrent_with_filter(
// 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 worktree_path = ctx.worktree_path.to_path_buf();
- let handles: Vec<_> = all_commands
+ let handles: Vec<_> = commands
.into_iter()
- .map(|(prepared, _label)| {
+ .map(|cmd| {
let shell = shell.clone();
let worktree_path = worktree_path.clone();
+ let prepared = cmd.prepared;
thread::spawn(move || {
use std::io::Write;
- let mut cmd = shell.command(&prepared.expanded);
- cmd.current_dir(&worktree_path)
+ let mut child_cmd = shell.command(&prepared.expanded);
+ child_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() {
+ let mut child = match child_cmd.spawn() {
Ok(child) => child,
Err(e) => {
return Some(HookFailure {
diff --git a/src/commands/standalone.rs b/src/commands/standalone.rs
index fba87ef36..86c38d9f7 100644
--- a/src/commands/standalone.rs
+++ b/src/commands/standalone.rs
@@ -13,9 +13,7 @@ use worktrunk::styling::{
use super::command_executor::CommandContext;
use super::commit::{CommitGenerator, CommitOptions};
use super::context::CommandEnv;
-use super::hooks::{
- HookFailureStrategy, HookPipeline, run_hook_concurrent_with_filter, run_hook_with_filter,
-};
+use super::hooks::{HookFailureStrategy, run_hook_concurrent_with_filter, run_hook_with_filter};
use super::merge::{
execute_post_merge_commands, execute_pre_remove_commands, run_pre_merge_commands,
};
@@ -274,29 +272,21 @@ pub fn handle_squash(
)))?;
}
- let pipeline = HookPipeline::new(ctx);
- let extra_vars = [("target", target_branch.as_str())];
-
- // Run user pre-commit hooks first (unless skipped)
- if !skip_pre_commit && let Some(user_config) = &ctx.config.hooks.pre_commit {
- use super::hooks::{HookFailureStrategy, HookSource};
- pipeline
- .run_sequential(
- user_config,
- HookType::PreCommit,
- HookSource::User,
- &extra_vars,
- HookFailureStrategy::FailFast,
- None,
- )
- .map_err(worktrunk::git::add_hook_skip_hint)?;
- }
-
- // Then run project pre-commit hooks (unless skipped)
- if !skip_pre_commit && let Some(ref config) = project_config {
- pipeline
- .run_pre_commit(config, Some(&target_branch), None)
- .map_err(worktrunk::git::add_hook_skip_hint)?;
+ // Run pre-commit hooks (user first, then project)
+ if !skip_pre_commit {
+ let extra_vars = [("target", target_branch.as_str())];
+ run_hook_with_filter(
+ &ctx,
+ ctx.config.hooks.pre_commit.as_ref(),
+ project_config
+ .as_ref()
+ .and_then(|c| c.hooks.pre_commit.as_ref()),
+ HookType::PreCommit,
+ &extra_vars,
+ HookFailureStrategy::FailFast,
+ None,
+ )
+ .map_err(worktrunk::git::add_hook_skip_hint)?;
}
// Get merge base with target branch
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index d8f3ec8ff..36150e03d 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -92,7 +92,7 @@ use worktrunk::styling::{
};
use super::command_executor::CommandContext;
-use super::hooks::{HookFailureStrategy, HookPipeline, HookSource};
+use super::hooks::{HookFailureStrategy, prepare_hook_commands, spawn_hook_commands_background};
use super::repository_ext::{RemoveTarget, RepositoryCliExt};
/// Generate a backup path for the given path with a timestamp suffix.
@@ -815,112 +815,56 @@ impl<'a> CommandContext<'a> {
///
/// Runs user hooks first, then project hooks.
pub fn execute_post_create_commands(&self) -> anyhow::Result<()> {
- let pipeline = HookPipeline::new(*self);
-
- // Run user hooks first (no approval required)
- if let Some(user_config) = &self.config.hooks.post_create {
- pipeline.run_sequential(
- user_config,
- HookType::PostCreate,
- HookSource::User,
- &[],
- HookFailureStrategy::Warn,
- None,
- )?;
- }
-
- // Then run project hooks (approval checked at gate, not here)
- let project_config = match self.repo.load_project_config()? {
- Some(cfg) => cfg,
- None => return Ok(()),
- };
-
- let Some(post_create_config) = &project_config.hooks.post_create else {
- return Ok(());
- };
-
- pipeline.run_sequential(
- post_create_config,
+ let project_config = self.repo.load_project_config()?;
+ super::hooks::run_hook_with_filter(
+ self,
+ self.config.hooks.post_create.as_ref(),
+ project_config
+ .as_ref()
+ .and_then(|c| c.hooks.post_create.as_ref()),
HookType::PostCreate,
- HookSource::Project,
&[],
HookFailureStrategy::Warn,
None,
- )?;
- Ok(())
+ )
}
/// Spawn post-start commands in parallel as background processes (non-blocking)
- ///
- /// Spawns user hooks first, then project hooks.
pub fn spawn_post_start_commands(&self) -> anyhow::Result<()> {
- let pipeline = HookPipeline::new(*self);
-
- // Spawn user hooks first (no approval required)
- if let Some(user_config) = &self.config.hooks.post_start {
- pipeline.spawn_background(
- user_config,
- HookType::PostStart,
- HookSource::User,
- &[],
- None,
- )?;
- }
-
- // Then spawn project hooks (approval checked at gate, not here)
- let project_config = match self.repo.load_project_config()? {
- Some(cfg) => cfg,
- None => return Ok(()),
- };
-
- let Some(post_start_config) = &project_config.hooks.post_start else {
- return Ok(());
- };
-
- pipeline.spawn_background(
- post_start_config,
+ let project_config = self.repo.load_project_config()?;
+
+ let commands = prepare_hook_commands(
+ self,
+ self.config.hooks.post_start.as_ref(),
+ project_config
+ .as_ref()
+ .and_then(|c| c.hooks.post_start.as_ref()),
HookType::PostStart,
- HookSource::Project,
&[],
None,
- )
+ )?;
+
+ spawn_hook_commands_background(self, commands, HookType::PostStart)
}
/// Spawn post-switch commands in parallel as background processes (non-blocking)
///
- /// Spawns user hooks first, then project hooks.
/// Runs on every switch, including to existing worktrees and newly created ones.
pub fn spawn_post_switch_commands(&self) -> anyhow::Result<()> {
- let pipeline = HookPipeline::new(*self);
-
- // Spawn user hooks first (no approval required)
- if let Some(user_config) = &self.config.hooks.post_switch {
- pipeline.spawn_background(
- user_config,
- HookType::PostSwitch,
- HookSource::User,
- &[],
- None,
- )?;
- }
-
- // Then spawn project hooks (approval checked at gate, not here)
- let project_config = match self.repo.load_project_config()? {
- Some(cfg) => cfg,
- None => return Ok(()),
- };
-
- let Some(post_switch_config) = &project_config.hooks.post_switch else {
- return Ok(());
- };
-
- pipeline.spawn_background(
- post_switch_config,
+ let project_config = self.repo.load_project_config()?;
+
+ let commands = prepare_hook_commands(
+ self,
+ self.config.hooks.post_switch.as_ref(),
+ project_config
+ .as_ref()
+ .and_then(|c| c.hooks.post_switch.as_ref()),
HookType::PostSwitch,
- HookSource::Project,
&[],
None,
- )
+ )?;
+
+ spawn_hook_commands_background(self, commands, HookType::PostSwitch)
}
}