Skip to content

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

refactor(hooks): combine post-remove and post-switch into single output line (#943)

Maximilian Roos6db4be8e7e84
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 2ea49f8ab..cc0e7795b 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -473,40 +473,6 @@ pub(crate) fn prepare_background_hooks(
)
}
-/// Spawn hook commands as background processes with automatic config lookup.
-///
-/// This is a convenience wrapper that:
-/// 1. Loads project config from the repository
-/// 2. Looks up user hooks from the config
-/// 3. Prepares and spawns background commands
-///
-/// For spawning multiple hook types in a single message, use `prepare_background_hooks`
-/// to collect hooks, then `spawn_background_hooks` to spawn them.
-pub fn spawn_hook_background(
- ctx: &CommandContext,
- hook_type: HookType,
- extra_vars: &[(&str, &str)],
- name_filter: Option<&str>,
- display_path: Option<&Path>,
-) -> anyhow::Result<()> {
- let project_config = ctx.repo.load_project_config()?;
- let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());
- let (user_config, proj_config) =
- lookup_hook_configs(&user_hooks, project_config.as_ref(), hook_type);
-
- let commands = prepare_hook_commands(
- ctx,
- user_config,
- proj_config,
- hook_type,
- extra_vars,
- name_filter,
- display_path,
- )?;
-
- spawn_background_hooks(ctx, commands)
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/commands/worktree/hooks.rs b/src/commands/worktree/hooks.rs
index f824a8716..aed44015e 100644
--- a/src/commands/worktree/hooks.rs
+++ b/src/commands/worktree/hooks.rs
@@ -9,7 +9,7 @@ use worktrunk::path::to_posix_path;
use crate::commands::command_executor::CommandContext;
use crate::commands::hooks::{
- HookFailureStrategy, execute_hook, prepare_hook_commands, spawn_background_hooks,
+ HookFailureStrategy, SourcedCommand, execute_hook, prepare_hook_commands,
};
impl<'a> CommandContext<'a> {
@@ -31,23 +31,25 @@ impl<'a> CommandContext<'a> {
)
}
- /// Spawn post-remove commands in parallel as background processes (non-blocking)
+ /// Prepare post-remove commands for background spawning.
///
- /// Runs after worktree removal. Commands execute from the invoking worktree (where
- /// the user ends up after removal), but template variables reflect the removed
- /// worktree so hooks can reference paths and names correctly.
+ /// Returns prepared commands without spawning them, so the caller can batch
+ /// them with other hook types (e.g., post-switch) into a single output line.
+ ///
+ /// Template variables reflect the removed worktree (not where commands run from),
+ /// so hooks can reference the removed path and branch correctly.
///
/// `removed_branch`: The branch that was removed (for `{{ branch }}`).
/// `removed_worktree_path`: The removed worktree's path (for `{{ worktree_path }}`, etc.).
/// `removed_commit`: The commit SHA of the removed worktree's HEAD (for `{{ commit }}`).
/// `display_path`: When `Some`, shows the path in hook announcements.
- pub fn spawn_post_remove_commands(
+ pub fn prepare_post_remove_commands(
&self,
removed_branch: &str,
removed_worktree_path: &Path,
removed_commit: Option<&str>,
display_path: Option<&Path>,
- ) -> anyhow::Result<()> {
+ ) -> anyhow::Result<Vec<SourcedCommand>> {
let project_config = self.repo.load_project_config()?;
// Template variables should reflect the removed worktree, not where we run from.
@@ -77,7 +79,7 @@ impl<'a> CommandContext<'a> {
];
let user_hooks = self.config.hooks(self.project_id().as_deref());
- let commands = prepare_hook_commands(
+ prepare_hook_commands(
self,
user_hooks.post_remove.as_ref(),
project_config
@@ -87,8 +89,6 @@ impl<'a> CommandContext<'a> {
&extra_vars,
None,
display_path,
- )?;
-
- spawn_background_hooks(self, commands)
+ )
}
}
diff --git a/src/output/global.rs b/src/output/global.rs
index 1f00d70ed..b3adbc844 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -305,9 +305,6 @@ pub fn pre_hook_display_path(hooks_run_at: &std::path::Path) -> Option<&std::pat
/// // Prepare and spawn hooks with display path:
/// let hooks = prepare_background_hooks(&ctx, HookType::PostStart, &extra_vars, post_hook_display_path(&destination))?;
/// spawn_background_hooks(&ctx, hooks)?;
-///
-/// // After remove when switching to main:
-/// spawn_hook_background(&ctx, HookType::PostSwitch, &[], None, post_hook_display_path(main_path))?;
/// ```
pub fn post_hook_display_path(destination: &std::path::Path) -> Option<&std::path::Path> {
if is_shell_integration_active() {
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index d7721f8d6..fe2c61110 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -12,7 +12,9 @@ use crate::commands::branch_deletion::{
BranchDeletionOutcome, BranchDeletionResult, delete_branch_if_safe,
};
use crate::commands::command_executor::CommandContext;
-use crate::commands::hooks::{HookFailureStrategy, execute_hook, spawn_hook_background};
+use crate::commands::hooks::{
+ HookFailureStrategy, execute_hook, prepare_background_hooks, spawn_background_hooks,
+};
use crate::commands::process::{HookLog, InternalOp, build_remove_command, spawn_detached};
use crate::commands::worktree::{BranchDeletionMode, RemoveResult, SwitchBranchInfo, SwitchResult};
use worktrunk::config::UserConfig;
@@ -635,19 +637,22 @@ fn handle_branch_only_output(
Ok(())
}
-/// Spawn post-remove hooks after worktree removal.
+/// Spawn post-remove and post-switch hooks as a single batch after worktree removal.
+///
+/// Combines both hook types into one output line for consistency with how
+/// post-switch and post-start are combined during worktree creation.
///
-/// Runs after the worktree is removed. Template variables reflect the removed
-/// worktree (branch, worktree_path, worktree_name, commit), but commands execute from
-/// `run_from_path` since the removed worktree no longer exists.
+/// 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).
-fn spawn_post_remove_hooks(
- run_from_path: &std::path::Path,
+fn spawn_hooks_after_remove(
+ main_path: &std::path::Path,
removed_worktree_path: &std::path::Path,
removed_branch: &str,
removed_commit: Option<&str>,
verify: bool,
+ changed_directory: bool,
) -> anyhow::Result<()> {
if !verify {
return Ok(());
@@ -655,59 +660,36 @@ fn spawn_post_remove_hooks(
let Ok(config) = UserConfig::load() else {
return Ok(());
};
- // Use run_from_path for discovery since the original worktree is removed
- let repo = Repository::at(run_from_path)?;
- // Context uses run_from_path for execution, but we pass removed worktree
- // info as extra_vars so template variables reflect the removed worktree
- let ctx = CommandContext::new(
- &repo,
- &config,
- Some(removed_branch),
- run_from_path,
- false, // yes=false for CommandContext
- );
- ctx.spawn_post_remove_commands(
+ let repo = Repository::at(main_path)?;
+ let display_path = super::post_hook_display_path(main_path);
+
+ // 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.
+ // Template variables differ per hook type (prepared separately below).
+ let remove_ctx = CommandContext::new(&repo, &config, Some(removed_branch), main_path, false);
+ let mut hooks = remove_ctx.prepare_post_remove_commands(
removed_branch,
removed_worktree_path,
removed_commit,
- super::post_hook_display_path(run_from_path),
- )
-}
+ display_path,
+ )?;
-/// Spawn post-switch hooks in the destination worktree after a directory change.
-///
-/// Called when removing a worktree causes a cd to the main worktree.
-/// Only runs if `verify` is true (hooks approved) and `changed_directory` is true.
-fn spawn_post_switch_after_remove(
- main_path: &std::path::Path,
- verify: bool,
- changed_directory: bool,
-) -> anyhow::Result<()> {
- if !verify || !changed_directory {
- return Ok(());
+ // Post-switch: only when the user actually changed directory.
+ // Uses its own context for template variable preparation (dest branch),
+ // but spawned under remove_ctx (removed branch) for log naming.
+ if changed_directory {
+ let dest_branch = repo.worktree_at(main_path).branch()?;
+ let switch_ctx =
+ CommandContext::new(&repo, &config, dest_branch.as_deref(), main_path, false);
+ hooks.extend(prepare_background_hooks(
+ &switch_ctx,
+ worktrunk::HookType::PostSwitch,
+ &[],
+ display_path,
+ )?);
}
- let Ok(config) = UserConfig::load() else {
- return Ok(());
- };
- // Use main_path for discovery since we're called after the original worktree
- // is removed (cwd may no longer exist).
- let repo = Repository::at(main_path)?;
- let dest_branch = repo.worktree_at(main_path).branch()?;
- let ctx = CommandContext::new(
- &repo,
- &config,
- dest_branch.as_deref(),
- main_path,
- false, // yes=false for CommandContext
- );
- // No base context for remove-triggered switch (we're returning to main, not creating)
- spawn_hook_background(
- &ctx,
- worktrunk::HookType::PostSwitch,
- &[],
- None,
- super::post_hook_display_path(main_path),
- )
+
+ spawn_background_hooks(&remove_ctx, hooks)
}
// ============================================================================
@@ -1000,8 +982,14 @@ fn handle_removed_worktree_output(
);
}
// Post-remove hooks for detached HEAD use "HEAD" as the branch identifier
- spawn_post_remove_hooks(main_path, worktree_path, "HEAD", removed_commit, verify)?;
- spawn_post_switch_after_remove(main_path, verify, changed_directory)?;
+ spawn_hooks_after_remove(
+ main_path,
+ worktree_path,
+ "HEAD",
+ removed_commit,
+ verify,
+ changed_directory,
+ )?;
stderr().flush()?;
return Ok(());
};
@@ -1041,14 +1029,14 @@ fn handle_removed_worktree_output(
None,
)?;
- spawn_post_remove_hooks(
+ spawn_hooks_after_remove(
main_path,
worktree_path,
branch_name,
removed_commit,
verify,
+ changed_directory,
)?;
- spawn_post_switch_after_remove(main_path, verify, changed_directory)?;
stderr().flush()?;
Ok(())
} else {
@@ -1093,14 +1081,14 @@ fn handle_removed_worktree_output(
display_info.print_hints(branch_name, deletion_mode, pre_computed_integration)?;
print_switch_message_if_changed(changed_directory, main_path)?;
- spawn_post_remove_hooks(
+ spawn_hooks_after_remove(
main_path,
worktree_path,
branch_name,
removed_commit,
verify,
+ changed_directory,
)?;
- spawn_post_switch_after_remove(main_path, verify, changed_directory)?;
stderr().flush()?;
Ok(())
}
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index 0b62d78f0..f2c470bbf 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -778,11 +778,10 @@ cleanup = "echo 'POST_REMOVE_DURING_MERGE' > ../merge_postremove_marker.txt"
);
}
-// Note: The `return Ok(())` path in spawn_post_remove_hooks when UserConfig::load()
-// fails (handlers.rs line 556) is defensive code for an extremely rare race condition
-// where config becomes invalid between command startup and hook execution. This is
-// not easily testable without complex timing manipulation and matches the existing
-// pattern in spawn_post_switch_after_remove (line 584).
+// Note: The `return Ok(())` path in spawn_hooks_after_remove when UserConfig::load()
+// fails is defensive code for an extremely rare race condition where config becomes
+// invalid between command startup and hook execution. This is not easily testable
+// without complex timing manipulation.
#[rstest]
fn test_standalone_hook_post_remove_invalid_template(repo: TestRepo) {