Skip to content

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

feat: show branch name in hook announcements during batch removal (#2014)

Maximilian Roos50a9fd2075aa
diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rs
index af0e08594..ac5f0e83b 100644
--- a/src/commands/handle_switch.rs
+++ b/src/commands/handle_switch.rs
@@ -262,7 +262,7 @@ pub(crate) fn spawn_switch_background_hooks(
);
}
- super::hooks::announce_and_spawn_background_hooks(pipelines)
+ super::hooks::announce_and_spawn_background_hooks(pipelines, false)
}
/// Handle the switch command.
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index fa7178176..8ce047c2f 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -253,9 +253,14 @@ fn format_unnamed(source_label: &str, count: usize) -> String {
/// can use different contexts (e.g., post-remove uses the removed branch while
/// post-switch uses the destination branch).
///
-/// Example output: `Running post-switch: zellij-tab; post-start: deps, assets, docs`
+/// When `show_branch` is true, includes the branch name for disambiguation in batch
+/// contexts (e.g., prune removing multiple worktrees):
+/// `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 fn announce_and_spawn_background_hooks(
pipelines: Vec<(CommandContext<'_>, Vec<SourcedStep>)>,
+ show_branch: bool,
) -> anyhow::Result<()> {
let non_empty: Vec<_> = pipelines
.into_iter()
@@ -285,9 +290,24 @@ pub fn announce_and_spawn_background_hooks(
}
}
+ // In batch contexts (prune), use the first pipeline's branch for disambiguation.
+ // This is the removed branch — it identifies the triggering event even for
+ // post-switch hooks that fire as a consequence of the removal.
+ let branch_suffix = if show_branch {
+ non_empty
+ .first()
+ .and_then(|(ctx, _)| ctx.branch)
+ .map(|b| cformat!(" for <bold>{b}</>"))
+ } else {
+ None
+ };
+
let combined: String = type_summaries
.iter()
- .map(|(ht, summaries)| format!("{ht}: {}", summaries.join(", ")))
+ .map(|(ht, summaries)| {
+ let suffix = branch_suffix.as_deref().unwrap_or("");
+ format!("{ht}{suffix}: {}", summaries.join(", "))
+ })
.collect::<Vec<_>>()
.join("; ");
let message = match display_path {
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index fe8f34efe..54888bddc 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -328,7 +328,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)?;
+ crate::output::handle_remove_output(&remove_result, false, verify, false, false)?;
true
};
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index fd20e5c49..cb721f723 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -1427,7 +1427,7 @@ pub fn step_prune(
return Ok(false);
}
};
- handle_remove_output(&plan, foreground, run_hooks, true)?;
+ handle_remove_output(&plan, foreground, run_hooks, true, true)?;
Ok(true)
}
diff --git a/src/main.rs b/src/main.rs
index ddd80c3e7..c66357cfa 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -765,7 +765,7 @@ fn handle_remove_command(args: RemoveArgs) -> anyhow::Result<()> {
// "Approve at the Gate": approval happens AFTER validation passes
let run_hooks = verify && approve_remove(args.yes)?;
- handle_remove_output(&result, args.foreground, run_hooks, false)?;
+ handle_remove_output(&result, args.foreground, run_hooks, false, false)?;
if json_mode {
let json = serde_json::json!([result.to_json()]);
println!("{}", serde_json::to_string_pretty(&json)?);
@@ -797,14 +797,16 @@ fn handle_remove_command(args: RemoveArgs) -> anyhow::Result<()> {
let run_hooks = verify && approve_remove(args.yes)?;
// 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 {
- handle_remove_output(result, args.foreground, run_hooks, false)?;
+ handle_remove_output(result, args.foreground, run_hooks, false, show_branch)?;
}
for result in &plans.branch_only {
- handle_remove_output(result, args.foreground, run_hooks, false)?;
+ handle_remove_output(result, args.foreground, run_hooks, false, show_branch)?;
}
if let Some(ref result) = plans.current {
- handle_remove_output(result, args.foreground, run_hooks, false)?;
+ handle_remove_output(result, args.foreground, run_hooks, false, show_branch)?;
}
if json_mode {
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 5aef851ad..846e4c89f 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -696,6 +696,7 @@ pub fn handle_remove_output(
foreground: bool,
verify: bool,
quiet: bool,
+ show_branch_in_hooks: bool,
) -> anyhow::Result<()> {
match result {
RemoveResult::RemovedWorktree {
@@ -722,6 +723,7 @@ pub fn handle_remove_output(
removed_commit: removed_commit.as_deref(),
foreground,
verify,
+ show_branch_in_hooks,
}),
RemoveResult::BranchOnly {
branch_name,
@@ -841,17 +843,13 @@ fn handle_branch_only_output(
/// 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).
///
-/// Only runs if `verify` is true (hooks approved).
+/// Only runs if `ctx.verify` is true (hooks approved).
fn spawn_hooks_after_remove(
repo: &Repository,
- main_path: &std::path::Path,
- removed_worktree_path: &std::path::Path,
+ ctx: &RemovedWorktreeOutputContext<'_>,
removed_branch: &str,
- removed_commit: Option<&str>,
- verify: bool,
- changed_directory: bool,
) -> anyhow::Result<()> {
- if !verify {
+ if !ctx.verify {
return Ok(());
}
let Ok(config) = UserConfig::load() else {
@@ -862,20 +860,20 @@ fn spawn_hooks_after_remove(
// (suppresses path if shell integration will cd there).
// When removing a different worktree, user stays at cwd → use pre_hook logic
// (shows path if main_path differs from cwd).
- let display_path = if changed_directory {
- super::post_hook_display_path(main_path)
+ let display_path = if ctx.changed_directory {
+ super::post_hook_display_path(ctx.main_path)
} else {
- super::pre_hook_display_path(main_path)
+ super::pre_hook_display_path(ctx.main_path)
};
// Build post-remove template variables from the removed worktree identity.
let remove_vars =
- PostRemoveContext::new(removed_worktree_path, removed_commit, main_path, repo);
+ PostRemoveContext::new(ctx.worktree_path, ctx.removed_commit, ctx.main_path, repo);
let extra_vars = remove_vars.extra_vars(removed_branch);
// All hooks use remove_ctx for spawning: log files are named after the removed
// branch since both post-remove and post-switch are consequences of that removal.
- let remove_ctx = CommandContext::new(repo, &config, Some(removed_branch), main_path, false);
+ let remove_ctx = CommandContext::new(repo, &config, Some(removed_branch), ctx.main_path, false);
// Collect post-remove and post-switch hooks for a single combined announcement.
let mut pipelines = Vec::new();
@@ -893,14 +891,14 @@ fn spawn_hooks_after_remove(
// Post-switch: only when the user actually changed directory.
// Uses its own context with the destination branch for template variables.
// dest_branch hoisted so it outlives the pipelines vec.
- let dest_branch = if changed_directory {
- Some(repo.worktree_at(main_path).branch()?)
+ let dest_branch = if ctx.changed_directory {
+ Some(repo.worktree_at(ctx.main_path).branch()?)
} else {
None
};
if let Some(ref dest_branch) = dest_branch {
let switch_ctx =
- CommandContext::new(repo, &config, dest_branch.as_deref(), main_path, false);
+ CommandContext::new(repo, &config, dest_branch.as_deref(), ctx.main_path, false);
pipelines.extend(
prepare_background_hooks(
&switch_ctx,
@@ -913,7 +911,7 @@ fn spawn_hooks_after_remove(
);
}
- announce_and_spawn_background_hooks(pipelines)?;
+ announce_and_spawn_background_hooks(pipelines, ctx.show_branch_in_hooks)?;
Ok(())
}
@@ -1126,6 +1124,8 @@ 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(
@@ -1246,15 +1246,7 @@ fn handle_detached_removed_worktree_output(
}
// Post-remove hooks for detached HEAD use "HEAD" as the branch identifier
- spawn_hooks_after_remove(
- repo,
- ctx.main_path,
- ctx.worktree_path,
- "HEAD",
- ctx.removed_commit,
- ctx.verify,
- ctx.changed_directory,
- )?;
+ spawn_hooks_after_remove(repo, ctx, "HEAD")?;
stderr().flush()?;
Ok(())
}
@@ -1306,15 +1298,7 @@ fn handle_named_removed_worktree_foreground(
display_info.print_hints(branch_name, ctx.deletion_mode, ctx.pre_computed_integration)?;
print_switch_message_if_changed(ctx.changed_directory, ctx.main_path)?;
- spawn_hooks_after_remove(
- repo,
- ctx.main_path,
- ctx.worktree_path,
- branch_name,
- ctx.removed_commit,
- ctx.verify,
- ctx.changed_directory,
- )?;
+ spawn_hooks_after_remove(repo, ctx, branch_name)?;
stderr().flush()?;
Ok(())
}
@@ -1352,15 +1336,7 @@ fn handle_named_removed_worktree_background(
ctx.changed_directory,
)?;
- spawn_hooks_after_remove(
- repo,
- ctx.main_path,
- ctx.worktree_path,
- branch_name,
- ctx.removed_commit,
- ctx.verify,
- ctx.changed_directory,
- )?;
+ spawn_hooks_after_remove(repo, ctx, branch_name)?;
stderr().flush()?;
Ok(())
}
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index 014674c48..364f3b7d5 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -779,3 +779,23 @@ fn test_prune_json_orphan_branch(repo: TestRepo) {
assert_snapshot!(String::from_utf8_lossy(&output.stdout));
}
+
+/// Hook announcements during prune include the branch name for disambiguation
+#[rstest]
+fn test_prune_hook_announcements_include_branch(mut repo: TestRepo) {
+ repo.commit("initial");
+
+ // Use branch names that don't collide with the fixture's feature-a/b/c
+ repo.add_worktree("merged-x");
+ repo.add_worktree("merged-y");
+
+ repo.write_test_config(
+ r#"[post-remove]
+cleanup = "echo done"
+"#,
+ );
+
+ let mut cmd = make_snapshot_cmd(&repo, "step", &["prune", "--yes", "--min-age=0s"], None);
+ cmd.env("RAYON_NUM_THREADS", "1");
+ assert_cmd_snapshot!(cmd);
+}
diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_hook_announcements_include_branch.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_hook_announcements_include_branch.snap
new file mode 100644
index 000000000..aae57262b
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_hook_announcements_include_branch.snap
@@ -0,0 +1,54 @@
+---
+source: tests/integration_tests/step_prune.rs
+info:
+ program: wt
+ args:
+ - step
+ - prune
+ - "--yes"
+ - "--min-age=0s"
+ 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: ""
+ RAYON_NUM_THREADS: "1"
+ 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 -----
+◎ Removing merged-x worktree & branch in background (same commit as main, _)
+◎ Running post-remove for merged-x: user:cleanup
+◎ Removing merged-y worktree & branch in background (same commit as main, _)
+◎ Running post-remove for merged-y: user:cleanup
+✓ Pruned 2 worktrees & branches