Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(hooks): route post-commit and post-switch through HookAnnouncer (#2482)
Maximilian Roosf499ec0590fe
diff --git a/src/commands/commit.rs b/src/commands/commit.rsindex fd090a108..13ca4ace5 100644--- a/src/commands/commit.rs+++ b/src/commands/commit.rs@@ -8,7 +8,9 @@ use worktrunk::styling::{use super::command_executor::CommandContext;use super::command_executor::FailureStrategy;-use super::hooks::{execute_hook, spawn_background_hooks};+use super::hooks::{+ HookAnnouncer, execute_hook, prepare_background_pipelines, run_hooks_background,+};use super::repository_ext::warn_about_untracked_files;use super::template_vars::TemplateVars;@@ -154,9 +156,14 @@ impl<'a> CommitGenerator<'a> {}}-/// Commit uncommitted changes with the shared commit pipeline.impl CommitOptions<'_> {- pub fn commit(self) -> anyhow::Result<()> {+ /// Commit uncommitted changes with the shared commit pipeline.+ ///+ /// `announcer`: when `Some`, post-commit pipelines are extended onto the+ /// caller's announcer so they share an announce line with later phases+ /// (e.g. `wt merge --squash` batching post-commit + post-remove ++ /// post-switch + post-merge). When `None`, post-commit self-announces.+ pub fn commit(self, announcer: Option<&mut HookAnnouncer<'_>>) -> anyhow::Result<()> {let project_config = self.ctx.repo.load_project_config()?;let user_hooks = self.ctx.config.hooks(self.ctx.project_id().as_deref());let (user_cfg, proj_cfg) = super::hooks::lookup_hook_configs(@@ -222,10 +229,16 @@ impl CommitOptions<'_> {self.stage_mode,)?;- // Spawn post-commit hooks in background (respects --no-hooks)+ // Spawn post-commit hooks in background (respects --no-hooks).if self.verify {let extra_vars = template_vars.as_extra_vars();- spawn_background_hooks(self.ctx, HookType::PostCommit, &extra_vars, None)?;+ let pipelines =+ prepare_background_pipelines(self.ctx, HookType::PostCommit, &extra_vars, None)?;+ if let Some(announcer) = announcer {+ announcer.extend(pipelines);+ } else {+ run_hooks_background(pipelines, false)?;+ }}Ok(())diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rsindex 722dab5fc..4d952899c 100644--- a/src/commands/handle_switch.rs+++ b/src/commands/handle_switch.rs@@ -16,7 +16,7 @@ use crate::cli::SwitchFormat;use super::command_approval::{approve_hooks, approve_or_skip};use super::command_executor::FailureStrategy;use super::command_executor::{CommandContext, build_hook_context};-use super::hooks::{execute_hook, prepare_background_pipelines, run_hooks_background};+use super::hooks::{HookAnnouncer, execute_hook};use super::template_vars::TemplateVars;use super::worktree::{SwitchBranchInfo, SwitchPlan, SwitchResult, execute_switch, offer_bare_repo_worktree_path_fix,@@ -196,19 +196,12 @@ pub(crate) fn spawn_switch_background_hooks() -> anyhow::Result<()> {let ctx = CommandContext::new(repo, config, branch, result.path(), yes);- let mut pipelines =- prepare_background_pipelines(&ctx, HookType::PostSwitch, extra_vars, hooks_display_path)?;-+ let mut announcer = HookAnnouncer::new(repo, config, false);+ announcer.register(&ctx, HookType::PostSwitch, extra_vars, hooks_display_path)?;if matches!(result, SwitchResult::Created { .. }) {- pipelines.extend(prepare_background_pipelines(- &ctx,- HookType::PostStart,- extra_vars,- hooks_display_path,- )?);+ announcer.register(&ctx, HookType::PostStart, extra_vars, hooks_display_path)?;}-- run_hooks_background(pipelines, false)+ announcer.flush()}/// Handle the switch command.diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 7247676a9..feca65164 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -770,23 +770,6 @@ pub(crate) fn lookup_hook_configs<'a>()}-/// Spawn background hooks for a single hook type (post-commit, post-merge, …).-///-/// Symmetric to [`execute_hook`] for the background path: a one-shot-/// convenience that constructs a single-phase [`HookAnnouncer`], registers the-/// hook type, and flushes. Multi-phase callers should build a [`HookAnnouncer`]-/// directly and call `register` per phase so all types share one announce line.-pub(crate) fn spawn_background_hooks(- ctx: &CommandContext,- hook_type: HookType,- extra_vars: &[(&str, &str)],- display_path: Option<&Path>,-) -> anyhow::Result<()> {- let mut announcer = HookAnnouncer::new(ctx.repo, ctx.config, false);- announcer.register(ctx, hook_type, extra_vars, display_path)?;- announcer.flush()-}-/// Run a single hook type in the foreground for an operation (merge, switch,/// commit, remove, …).///diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex da785e76d..fcce18a9b 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -197,6 +197,12 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {false};+ // One announcer for the whole command's background hooks: post-commit+ // (from auto-commit or squash), post-remove + post-switch (from worktree+ // removal), and post-merge share a single `◎ Running …` line flushed at+ // the end.+ let mut announcer = HookAnnouncer::new(repo, config, false);+// Handle uncommitted changes (skip if --no-commit) - track whether commit occurredlet committed = if commit && current_wt.is_dirty()? {if squash_enabled {@@ -210,7 +216,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {options.warn_about_untracked = stage_mode == super::commit::StageMode::All;options.show_no_squash_note = true;- options.commit()?;+ options.commit(Some(&mut announcer))?;true // Committed directly}} else {@@ -224,7 +230,8 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {Some(&target_branch),yes,verify,- Some(stage_mode)+ Some(stage_mode),+ Some(&mut announcer),)?,super::step_commands::SquashResult::Squashed)@@ -297,11 +304,6 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {feature_vars = feature_vars.with_active_commit(commit);}- // One announcer for the whole command's background hooks: post-remove +- // post-switch (from worktree removal) and post-merge share a single- // `◎ Running …` line, flushed at the end.- let mut announcer = HookAnnouncer::new(repo, config, false);-// Finish worktree unless removal is disabled or blocked.// Guards are shared with `wt remove`: is_primary_worktree (Phase 2) and// check_not_default_branch (Phase 3) are the same helpers both paths use.diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 4e6b1ed5e..d1280bc8f 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -112,7 +112,7 @@ use super::command_executor::FailureStrategy;use super::handle_switch::{approve_switch_hooks, run_pre_switch_hooks, spawn_switch_background_hooks,};-use super::hooks::{execute_hook, spawn_background_hooks};+use super::hooks::{execute_hook, prepare_background_pipelines, run_hooks_background};use super::list::collect;use super::list::progressive::RenderTarget;use super::repository_ext::{RemoveTarget, RepositoryCliExt};@@ -231,12 +231,13 @@ impl PickerCollector {&repo,);let extra_vars = remove_vars.extra_vars(hook_branch);- spawn_background_hooks(+ let pipelines = prepare_background_pipelines(&post_ctx,worktrunk::HookType::PostRemove,&extra_vars,None, // no display path in TUI context)?;+ run_hooks_background(pipelines, false)?;}RemoveResult::BranchOnly {branch_name,diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex f86cd54d5..e55f98ca1 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -39,7 +39,9 @@ use super::command_approval::approve_or_skip;use super::command_executor::FailureStrategy;use super::commit::{CommitGenerator, CommitOptions, StageMode};use super::context::CommandEnv;-use super::hooks::{execute_hook, spawn_background_hooks};+use super::hooks::{+ HookAnnouncer, execute_hook, prepare_background_pipelines, run_hooks_background,+};use super::repository_ext::{RemoveTarget, RepositoryCliExt};use super::template_vars::TemplateVars;use crate::output::handle_remove_output;@@ -96,7 +98,7 @@ pub fn step_commit(// Only warn about untracked if we're staging alloptions.warn_about_untracked = stage_mode == StageMode::All;- options.commit()+ options.commit(None)}/// Result of a squash operation@@ -117,11 +119,16 @@ pub enum SquashResult {/// # Arguments/// * `verify` - If true, run pre-commit hooks (false when --no-hooks flag is passed)/// * `stage` - CLI-provided stage mode. If None, uses the effective config default.+/// * `parent_announcer` - When `Some`, post-commit hooks register on the+/// caller's announcer so they share an announce line with later phases+/// (e.g. `wt merge --squash` combining post-commit + post-remove ++/// post-switch + post-merge). When `None`, post-commit self-announces.pub fn handle_squash(target: Option<&str>,yes: bool,verify: bool,stage: Option<StageMode>,+ parent_announcer: Option<&mut HookAnnouncer<'_>>,) -> anyhow::Result<SquashResult> {// Load config once, run LLM setup prompt, then reuse configlet mut config = UserConfig::load().context("Failed to load config")?;@@ -341,10 +348,16 @@ pub fn handle_squash(success_message(cformat!("Squashed @ <dim>{commit_hash}</>")));- // Spawn post-commit hooks in background (respects --no-hooks)+ // Spawn post-commit hooks in background (respects --no-hooks).if verify {let extra_vars = template_vars.as_extra_vars();- spawn_background_hooks(&ctx, HookType::PostCommit, &extra_vars, None)?;+ let pipelines =+ prepare_background_pipelines(&ctx, HookType::PostCommit, &extra_vars, None)?;+ if let Some(announcer) = parent_announcer {+ announcer.extend(pipelines);+ } else {+ run_hooks_background(pipelines, false)?;+ }}Ok(SquashResult::Squashed)diff --git a/src/main.rs b/src/main.rsindex 485f85149..2555c0950 100644--- a/src/main.rs+++ b/src/main.rs@@ -215,7 +215,7 @@ fn handle_step_command(action: StepCommand, yes: bool) -> anyhow::Result<()> {commands::step_show_squash_prompt(args.target.as_deref())} else {// Approval is handled inside handle_squash (like step_commit)- handle_squash(args.target.as_deref(), yes, verify, args.stage).map(|result| {+ handle_squash(args.target.as_deref(), yes, verify, args.stage, None).map(|result| {match result {SquashResult::Squashed | SquashResult::NoNetChanges => {}SquashResult::NoCommitsAhead(branch) => {diff --git a/src/output/global.rs b/src/output/global.rsindex f3e397b89..67ca1dec0 100644--- a/src/output/global.rs+++ b/src/output/global.rs@@ -602,7 +602,8 @@ pub fn pre_hook_display_path(hooks_run_at: &std::path::Path) -> Option<&std::pat////// ```ignore/// // Spawn hooks with display path:-/// spawn_background_hooks(&ctx, HookType::PostStart, &extra_vars, post_hook_display_path(&destination))?;+/// let pipelines = prepare_background_pipelines(&ctx, HookType::PostStart, &extra_vars, post_hook_display_path(&destination))?;+/// run_hooks_background(pipelines, false)?;/// ```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 21d355dd3..f4bd6cd9e 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -955,6 +955,77 @@ sync = "echo merged");}+/// `wt merge` (no squash) with uncommitted changes auto-commits via+/// `CommitOptions::commit`, which threads the merge announcer through. The+/// post-commit phase should join post-remove + post-switch + post-merge on+/// one combined announce line — the non-squash sibling of+/// [`test_merge_squash_combines_post_commit_post_remove_post_switch_post_merge`].+#[rstest]+fn test_merge_auto_commit_combines_post_commit_post_remove_post_switch_post_merge(+ mut repo: TestRepo,+) {+ let feature_wt =+ repo.add_worktree_with_commit("feature", "feature.txt", "feature", "Add feature");+ // Leave an uncommitted change so the merge auto-commits via+ // CommitOptions::commit (the path that exercises the announcer Some arm).+ std::fs::write(feature_wt.join("dirty.txt"), "uncommitted").unwrap();++ repo.write_test_config(+ r#"[post-commit]+mark = "echo committed"++[post-remove]+cleanup = "echo removed"++[post-switch]+notify = "echo switched"++[post-merge]+sync = "echo merged"+"#,+ );++ snapshot_merge(+ "merge_auto_commit_combines_post_commit_post_remove_post_switch_post_merge",+ &repo,+ &["main", "--yes", "--no-squash"],+ Some(&feature_wt),+ );+}++/// `wt merge --squash` fires post-commit (from the squash phase), post-remove,+/// post-switch (from worktree removal), and post-merge. All four should share+/// one `Running …` announce line so the user sees a single status line for+/// the whole command, not four.+#[rstest]+fn test_merge_squash_combines_post_commit_post_remove_post_switch_post_merge(mut repo: TestRepo) {+ // Squash needs >1 commit ahead of main to actually run.+ let feature_wt = repo.add_worktree_with_commit("feature", "feature1.txt", "one", "feat: one");+ repo.commit_in_worktree(&feature_wt, "feature2.txt", "two", "feat: two");++ repo.write_test_config(+ r#"[post-commit]+mark = "echo committed"++[post-remove]+cleanup = "echo removed"++[post-switch]+notify = "echo switched"++[post-merge]+sync = "echo merged"+"#,+ );++ snapshot_merge(+ "merge_squash_combines_post_commit_post_remove_post_switch_post_merge",+ &repo,+ &["main", "--yes", "--squash"],+ Some(&feature_wt),+ );+}+/// When post-merge template prep errors after post-remove + post-switch are/// already registered, the announcer's `Drop` impl flushes the pending hooks/// so they still spawn — preserving the prior fire-and-forget behavior indiff --git a/tests/snapshots/integration__integration_tests__user_hooks__merge_auto_commit_combines_post_commit_post_remove_post_switch_post_merge.snap b/tests/snapshots/integration__integration_tests__user_hooks__merge_auto_commit_combines_post_commit_post_remove_post_switch_post_merge.snapnew file mode 100644index 000000000..ed7ce0238--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__merge_auto_commit_combines_post_commit_post_remove_post_switch_post_merge.snap@@ -0,0 +1,66 @@+---+source: tests/integration_tests/user_hooks.rs+info:+ program: wt+ args:+ - merge+ - main+ - "--yes"+ - "--no-squash"+ 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 -----+[33m▲[39m [33mAuto-staging 1 untracked path:[39m+[107m [0m dirty.txt+[36m◎[39m [36mCommitting changes with default message... [90m(1 file, [32m+1[39m, no squashing needed[39m[90m)[39m[39m+[2m↳[22m [2mUsing fallback commit message. For LLM setup guide, run [4mwt config --help[24m[22m+[107m [0m [1mChanges to dirty.txt[22m+[32m✓[39m [32mCommitted changes @ [2m[HASH][22m[39m+[36m◎[39m [36mMerging 2 commits to [1mmain[22m @ [2m[HASH][22m (no rebase needed)[39m+[107m [0m * [33m[HASH][m Changes to dirty.txt+[107m [0m * [33m[HASH][m Add feature+[107m [0m dirty.txt | 1 [32m+[m+[107m [0m feature.txt | 1 [32m+[m+[107m [0m 2 files changed, 2 insertions(+)+[32m✓[39m [32mMerged to [1mmain[22m [90m(2 commits, 2 files, [32m+2[39m[39m[90m)[39m[39m+[36m◎[39m [36mRemoving [1mfeature[22m worktree in background[39m+[2m↳[22m [2mBranch unmerged; to delete, run [4mwt remove -D feature[24m[22m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [4mwt config shell install[24m[22m+[36m◎[39m [36mRunning post-commit: [1muser:mark[22m; post-remove: [1muser:cleanup[22m; post-switch: [1muser:notify[22m; post-merge: [1muser:sync[22m @ [1m_REPO_[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__user_hooks__merge_squash_combines_post_commit_post_remove_post_switch_post_merge.snap b/tests/snapshots/integration__integration_tests__user_hooks__merge_squash_combines_post_commit_post_remove_post_switch_post_merge.snapnew file mode 100644index 000000000..582f6ae55--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__merge_squash_combines_post_commit_post_remove_post_switch_post_merge.snap@@ -0,0 +1,67 @@+---+source: tests/integration_tests/user_hooks.rs+info:+ program: wt+ args:+ - merge+ - main+ - "--yes"+ - "--squash"+ 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 [36mSquashing 2 commits into a single commit [90m(2 files, [32m+2[39m[39m[90m)[39m...[39m+[36m◎[39m [36mGenerating squash commit message...[39m+[2m↳[22m [2mUsing fallback commit message. For LLM setup guide, run [4mwt config --help[24m[22m+[107m [0m [1mSquash commits from feature[22m+[107m [0m+[107m [0m Combined commits:+[107m [0m - feat: one+[107m [0m - feat: two+[32m✓[39m [32mSquashed @ [HASH][39m+[36m◎[39m [36mMerging 1 commit to [1mmain[22m @ [2m[HASH][22m (no rebase needed)[39m+[107m [0m * [33m[HASH][m Squash commits from feature+[107m [0m feature1.txt | 1 [32m+[m+[107m [0m feature2.txt | 1 [32m+[m+[107m [0m 2 files changed, 2 insertions(+)+[32m✓[39m [32mMerged to [1mmain[22m [90m(1 commit, 2 files, [32m+2[39m[39m[90m)[39m[39m+[36m◎[39m [36mRemoving [1mfeature[22m worktree & branch in background (same commit as [1mmain[22m,[39m [2m_[22m[36m)[39m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [4mwt config shell install[24m[22m+[36m◎[39m [36mRunning post-commit: [1muser:mark[22m; post-remove: [1muser:cleanup[22m; post-switch: [1muser:notify[22m; post-merge: [1muser:sync[22m @ [1m_REPO_[22m[39m