Skip to content

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

refactor(hooks): make HookAnnouncer the single entry point (#2484)

Maximilian Roos7d354c797612
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index da9956d7d..50c62b070 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -8,9 +8,7 @@ use worktrunk::styling::{
use super::command_executor::CommandContext;
use super::command_executor::FailureStrategy;
-use super::hooks::{
- HookAnnouncer, execute_hook, prepare_background_pipelines, run_hooks_background,
-};
+use super::hooks::{HookAnnouncer, execute_hook};
use super::repository_ext::warn_about_untracked_files;
use super::template_vars::TemplateVars;
@@ -191,11 +189,12 @@ impl<'a> CommitGenerator<'a> {
impl CommitOptions<'_> {
/// 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<()> {
+ /// Post-commit pipelines are registered onto the caller's announcer; the
+ /// caller decides when to flush. Multi-phase callers (e.g. `wt merge
+ /// --squash` batching post-commit + post-remove + post-switch + post-merge)
+ /// share one announce line; standalone callers (e.g. `wt commit`)
+ /// construct an announcer of their own and flush right after.
+ pub fn commit(self, announcer: &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(
@@ -263,16 +262,10 @@ impl CommitOptions<'_> {
self.stage_mode,
)?;
- // Spawn post-commit hooks in background (respects --no-hooks).
+ // Register post-commit hooks onto the caller's announcer (respects --no-hooks).
if self.hooks.run() {
let extra_vars = template_vars.as_extra_vars();
- 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)?;
- }
+ announcer.register(self.ctx, HookType::PostCommit, &extra_vars, None)?;
}
Ok(())
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index 2e31a944d..359b3d177 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -28,8 +28,7 @@ use super::command_executor::CommandContext;
use super::command_executor::FailureStrategy;
use super::context::CommandEnv;
use super::hooks::{
- HookCommandSpec, lookup_hook_configs, prepare_and_check, prepare_background_pipelines,
- run_hooks_background, run_hooks_foreground,
+ HookAnnouncer, HookCommandSpec, lookup_hook_configs, prepare_and_check, run_hooks_foreground,
};
use super::template_vars::TemplateVars;
@@ -81,8 +80,9 @@ fn run_post_hook(
// Filter path merges user + project matches into one pipeline (the user
// cherry-picked specific names across sources). The default path keeps
// sources independent so a user hook failure doesn't abort project hooks.
- let pipelines = if name_filters.is_empty() {
- prepare_background_pipelines(ctx, hook_type, extra_vars, None)?
+ let mut announcer = HookAnnouncer::new(ctx.repo, ctx.config, false);
+ if name_filters.is_empty() {
+ announcer.register(ctx, hook_type, extra_vars, None)?;
} else {
let flat = prepare_and_check(
ctx,
@@ -98,9 +98,9 @@ fn run_post_hook(
if flat.is_empty() {
return Ok(());
}
- vec![(*ctx, flat)]
- };
- run_hooks_background(pipelines, false)
+ announcer.extend(std::iter::once((*ctx, flat)));
+ }
+ announcer.flush()
}
/// Build best-effort directional vars for manual `wt hook` invocation.
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index feca65164..3d03b2186 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -386,10 +386,10 @@ impl Drop for HookAnnouncer<'_> {
/// Announce and spawn background hook pipelines.
///
-/// Internal primitive: sites should construct a [`HookAnnouncer`] (one per
-/// command) and `register`/`extend` into it; `flush` lands here. The function
-/// stays separate to keep the announce/spawn formatting isolated from the
-/// announcer's pending-list bookkeeping.
+/// Module-private implementation of [`HookAnnouncer::flush`] — sites construct
+/// a [`HookAnnouncer`] (one per command) and `register`/`extend` into it;
+/// `flush` lands here. The function stays separate to keep the announce/spawn
+/// formatting isolated from the announcer's pending-list bookkeeping.
///
/// Displays a single combined summary line covering all hook types, then
/// spawns each pipeline independently. Pipelines may carry different
@@ -401,7 +401,7 @@ impl Drop for HookAnnouncer<'_> {
/// `Running post-remove for feature: docs; post-switch for feature: zellij-tab`
///
/// Without `show_branch`: `Running post-switch: zellij-tab; post-start: deps, assets, docs`
-pub(crate) fn run_hooks_background(
+fn run_hooks_background(
pipelines: Vec<(CommandContext<'_>, Vec<SourcedStep>)>,
show_branch: bool,
) -> anyhow::Result<()> {
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 9187d6451..91bcca61b 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -222,7 +222,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(Some(&mut announcer))?;
+ options.commit(&mut announcer)?;
true // Committed directly
}
} else {
@@ -239,7 +239,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
yes,
commit_hooks,
Some(stage_mode),
- Some(&mut announcer),
+ &mut announcer,
)?,
super::step_commands::SquashResult::Squashed
)
@@ -355,14 +355,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
expected_path,
removed_commit: feature_commit.clone(),
};
- crate::output::handle_remove_output(
- &remove_result,
- false,
- verify,
- false,
- false,
- Some(&mut announcer),
- )?;
+ crate::output::handle_remove_output(&remove_result, false, verify, false, &mut announcer)?;
true
};
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index d1280bc8f..10a012aca 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, prepare_background_pipelines, run_hooks_background};
+use super::hooks::{HookAnnouncer, execute_hook};
use super::list::collect;
use super::list::progressive::RenderTarget;
use super::repository_ext::{RemoveTarget, RepositoryCliExt};
@@ -231,13 +231,14 @@ impl PickerCollector {
&repo,
);
let extra_vars = remove_vars.extra_vars(hook_branch);
- let pipelines = prepare_background_pipelines(
+ let mut announcer = HookAnnouncer::new(&repo, config, false);
+ announcer.register(
&post_ctx,
worktrunk::HookType::PostRemove,
&extra_vars,
None, // no display path in TUI context
)?;
- run_hooks_background(pipelines, false)?;
+ announcer.flush()?;
}
RemoveResult::BranchOnly {
branch_name,
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index cd341232b..6315c76b9 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -39,9 +39,7 @@ use super::command_approval::approve_or_skip;
use super::command_executor::FailureStrategy;
use super::commit::{CommitGenerator, CommitOptions, HookGate, StageMode};
use super::context::CommandEnv;
-use super::hooks::{
- HookAnnouncer, execute_hook, prepare_background_pipelines, run_hooks_background,
-};
+use super::hooks::{HookAnnouncer, execute_hook};
use super::repository_ext::{RemoveTarget, RepositoryCliExt};
use super::template_vars::TemplateVars;
use crate::output::handle_remove_output;
@@ -99,7 +97,9 @@ pub fn step_commit(
// Only warn about untracked if we're staging all
options.warn_about_untracked = stage_mode == StageMode::All;
- options.commit(None)
+ let mut announcer = HookAnnouncer::new(ctx.repo, ctx.config, false);
+ options.commit(&mut announcer)?;
+ announcer.flush()
}
/// Result of a squash operation
@@ -122,16 +122,17 @@ pub enum SquashResult {
/// prompt; `NoHooksFlag` skips with a "(--no-hooks)" message; `Silent` skips silently
/// (used when the caller already declined approval upstream and announced it).
/// * `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.
+/// * `announcer` - Post-commit hooks register on the caller's announcer; the
+/// caller decides when to flush. Multi-phase callers (`wt merge --squash`
+/// combining post-commit + post-remove + post-switch + post-merge) share
+/// one announce line; standalone callers (`wt step squash`) construct an
+/// announcer of their own and flush right after.
pub fn handle_squash(
target: Option<&str>,
yes: bool,
hooks: HookGate,
stage: Option<StageMode>,
- parent_announcer: Option<&mut HookAnnouncer<'_>>,
+ announcer: &mut HookAnnouncer<'_>,
) -> anyhow::Result<SquashResult> {
// Load config once, run LLM setup prompt, then reuse config
let mut config = UserConfig::load().context("Failed to load config")?;
@@ -360,16 +361,10 @@ pub fn handle_squash(
success_message(cformat!("Squashed @ <dim>{commit_hash}</>"))
);
- // Spawn post-commit hooks in background (respects --no-hooks).
+ // Register post-commit hooks onto the caller's announcer (respects --no-hooks).
if hooks.run() {
let extra_vars = template_vars.as_extra_vars();
- 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)?;
- }
+ announcer.register(&ctx, HookType::PostCommit, &extra_vars, None)?;
}
Ok(SquashResult::Squashed)
@@ -1451,7 +1446,9 @@ pub fn step_prune(
return Ok(false);
}
};
- handle_remove_output(&plan, foreground, run_hooks, true, true, None)?;
+ let mut announcer = HookAnnouncer::new(repo, config, true);
+ handle_remove_output(&plan, foreground, run_hooks, true, &mut announcer)?;
+ announcer.flush()?;
Ok(true)
}
diff --git a/src/main.rs b/src/main.rs
index 45266bb7a..05eca70a6 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -17,6 +17,7 @@ use worktrunk::styling::{
use commands::command_approval::approve_or_skip;
use commands::command_executor::CommandContext;
+use commands::hooks::HookAnnouncer;
use commands::worktree::RemoveResult;
mod cli;
@@ -215,31 +216,41 @@ fn handle_step_command(action: StepCommand, yes: bool) -> anyhow::Result<()> {
if args.show_prompt {
commands::step_show_squash_prompt(args.target.as_deref())
} else {
- // Approval is handled inside handle_squash (like step_commit)
+ // Approval is handled inside handle_squash (like step_commit).
+ let repo = Repository::current()?;
+ let config = UserConfig::load().context("Failed to load config")?;
let hooks = if verify {
HookGate::Run
} else {
HookGate::NoHooksFlag
};
- handle_squash(args.target.as_deref(), yes, hooks, args.stage, None).map(|result| {
- match result {
- SquashResult::Squashed | SquashResult::NoNetChanges => {}
- SquashResult::NoCommitsAhead(branch) => {
- eprintln!(
- "{}",
- info_message(format!(
- "Nothing to squash; no commits ahead of {branch}"
- ))
- );
- }
- SquashResult::AlreadySingleCommit => {
- eprintln!(
- "{}",
- info_message("Nothing to squash; already a single commit")
- );
- }
+ let mut announcer = HookAnnouncer::new(&repo, &config, false);
+ let result = handle_squash(
+ args.target.as_deref(),
+ yes,
+ hooks,
+ args.stage,
+ &mut announcer,
+ )?;
+ announcer.flush()?;
+ match result {
+ SquashResult::Squashed | SquashResult::NoNetChanges => {}
+ SquashResult::NoCommitsAhead(branch) => {
+ eprintln!(
+ "{}",
+ info_message(format!(
+ "Nothing to squash; no commits ahead of {branch}"
+ ))
+ );
}
- })
+ SquashResult::AlreadySingleCommit => {
+ eprintln!(
+ "{}",
+ info_message("Nothing to squash; already a single commit")
+ );
+ }
+ }
+ Ok(())
}
}
StepCommand::Push { target, no_ff, .. } => {
@@ -808,7 +819,9 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {
// "Approve at the Gate": approval happens AFTER validation passes
let run_hooks = verify && approve_remove(yes)?;
- handle_remove_output(&result, args.foreground, run_hooks, false, false, None)?;
+ let mut announcer = HookAnnouncer::new(&repo, &config, false);
+ handle_remove_output(&result, args.foreground, run_hooks, false, &mut announcer)?;
+ announcer.flush()?;
if json_mode {
let json = serde_json::json!([result.to_json()]);
println!("{}", serde_json::to_string_pretty(&json)?);
@@ -846,35 +859,25 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {
// Execute all validated plans: others first, branch-only next, current last
let show_branch =
plans.others.len() + plans.branch_only.len() + plans.current.iter().len() > 1;
- for result in &plans.others {
+ let run = |result: &RemoveResult| -> anyhow::Result<()> {
+ let mut announcer = HookAnnouncer::new(&repo, &config, show_branch);
handle_remove_output(
result,
args.foreground,
run_hooks,
false,
- show_branch,
- None,
+ &mut announcer,
)?;
+ announcer.flush()
+ };
+ for result in &plans.others {
+ run(result)?;
}
for result in &plans.branch_only {
- handle_remove_output(
- result,
- args.foreground,
- run_hooks,
- false,
- show_branch,
- None,
- )?;
+ run(result)?;
}
if let Some(ref result) = plans.current {
- handle_remove_output(
- result,
- args.foreground,
- run_hooks,
- false,
- show_branch,
- None,
- )?;
+ run(result)?;
}
if json_mode {
diff --git a/src/output/global.rs b/src/output/global.rs
index 67ca1dec0..1a94ae738 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -601,9 +601,8 @@ pub fn pre_hook_display_path(hooks_run_at: &std::path::Path) -> Option<&std::pat
/// # Examples
///
/// ```ignore
-/// // Spawn hooks with display path:
-/// let pipelines = prepare_background_pipelines(&ctx, HookType::PostStart, &extra_vars, post_hook_display_path(&destination))?;
-/// run_hooks_background(pipelines, false)?;
+/// // Register hooks with display path:
+/// announcer.register(&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/src/output/handlers.rs b/src/output/handlers.rs
index 2d0c6b8a8..c97c91abe 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -725,7 +725,9 @@ pub fn execute_user_command(command: &str, display_path: Option<&Path>) -> anyho
/// Handle output for a remove operation
///
-/// Approval is handled at the gate (command entry point), not here.
+/// Approval is handled at the gate (command entry point), not here. The
+/// `announcer`'s `show_branch` setting (set by the caller) controls whether
+/// hook announce lines include the branch name for batch-context disambiguation.
/// When `quiet` is true (prune context), suppresses informational messages
/// like "No worktree found for branch X" that are noise in batch operations.
pub fn handle_remove_output(
@@ -733,8 +735,7 @@ pub fn handle_remove_output(
foreground: bool,
verify: bool,
quiet: bool,
- show_branch_in_hooks: bool,
- announcer: Option<&mut HookAnnouncer<'_>>,
+ announcer: &mut HookAnnouncer<'_>,
) -> anyhow::Result<()> {
match result {
RemoveResult::RemovedWorktree {
@@ -762,7 +763,6 @@ pub fn handle_remove_output(
removed_commit: removed_commit.as_deref(),
foreground,
verify,
- show_branch_in_hooks,
},
announcer,
),
@@ -876,22 +876,22 @@ fn handle_branch_only_output(
Ok(())
}
-/// Register or spawn post-remove and post-switch hooks after worktree removal.
+/// Register post-remove and post-switch hooks after worktree removal onto the
+/// caller's announcer.
///
-/// When `ctx.announcer` is `Some`, pipelines are registered on the caller's
-/// announcer so they can share an announce line with later hooks (e.g.
-/// post-merge in `wt merge`). When `None`, this self-announces and spawns —
-/// the standalone `wt remove` path.
-///
-/// Post-remove template variables reflect the removed worktree (branch, path, commit).
-/// Post-switch hooks only run when `changed_directory` is true (user cd'd to main).
+/// Pipelines come from two contexts: post-remove uses the removed worktree's
+/// identity (branch, path, commit), while post-switch (only when
+/// `changed_directory` is true) uses the destination worktree's branch. Both
+/// types share whatever announce line the caller's announcer eventually
+/// flushes — multi-phase callers (e.g. `wt merge`) batch with later phases,
+/// standalone callers (e.g. `wt remove`) flush immediately after.
///
/// Only runs if `ctx.verify` is true (hooks approved).
fn spawn_hooks_after_remove(
repo: &Repository,
ctx: &RemovedWorktreeOutputContext<'_>,
removed_branch: &str,
- announcer: Option<&mut HookAnnouncer<'_>>,
+ announcer: &mut HookAnnouncer<'_>,
) -> anyhow::Result<()> {
if !ctx.verify {
return Ok(());
@@ -946,14 +946,7 @@ fn spawn_hooks_after_remove(
)?);
}
- if let Some(announcer) = announcer {
- announcer.extend(pipelines);
- } else {
- let mut local = HookAnnouncer::new(repo, &config, ctx.show_branch_in_hooks);
- local.extend(pipelines);
- local.flush()?;
- }
-
+ announcer.extend(pipelines);
Ok(())
}
@@ -1181,8 +1174,6 @@ struct RemovedWorktreeOutputContext<'a> {
removed_commit: Option<&'a str>,
foreground: bool,
verify: bool,
- /// Show branch name in hook announcements for disambiguation in batch contexts.
- show_branch_in_hooks: bool,
}
fn execute_pre_remove_hooks_if_needed(
@@ -1248,7 +1239,7 @@ fn prepare_remove_directory_change(
fn handle_detached_removed_worktree_output(
repo: &Repository,
ctx: &RemovedWorktreeOutputContext<'_>,
- announcer: Option<&mut HookAnnouncer<'_>>,
+ announcer: &mut HookAnnouncer<'_>,
) -> anyhow::Result<()> {
if ctx.foreground {
eprintln!(
@@ -1318,7 +1309,7 @@ fn handle_named_removed_worktree_foreground(
repo: &Repository,
ctx: &RemovedWorktreeOutputContext<'_>,
branch_name: &str,
- announcer: Option<&mut HookAnnouncer<'_>>,
+ announcer: &mut HookAnnouncer<'_>,
) -> anyhow::Result<()> {
eprintln!(
"{}",
@@ -1375,7 +1366,7 @@ fn handle_named_removed_worktree_background(
repo: &Repository,
ctx: &RemovedWorktreeOutputContext<'_>,
branch_name: &str,
- announcer: Option<&mut HookAnnouncer<'_>>,
+ announcer: &mut HookAnnouncer<'_>,
) -> anyhow::Result<()> {
if let Some(expected) = ctx.expected_path {
eprintln!(
@@ -1413,7 +1404,7 @@ fn handle_named_removed_worktree_background(
/// Handle output for RemovedWorktree removal
fn handle_removed_worktree_output(
ctx: RemovedWorktreeOutputContext<'_>,
- announcer: Option<&mut HookAnnouncer<'_>>,
+ announcer: &mut HookAnnouncer<'_>,
) -> anyhow::Result<()> {
// Use main_path for discovery - the worktree being removed might be cwd,
// and git operations after removal need a valid working directory.