Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: add pre_hook_display_path and post_hook_display_path helpers (#422)
Maximilian Roos0acbd80537c0
diff --git a/.claude/rules/cli-output-formatting.md b/.claude/rules/cli-output-formatting.mdindex a9f19408c..bcd2b26fe 100644--- a/.claude/rules/cli-output-formatting.md+++ b/.claude/rules/cli-output-formatting.md@@ -65,46 +65,33 @@ in their native styling (see "Symbol styling" below).**Show path when hooks run in a different directory:** When hooks run in aworktree other than the user's current (or eventual) location, show the path.-Use `output::compute_hooks_display_path(hooks_run_at, user_location)` which-returns `Some(hooks_run_at)` when different from `user_location`, or `None`-when they match.+Use the appropriate helper function:-There are two cases for determining `user_location`:+1. **Pre-hooks and manual `wt hook`** — User is at cwd, no cd happens.+ Use `output::pre_hook_display_path(hooks_run_at)`.+ Examples: pre-commit, pre-merge, pre-remove, manual `wt hook post-merge`.-1. **Pre-hooks** — User is at cwd when hooks run. Use cwd as user_location.- Example: `wt step commit` runs pre-commit hooks in the current worktree.--2. **Post-hooks** — User will be at destination if shell integration is active.- Check `is_shell_integration_active()` to determine user_location.- Examples: post-switch, post-start, post-create, post-merge hooks.+2. **Post-hooks** — User will cd to destination if shell integration is active.+ Use `output::post_hook_display_path(destination)`.+ Examples: post-create, post-switch, post-start, post-merge (after removal).```rust-// Pre-hooks: user is at cwd when hooks run-let cwd = std::env::current_dir().unwrap_or_else(|_| ctx.worktree_path.to_path_buf());-let display_path = crate::output::compute_hooks_display_path(ctx.worktree_path, &cwd);+// Pre-hooks: user is at cwd, no cd happens+run_hook_with_filter(..., crate::output::pre_hook_display_path(ctx.worktree_path))?;-// Post-hooks: user will be at destination if shell integration active-let user_location = if crate::output::is_shell_integration_active() {- destination_path.to_path_buf()-} else {- std::env::current_dir().unwrap_or_else(|_| destination_path.to_path_buf())-};-let display_path = crate::output::compute_hooks_display_path(&destination_path, &user_location);+// Post-hooks: user will cd to destination if shell integration active+ctx.spawn_post_start_commands(crate::output::post_hook_display_path(&destination))?;-// Simpler post-hook case when destination == worktree_path-let display_path = if crate::output::is_shell_integration_active() {- None // Shell will cd there+// Complex case: cd only happens under certain conditions+let display_path = if will_cd_to_destination {+ crate::output::post_hook_display_path(&destination_path)} else {- Some(destination_path.as_path())+ crate::output::pre_hook_display_path(&destination_path)};```-Omit the path when the user is (or will be) in the worktree where hooks run:--- **User is already there and will stay**: Pre-merge hooks, pre-commit hooks- when cwd matches worktree_path-- **User will cd there via shell integration**: Post-switch, post-start, and- post-merge hooks when shell integration is active+These helpers encapsulate the shell integration check internally, so callers+don't need to check `is_shell_integration_active()` directly**Avoid pronouns with cross-message referents:** Hints appear as separatemessages from errors. Don't use pronouns like "it" that refer to somethingdiff --git a/src/commands/commit.rs b/src/commands/commit.rsindex d0a219ae8..85656a491 100644--- a/src/commands/commit.rs+++ b/src/commands/commit.rs@@ -167,9 +167,6 @@ impl CommitOptions<'_> {.collect();// Run pre-commit hooks (user first, then project)- // Pre-hook: user is at cwd when hooks run- let cwd =- std::env::current_dir().unwrap_or_else(|_| self.ctx.worktree_path.to_path_buf());super::hooks::run_hook_with_filter(self.ctx,self.ctx.config.hooks.pre_commit.as_ref(),@@ -180,7 +177,7 @@ impl CommitOptions<'_> {&extra_vars,HookFailureStrategy::FailFast,None,- crate::output::compute_hooks_display_path(self.ctx.worktree_path, &cwd),+ crate::output::pre_hook_display_path(self.ctx.worktree_path),).map_err(worktrunk::git::add_hook_skip_hint)?;}diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 295a8d4a9..2267a0167 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -88,8 +88,7 @@ pub fn run_hook(hook_type: HookType, yes: bool, name_filter: Option<&str>) -> an.as_ref().and_then(|c| c.hooks.post_create.as_ref());require_hooks(user_config, project_config, hook_type)?;- // Manual wt hook: user is always at cwd (no cd happens)- let cwd = std::env::current_dir().unwrap_or_else(|_| ctx.worktree_path.to_path_buf());+ // Manual wt hook: user stays at cwd (no cd happens)run_hook_with_filter(&ctx,user_config,@@ -98,7 +97,7 @@ pub fn run_hook(hook_type: HookType, yes: bool, name_filter: Option<&str>) -> an&[],HookFailureStrategy::FailFast,name_filter,- crate::output::compute_hooks_display_path(ctx.worktree_path, &cwd),+ crate::output::pre_hook_display_path(ctx.worktree_path),)}HookType::PostStart => {@@ -152,8 +151,7 @@ pub fn run_hook(hook_type: HookType, yes: bool, name_filter: Option<&str>) -> an.into_iter().map(|t| ("target", t)).collect();- // Manual wt hook: user is always at cwd (no cd happens)- let cwd = std::env::current_dir().unwrap_or_else(|_| ctx.worktree_path.to_path_buf());+ // Manual wt hook: user stays at cwd (no cd happens)run_hook_with_filter(&ctx,user_config,@@ -162,7 +160,7 @@ pub fn run_hook(hook_type: HookType, yes: bool, name_filter: Option<&str>) -> an&extra_vars,HookFailureStrategy::FailFast,name_filter,- crate::output::compute_hooks_display_path(ctx.worktree_path, &cwd),+ crate::output::pre_hook_display_path(ctx.worktree_path),)}HookType::PreMerge => {@@ -173,23 +171,20 @@ pub fn run_hook(hook_type: HookType, yes: bool, name_filter: Option<&str>) -> anrun_pre_merge_commands(&project_cfg, &ctx, ctx.branch_or_head(), name_filter)}HookType::PostMerge => {- // Use current branch as target (matches approval prompt for wt hook)- // Manual wt hook: user is always at cwd (no cd happens)- let cwd = std::env::current_dir().unwrap_or_else(|_| ctx.worktree_path.to_path_buf());+ // Manual wt hook: user stays at cwd (no cd happens)execute_post_merge_commands(&ctx,ctx.branch_or_head(),name_filter,- crate::output::compute_hooks_display_path(ctx.worktree_path, &cwd),+ crate::output::pre_hook_display_path(ctx.worktree_path),)}HookType::PreRemove => {- // Manual wt hook: user is always at cwd (no cd happens)- let cwd = std::env::current_dir().unwrap_or_else(|_| ctx.worktree_path.to_path_buf());+ // Manual wt hook: user stays at cwd (no cd happens)execute_pre_remove_commands(&ctx,name_filter,- crate::output::compute_hooks_display_path(ctx.worktree_path, &cwd),+ crate::output::pre_hook_display_path(ctx.worktree_path),)}}diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 82c74d053..73a4d5d43 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -254,20 +254,13 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {yes,);// Show path when user's shell won't be in the destination directory where hooks run.- let display_path = if in_main || on_target {- // User is already in the destination directory- None- } else if !remove_effective {- // Worktree preserved — user's shell stays in feature worktree- Some(destination_path.as_path())+ let display_path = if remove_effective && !in_main && !on_target {+ // Worktree removed, user will cd to destination+ crate::output::post_hook_display_path(&destination_path)} else {- // Worktree removed — show path only if shell integration won't cd there- // Post-hook: user will be at destination if shell integration active- if crate::output::is_shell_integration_active() {- None // Shell will cd there- } else {- Some(destination_path.as_path())- }+ // No cd happens — user stays at cwd (either already at destination,+ // or worktree preserved so they stay in feature)+ crate::output::pre_hook_display_path(&destination_path)};execute_post_merge_commands(&ctx, &target_branch, None, display_path)?;}@@ -285,8 +278,6 @@ pub fn run_pre_merge_commands(target_branch: &str,name_filter: Option<&str>,) -> anyhow::Result<()> {- // Pre-hook: user is at cwd when hooks run- let cwd = std::env::current_dir().unwrap_or_else(|_| ctx.worktree_path.to_path_buf());run_hook_with_filter(ctx,ctx.config.hooks.pre_merge.as_ref(),@@ -295,7 +286,7 @@ pub fn run_pre_merge_commands(&[("target", target_branch)],HookFailureStrategy::FailFast,name_filter,- crate::output::compute_hooks_display_path(ctx.worktree_path, &cwd),+ crate::output::pre_hook_display_path(ctx.worktree_path),).map_err(worktrunk::git::add_hook_skip_hint)}diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 6728ac2b4..723e7033b 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -134,9 +134,7 @@ pub fn handle_squash(}// Run pre-commit hooks (user first, then project)- // Pre-hook: user is at cwd when hooks runif !skip_pre_commit {- let cwd = std::env::current_dir().unwrap_or_else(|_| ctx.worktree_path.to_path_buf());let extra_vars = [("target", target_branch.as_str())];run_hook_with_filter(&ctx,@@ -148,7 +146,7 @@ pub fn handle_squash(&extra_vars,HookFailureStrategy::FailFast,None,- crate::output::compute_hooks_display_path(ctx.worktree_path, &cwd),+ crate::output::pre_hook_display_path(ctx.worktree_path),).map_err(worktrunk::git::add_hook_skip_hint)?;}diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 7ccc843ae..fb57fe9ae 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -763,12 +763,6 @@ impl<'a> CommandContext<'a> {/// won't cd to the new worktree, so they need to know where hooks ran).pub fn execute_post_create_commands(&self) -> anyhow::Result<()> {let project_config = self.repo.load_project_config()?;- // Post-hook: user will be at worktree_path if shell integration active- let user_location = if crate::output::is_shell_integration_active() {- self.worktree_path.to_path_buf()- } else {- std::env::current_dir().unwrap_or_else(|_| self.worktree_path.to_path_buf())- };super::hooks::run_hook_with_filter(self,self.config.hooks.post_create.as_ref(),@@ -779,7 +773,7 @@ impl<'a> CommandContext<'a> {&[],HookFailureStrategy::Warn,None,- crate::output::compute_hooks_display_path(self.worktree_path, &user_location),+ crate::output::post_hook_display_path(self.worktree_path),)}diff --git a/src/output/global.rs b/src/output/global.rsindex ffa8f8c9c..c803ceee7 100644--- a/src/output/global.rs+++ b/src/output/global.rs@@ -288,16 +288,11 @@ pub fn is_shell_integration_active() -> bool {/// * `hooks_run_at` - The directory where hooks will execute/// * `user_location` - Where the user's shell is (or will be) when they see the output///-/// # Determining `user_location`+/// # Higher-level helpers///-/// For **pre-hooks** (pre-commit, pre-merge, pre-remove): pass `cwd` - the user-/// sees hook output while at their current location.-///-/// For **post-hooks** (post-create, post-merge, post-switch, post-start): pass-/// where the user **will be** after the command. If shell integration is active-/// and a cd directive was emitted, that's the target path. Otherwise it's `cwd`.-///-/// For **manual `wt hook`**: always pass `cwd` - no cd happens.+/// For most cases, use the convenience functions instead of computing `user_location` manually:+/// - [`pre_hook_display_path`] - for pre-hooks and manual `wt hook` invocations+/// - [`post_hook_display_path`] - for post-hooks (handles shell integration internally)pub fn compute_hooks_display_path<'a>(hooks_run_at: &'a std::path::Path,user_location: &std::path::Path,@@ -309,6 +304,53 @@ pub fn compute_hooks_display_path<'a>(}}+/// Display path for pre-hooks and manual `wt hook` invocations.+///+/// Pre-hooks run while the user is at cwd, and no cd will happen after.+/// Manual `wt hook` commands also run at cwd with no cd.+///+/// Shows the path if hooks run somewhere other than cwd.+///+/// # Examples+///+/// ```ignore+/// // In pre-commit, pre-merge, pre-remove hooks:+/// run_hook_with_filter(..., pre_hook_display_path(ctx.worktree_path))?;+///+/// // In manual wt hook commands (even for post-* hook types):+/// run_hook_with_filter(..., pre_hook_display_path(ctx.worktree_path))?;+/// ```+pub fn pre_hook_display_path(hooks_run_at: &std::path::Path) -> Option<&std::path::Path> {+ let cwd = match std::env::current_dir() {+ Ok(cwd) => cwd,+ Err(_) => return None, // Can't determine cwd, don't show path+ };+ compute_hooks_display_path(hooks_run_at, &cwd)+}++/// Display path for post-hooks.+///+/// Post-hooks run after the operation completes. If shell integration is active,+/// the user will be cd'd to the destination, so no path needs to be shown.+/// Without shell integration, shows the path if user is elsewhere.+///+/// # Examples+///+/// ```ignore+/// // In post-create, post-switch, post-merge hooks:+/// ctx.spawn_post_start_commands(post_hook_display_path(&destination))?;+///+/// // After remove when switching to main:+/// ctx.spawn_post_switch_commands(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() {+ None // Shell will cd user to destination+ } else {+ pre_hook_display_path(destination)+ }+}+#[cfg(test)]mod tests {use super::*;@@ -329,6 +371,53 @@ mod tests {assert_eq!(result, Some(hooks_run_at.as_path()));}+ #[test]+ fn test_pre_hook_display_path_at_cwd() {+ // When hooks run at cwd, no path annotation needed+ let cwd = std::env::current_dir().unwrap();+ let result = pre_hook_display_path(&cwd);+ assert!(result.is_none(), "Should return None when hooks run at cwd");+ }++ #[test]+ fn test_pre_hook_display_path_elsewhere() {+ // When hooks run elsewhere, show the path+ let elsewhere = PathBuf::from("/some/other/path");+ let result = pre_hook_display_path(&elsewhere);+ assert_eq!(+ result,+ Some(elsewhere.as_path()),+ "Should return path when hooks run elsewhere"+ );+ }++ #[test]+ fn test_post_hook_display_path_no_shell_integration() {+ // Without shell integration, post_hook_display_path behaves like pre_hook_display_path+ // (This test runs without WORKTRUNK_DIRECTIVE_FILE set)+ let elsewhere = PathBuf::from("/some/destination");+ let result = post_hook_display_path(&elsewhere);+ // If cwd != elsewhere, should return Some+ // If cwd == elsewhere (unlikely), should return None+ let cwd = std::env::current_dir().unwrap();+ if cwd == elsewhere {+ assert!(result.is_none());+ } else {+ assert_eq!(result, Some(elsewhere.as_path()));+ }+ }++ #[test]+ fn test_post_hook_display_path_at_cwd_no_shell_integration() {+ // Without shell integration, if destination == cwd, no path needed+ let cwd = std::env::current_dir().unwrap();+ let result = post_hook_display_path(&cwd);+ assert!(+ result.is_none(),+ "Should return None when destination is cwd (no shell integration)"+ );+ }+#[test]fn test_lazy_init_does_not_panic() {// Verify lazy initialization doesn't panic.diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex c1ed55b45..6b1be9a04 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -519,13 +519,7 @@ fn spawn_post_switch_after_remove(&repo_root,false, // force=false for CommandContext);- // Post-hook: user will be at main_path if shell integration active- let display_path = if super::is_shell_integration_active() {- None // Shell will cd there- } else {- Some(main_path)- };- ctx.spawn_post_switch_commands(display_path)+ ctx.spawn_post_switch_commands(super::post_hook_display_path(main_path))}/// Handle output for RemovedWorktree removaldiff --git a/src/output/mod.rs b/src/output/mod.rsindex fbffa780b..46cb8292b 100644--- a/src/output/mod.rs+++ b/src/output/mod.rs@@ -34,8 +34,8 @@ pub mod shell_integration;// Re-export the public APIpub use global::{- blank, change_directory, compute_hooks_display_path, execute, flush,- is_shell_integration_active, print, stdout, terminate_output,+ blank, change_directory, execute, flush, is_shell_integration_active, post_hook_display_path,+ pre_hook_display_path, print, stdout, terminate_output,};// Re-export output handlerspub use handlers::{