Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(hooks): consolidate per-source loop into spawn_background_hooks (#2298)
Maximilian Roos39cbbede62be
diff --git a/src/commands/commit.rs b/src/commands/commit.rsindex 1917aac47..2edb12218 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::command_executor::FailureStrategy;-use super::hooks::{HookCommandSpec, prepare_background_hooks, spawn_hook_pipeline};+use super::hooks::{HookCommandSpec, spawn_background_hooks};use super::repository_ext::warn_about_untracked_files;// Re-export StageMode from config for use by CLI@@ -236,11 +236,7 @@ impl CommitOptions<'_> {.into_iter().map(|target| ("target", target)).collect();- for steps in- prepare_background_hooks(self.ctx, HookType::PostCommit, &extra_vars, None)?- {- spawn_hook_pipeline(self.ctx, steps)?;- }+ spawn_background_hooks(self.ctx, HookType::PostCommit, &extra_vars, None)?;}Ok(())diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 943ac36c0..2c8d5b560 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -27,8 +27,8 @@ use super::command_executor::{FailureStrategy, command_summary_name};use super::context::CommandEnv;use super::hook_filter::{HookSource, ParsedFilter};use super::hooks::{- HookCommandSpec, check_name_filter_matched, 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_sourced_steps,+ run_hook_with_filter, spawn_background_hooks, spawn_hook_pipeline,};fn run_filtered_hook(@@ -86,11 +86,8 @@ fn run_post_hook(return spawn_hook_pipeline(ctx, steps);}- // No name filter: prepare as pipeline steps and spawn per source.- for steps in prepare_background_hooks(ctx, hook_type, extra_vars, None)? {- spawn_hook_pipeline(ctx, steps)?;- }- return Ok(());+ // No name filter: prepare and spawn source-grouped pipelines.+ return spawn_background_hooks(ctx, hook_type, extra_vars, None);}run_filtered_hook(diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 2878ec4df..249ae6178 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -240,9 +240,10 @@ fn format_pipeline_summary(steps: &[SourcedStep]) -> String {/// Announce and spawn background hooks for one or more hook types.////// Displays a single combined summary line covering all hook types, then-/// spawns each source group as an independent pipeline. Use this instead-/// of calling `spawn_hook_pipeline` directly when multiple hook types-/// fire together (e.g., post-switch + post-start on create).+/// spawns each source group as an independent pipeline. For a single hook+/// type, prefer `spawn_background_hooks` — it wraps the prepare+announce+/// step. Use this directly when multiple hook types fire together (e.g.,+/// post-switch + post-start on create).////// Each pipeline carries its own `CommandContext` so that different hook types/// can use different contexts (e.g., post-remove uses the removed branch while@@ -321,27 +322,42 @@ pub fn announce_and_spawn_background_hooks(Ok(())}-/// Spawn a hook pipeline as a background `wt hook run-pipeline` process.+/// Prepare and spawn all source-group pipelines for a single hook type.///-/// Displays a summary line and spawns the pipeline. For multiple hook types-/// that should share a single display line, use `announce_and_spawn_background_hooks`.-pub fn spawn_hook_pipeline(ctx: &CommandContext, steps: Vec<SourcedStep>) -> anyhow::Result<()> {- if steps.is_empty() {- return Ok(());- }+/// Wraps `prepare_background_hooks` + `announce_and_spawn_background_hooks` so+/// callers produce exactly one `Running {hook}: …` announce line even when+/// both user and project configs contribute pipelines. Iterating the prepared+/// groups and calling `spawn_hook_pipeline` per group is a footgun — it prints+/// one announce line per source.+pub fn spawn_background_hooks(+ ctx: &CommandContext,+ hook_type: HookType,+ extra_vars: &[(&str, &str)],+ display_path: Option<&Path>,+) -> anyhow::Result<()> {+ let pipelines: Vec<_> = prepare_background_hooks(ctx, hook_type, extra_vars, display_path)?+ .into_iter()+ .map(|g| (*ctx, g))+ .collect();+ announce_and_spawn_background_hooks(pipelines, false)+}+/// Spawn a filter-matched hook pipeline as a background `wt hook run-pipeline`.+///+/// The name-filter path merges user + project matches into one pipeline (vs.+/// the source-grouped path that produces one pipeline per source). For the+/// source-grouped path, use `spawn_background_hooks` instead.+///+/// `check_name_filter_matched` must have run first — it guarantees `steps` is+/// non-empty. The filter path always calls with `display_path: None`, so no+/// path annotation is rendered.+pub fn spawn_hook_pipeline(ctx: &CommandContext, steps: Vec<SourcedStep>) -> anyhow::Result<()> {let hook_type = steps[0].hook_type;- let display_path = steps[0].display_path.as_ref();let summary = format_pipeline_summary(&steps);- let message = match display_path {- Some(path) => {- let path_display = format_path_for_display(path);- cformat!("Running {hook_type}: {summary} @ <bold>{path_display}</>")- }- None => format!("Running {hook_type}: {summary}"),- };- eprintln!("{}", progress_message(message));-+ eprintln!(+ "{}",+ progress_message(format!("Running {hook_type}: {summary}"))+ );spawn_hook_pipeline_quiet(ctx, steps)}diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 5de42a81f..8d8472812 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -9,7 +9,7 @@ use super::command_executor::CommandContext;use super::command_executor::FailureStrategy;use super::commit::CommitOptions;use super::context::CommandEnv;-use super::hooks::{announce_and_spawn_background_hooks, execute_hook, prepare_background_hooks};+use super::hooks::{execute_hook, spawn_background_hooks};use super::project_config::{ApprovableCommand, collect_commands_for_hooks};use super::repository_ext::{RepositoryCliExt, check_not_default_branch, compute_integration_reason, is_primary_worktree,@@ -358,12 +358,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {extra.push(("short_commit", sc));}- let pipelines: Vec<_> =- prepare_background_hooks(&ctx, HookType::PostMerge, &extra, display_path)?- .into_iter()- .map(|g| (ctx, g))- .collect();- announce_and_spawn_background_hooks(pipelines, false)?;+ spawn_background_hooks(&ctx, HookType::PostMerge, &extra, display_path)?;}if json_mode {diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 391051aa0..adf689737 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -109,7 +109,7 @@ 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::{execute_hook, prepare_background_hooks, spawn_hook_pipeline};+use super::hooks::{execute_hook, spawn_background_hooks};use super::list::collect;use super::repository_ext::{RemoveTarget, RepositoryCliExt};use super::worktree::hooks::PostRemoveContext;@@ -229,14 +229,12 @@ impl PickerCollector {&repo,);let extra_vars = remove_vars.extra_vars(hook_branch);- for steps in prepare_background_hooks(+ spawn_background_hooks(&post_ctx,worktrunk::HookType::PostRemove,&extra_vars,None, // no display path in TUI context- )? {- spawn_hook_pipeline(&post_ctx, steps)?;- }+ )?;}RemoveResult::BranchOnly {branch_name,diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 6a57911b1..7f2241d75 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -38,9 +38,7 @@ 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, prepare_background_hooks, run_hook_with_filter, spawn_hook_pipeline,-};+use super::hooks::{HookCommandSpec, run_hook_with_filter, spawn_background_hooks};use super::repository_ext::{RemoveTarget, RepositoryCliExt};use crate::output::handle_remove_output;use worktrunk::git::BranchDeletionMode;@@ -363,9 +361,7 @@ pub fn handle_squash(// Spawn post-commit hooks in background (respects --no-hooks)if verify {let extra_vars: Vec<(&str, &str)> = vec![("target", integration_target.as_str())];- for steps in prepare_background_hooks(&ctx, HookType::PostCommit, &extra_vars, None)? {- spawn_hook_pipeline(&ctx, steps)?;- }+ spawn_background_hooks(&ctx, HookType::PostCommit, &extra_vars, None)?;}Ok(SquashResult::Squashed)diff --git a/src/output/global.rs b/src/output/global.rsindex c327b3ba2..1bc9b4781 100644--- a/src/output/global.rs+++ b/src/output/global.rs@@ -602,9 +602,7 @@ pub fn pre_hook_display_path(hooks_run_at: &std::path::Path) -> Option<&std::pat////// ```ignore/// // Prepare and spawn hooks with display path:-/// for steps in prepare_background_hooks(&ctx, HookType::PostStart, &extra_vars, post_hook_display_path(&destination))? {-/// spawn_hook_pipeline(&ctx, steps)?;-/// }+/// spawn_background_hooks(&ctx, HookType::PostStart, &extra_vars, post_hook_display_path(&destination))?;/// ```pub fn post_hook_display_path(destination: &std::path::Path) -> Option<&std::path::Path> {post_hook_display_path_with(destination, is_shell_integration_active())diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex 90ac29cbc..09ccf85b9 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -1449,6 +1449,28 @@ fn test_standalone_hook_post_merge(repo: TestRepo) {assert!(content.contains("STANDALONE_POST_MERGE"));}+#[rstest]+fn test_standalone_hook_post_merge_combined_user_and_project(repo: TestRepo) {+ // Both user and project configs contribute to post-merge — a single+ // `Running post-merge:` announce line must cover both sources.+ repo.write_project_config(r#"post-merge = "echo 'PROJECT_RAN' > project.txt""#);+ repo.write_test_config(+ r#"[post-merge]+notify = "echo 'USER_RAN' > user.txt"+"#,+ );++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "hook", &["post-merge", "--yes"], None);+ assert_cmd_snapshot!("standalone_hook_post_merge_combined_sources", cmd);+ });++ let root = repo.root_path();+ wait_for_file(&root.join("user.txt"));+ wait_for_file(&root.join("project.txt"));+}+#[rstest]fn test_standalone_hook_pre_remove(repo: TestRepo) {// Write project config with pre-remove hookdiff --git a/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_post_merge_combined_sources.snap b/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_post_merge_combined_sources.snapnew file mode 100644index 000000000..2f469c629--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__standalone_hook_post_merge_combined_sources.snap@@ -0,0 +1,48 @@+---+source: tests/integration_tests/user_hooks.rs+info:+ program: wt+ args:+ - hook+ - post-merge+ - "--yes"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ 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: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ NO_COLOR: ""+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[36m◎[39m [36mRunning post-merge: [1muser:notify[22m, [1mproject[22m[39m