Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: simplify command structure and remove dead code (#892)
Maximilian Roosa567d5dffa6c
diff --git a/src/commands/context.rs b/src/commands/context.rsindex e4cf3e666..6faa8821a 100644--- a/src/commands/context.rs+++ b/src/commands/context.rs@@ -28,11 +28,10 @@ impl CommandEnv {////// `action` describes what command is running (e.g., "merge", "squash")./// Used in error messages when the environment can't be loaded.- pub fn for_action(action: &str) -> anyhow::Result<Self> {+ pub fn for_action(action: &str, config: UserConfig) -> anyhow::Result<Self> {let repo = Repository::current()?;let worktree_path = std::env::current_dir().context("Failed to get current directory")?;let branch = repo.require_current_branch(action)?;- let config = UserConfig::load().context("Failed to load config")?;Ok(Self {repo,diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rsnew file mode 100644index 000000000..4f605175f--- /dev/null+++ b/src/commands/handle_switch.rs@@ -0,0 +1,185 @@+//! Switch command handler.++use std::collections::HashMap;++use anyhow::Context;+use worktrunk::HookType;+use worktrunk::config::{UserConfig, expand_template};+use worktrunk::git::Repository;+use worktrunk::styling::{eprintln, info_message};++use super::command_approval::approve_hooks;+use super::command_executor::{CommandContext, build_hook_context};+use super::worktree::{SwitchResult, execute_switch, plan_switch};+use crate::output::{+ execute_user_command, handle_switch_output, is_shell_integration_active,+ prompt_shell_integration,+};++/// Options for the switch command+pub struct SwitchOptions<'a> {+ pub branch: &'a str,+ pub create: bool,+ pub base: Option<&'a str>,+ pub execute: Option<&'a str>,+ pub execute_args: &'a [String],+ pub yes: bool,+ pub clobber: bool,+ pub verify: bool,+}++/// Handle the switch command.+pub fn handle_switch(+ opts: SwitchOptions<'_>,+ config: &mut UserConfig,+ binary_name: &str,+) -> anyhow::Result<()> {+ let SwitchOptions {+ branch,+ create,+ base,+ execute,+ execute_args,+ yes,+ clobber,+ verify,+ } = opts;++ let repo = Repository::current().context("Failed to switch worktree")?;++ // Validate FIRST (before approval) - fails fast if branch doesn't exist, etc.+ let plan = plan_switch(&repo, branch, create, base, clobber, config)?;++ // "Approve at the Gate": collect and approve hooks upfront+ // This ensures approval happens once at the command entry point+ // If user declines, skip hooks but continue with worktree operation+ let approved = if verify {+ let ctx = CommandContext::new(+ &repo,+ config,+ Some(plan.branch()),+ plan.worktree_path(),+ yes,+ );+ // Approve different hooks based on whether we're creating or switching+ if plan.is_create() {+ approve_hooks(+ &ctx,+ &[+ HookType::PostCreate,+ HookType::PostStart,+ HookType::PostSwitch,+ ],+ )?+ } else {+ // When switching to existing, only post-switch needs approval+ approve_hooks(&ctx, &[HookType::PostSwitch])?+ }+ } else {+ true // --no-verify: skip all hooks+ };++ // Skip hooks if --no-verify or user declined approval+ let skip_hooks = !verify || !approved;++ // Show message if user declined approval+ if !approved {+ eprintln!(+ "{}",+ info_message(if plan.is_create() {+ "Commands declined, continuing worktree creation"+ } else {+ "Commands declined"+ })+ );+ }++ // Execute the validated plan+ let (result, branch_info) = execute_switch(&repo, plan, config, yes, skip_hooks)?;++ // Show success message (temporal locality: immediately after worktree operation)+ // Returns path to display in hooks when user's shell won't be in the worktree+ // Also shows worktree-path hint on first --create (before shell integration warning)+ let hooks_display_path = handle_switch_output(&result, &branch_info)?;++ // Offer shell integration if not already installed/active+ // (only shows prompt/hint when shell integration isn't working)+ // With --execute: show hints only (don't interrupt with prompt)+ // Best-effort: don't fail switch if offer fails+ if !is_shell_integration_active() {+ let skip_prompt = execute.is_some();+ let _ = prompt_shell_integration(config, binary_name, skip_prompt);+ }++ // Build extra vars for base branch context (used by both hooks and --execute)+ // "base" is the branch we branched from when creating a new worktree.+ // For existing worktrees, there's no base concept.+ let (base_branch, base_worktree_path): (Option<&str>, Option<&str>) = match &result {+ SwitchResult::Created {+ base_branch,+ base_worktree_path,+ ..+ } => (base_branch.as_deref(), base_worktree_path.as_deref()),+ SwitchResult::Existing { .. } | SwitchResult::AlreadyAt(_) => (None, None),+ };+ let extra_vars: Vec<(&str, &str)> = [+ base_branch.map(|b| ("base", b)),+ base_worktree_path.map(|p| ("base_worktree_path", p)),+ ]+ .into_iter()+ .flatten()+ .collect();++ // Spawn background hooks after success message+ // - post-switch: runs on ALL switches (shows "@ path" when shell won't be there)+ // - post-start: runs only when creating a NEW worktree+ if !skip_hooks {+ let ctx = CommandContext::new(&repo, config, Some(&branch_info.branch), result.path(), yes);++ // Post-switch runs first (immediate "I'm here" signal)+ ctx.spawn_post_switch_commands(&extra_vars, hooks_display_path.as_deref())?;++ // Post-start runs only on creation (setup tasks)+ if matches!(&result, SwitchResult::Created { .. }) {+ ctx.spawn_post_start_commands(&extra_vars, hooks_display_path.as_deref())?;+ }+ }++ // Execute user command after post-start hooks have been spawned+ // Note: execute_args requires execute via clap's `requires` attribute+ if let Some(cmd) = execute {+ // Build template context for expansion (includes base vars when creating)+ let ctx = CommandContext::new(&repo, config, Some(&branch_info.branch), result.path(), yes);+ let template_vars = build_hook_context(&ctx, &extra_vars);+ let vars: HashMap<&str, &str> = template_vars+ .iter()+ .map(|(k, v)| (k.as_str(), v.as_str()))+ .collect();++ // Expand template variables in command (shell_escape: true for safety)+ let expanded_cmd = expand_template(cmd, &vars, true, &repo, "--execute command")+ .map_err(|e| anyhow::anyhow!("Failed to expand --execute template: {}", e))?;++ // Append any trailing args (after --) to the execute command+ // Each arg is also expanded, then shell-escaped+ let full_cmd = if execute_args.is_empty() {+ expanded_cmd+ } else {+ let expanded_args: Result<Vec<_>, _> = execute_args+ .iter()+ .map(|arg| {+ expand_template(arg, &vars, false, &repo, "--execute argument")+ .map_err(|e| anyhow::anyhow!("Failed to expand argument template: {}", e))+ })+ .collect();+ let escaped_args: Vec<_> = expanded_args?+ .iter()+ .map(|arg| shlex::try_quote(arg).unwrap_or(arg.into()).into_owned())+ .collect();+ format!("{} {}", expanded_cmd, escaped_args.join(" "))+ };+ execute_user_command(&full_cmd, hooks_display_path.as_deref())?;+ }++ Ok(())+}diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 43125f6a4..0eaa189d0 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -26,13 +26,11 @@ use super::command_executor::build_hook_context;use super::command_executor::CommandContext;use super::context::CommandEnv;+use super::hooks::execute_hook;use super::hooks::{HookFailureStrategy, check_name_filter_matched, prepare_hook_commands, run_hook_with_filter,spawn_hook_commands_background,};-use super::merge::{- execute_post_merge_commands, execute_pre_remove_commands, run_pre_merge_commands,-};use super::project_config::collect_commands_for_hooks;/// Handle `wt hook` command@@ -224,35 +222,40 @@ pub fn run_hook()}HookType::PreMerge => {- // pre-merge, post-merge, pre-remove use functions from merge.rs- // which already handle user hooks (approval already happened at gate)// Use current branch as target (matches approval prompt for wt hook)- let project_cfg = project_config.unwrap_or_default();- run_pre_merge_commands(- &project_cfg,+ let mut vars = vec![("target", ctx.branch_or_head())];+ vars.extend(custom_vars_refs.iter().cloned());+ execute_hook(&ctx,- ctx.branch_or_head(),+ HookType::PreMerge,+ &vars,+ HookFailureStrategy::FailFast,name_filter,- &custom_vars_refs,+ crate::output::pre_hook_display_path(ctx.worktree_path),)}HookType::PostMerge => {// Manual wt hook: user stays at cwd (no cd happens)- execute_post_merge_commands(+ let mut vars = vec![("target", ctx.branch_or_head())];+ vars.extend(custom_vars_refs.iter().cloned());+ execute_hook(&ctx,- ctx.branch_or_head(),+ HookType::PostMerge,+ &vars,+ HookFailureStrategy::Warn,name_filter,crate::output::pre_hook_display_path(ctx.worktree_path),- &custom_vars_refs,)}HookType::PreRemove => {// Manual wt hook: user stays at cwd (no cd happens)- execute_pre_remove_commands(+ execute_hook(&ctx,+ HookType::PreRemove,+ &custom_vars_refs,+ HookFailureStrategy::FailFast,name_filter,crate::output::pre_hook_display_path(ctx.worktree_path),- &custom_vars_refs,)}HookType::PostRemove => {diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex a08df31f7..206a1af45 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -357,6 +357,84 @@ pub fn run_hook_with_filter(Ok(())}+/// Look up user and project configs for a given hook type.+fn lookup_hook_configs<'a>(+ user_hooks: &'a worktrunk::config::HooksConfig,+ project_config: Option<&'a worktrunk::config::ProjectConfig>,+ hook_type: HookType,+) -> (Option<&'a CommandConfig>, Option<&'a CommandConfig>) {+ (+ user_hooks.get(hook_type),+ project_config.and_then(|c| c.hooks.get(hook_type)),+ )+}++/// Run a hook type 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. Calls `run_hook_with_filter` with the appropriate hook configs+/// 4. Adds the hook skip hint to errors+///+/// Use this instead of manually looking up configs and calling `run_hook_with_filter`.+pub fn execute_hook(+ ctx: &CommandContext,+ hook_type: HookType,+ extra_vars: &[(&str, &str)],+ failure_strategy: HookFailureStrategy,+ 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);++ run_hook_with_filter(+ ctx,+ user_config,+ proj_config,+ hook_type,+ extra_vars,+ failure_strategy,+ name_filter,+ display_path,+ )+ .map_err(worktrunk::git::add_hook_skip_hint)+}++/// 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+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_hook_commands_background(ctx, commands, hook_type)+}+#[cfg(test)]mod tests {use super::*;diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex af16ebda6..889977fb5 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -1,8 +1,6 @@-use std::path::Path;-use anyhow::Context;use worktrunk::HookType;-use worktrunk::config::{ProjectConfig, UserConfig};+use worktrunk::config::UserConfig;use worktrunk::git::Repository;use worktrunk::styling::{eprintln, info_message};@@ -10,7 +8,7 @@ use super::command_approval::approve_command_batch;use super::command_executor::CommandContext;use super::commit::CommitOptions;use super::context::CommandEnv;-use super::hooks::{HookFailureStrategy, run_hook_with_filter};+use super::hooks::{HookFailureStrategy, execute_hook};use super::project_config::{HookCommand, collect_commands_for_hooks};use super::repository_ext::RepositoryCliExt;use super::worktree::{@@ -51,7 +49,7 @@ fn collect_merge_commands(let mut all_commands = Vec::new();let project_config = match repo.load_project_config()? {Some(cfg) => cfg,- None => return Ok((all_commands, repo.project_identifier()?.to_string())),+ None => return Ok((all_commands, repo.project_identifier()?)),};let mut hooks = Vec::new();@@ -74,7 +72,7 @@ fn collect_merge_commands(all_commands.extend(collect_commands_for_hooks(&project_config, &hooks));- let project_id = repo.project_identifier()?.to_string();+ let project_id = repo.project_identifier()?;Ok((all_commands, project_id))}@@ -90,13 +88,14 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {stage,} = opts;- // One-time LLM setup prompt (errors logged internally; don't block merge)+ // Load config once, run LLM setup prompt if committing, then reuse config+ let mut config = UserConfig::load().context("Failed to load config")?;if commit_opt.unwrap_or(true) {- let mut config = UserConfig::load().context("Failed to load config")?;+ // One-time LLM setup prompt (errors logged internally; don't block merge)let _ = crate::output::prompt_commit_generation(&mut config);}- let env = CommandEnv::for_action("merge")?;+ let env = CommandEnv::for_action("merge", config)?;let repo = &env.repo;let config = &env.config;// Merge requires being on a branch (can't merge from detached HEAD)@@ -134,7 +133,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {if !commit && current_wt.is_dirty()? {return Err(worktrunk::git::GitError::UncommittedChanges {action: Some("merge with --no-commit".into()),- branch: Some(current_branch.clone()),+ branch: Some(current_branch),force_hint: false,}.into());@@ -214,10 +213,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {} else {// --no-rebase: verify already rebased, fail if notif !repo.is_rebased_onto(&target_branch)? {- return Err(worktrunk::git::GitError::NotRebased {- target_branch: target_branch.clone(),- }- .into());+ return Err(worktrunk::git::GitError::NotRebased { target_branch }.into());}false // Already rebased, no rebase occurred};@@ -226,8 +222,14 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {// Do this after commit/squash/rebase to validate the final state that will be pushedif verify {let ctx = env.context(yes);- let project_config = repo.load_project_config()?.unwrap_or_default();- run_pre_merge_commands(&project_config, &ctx, &target_branch, None, &[])?;+ execute_hook(+ &ctx,+ HookType::PreMerge,+ &[("target", target_branch.as_str())],+ HookFailureStrategy::FailFast,+ None,+ crate::output::pre_hook_display_path(ctx.worktree_path),+ )?;}// Fast-forward push to target branch with commit/squash/rebase info for consolidated message@@ -254,7 +256,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {current_wt.ensure_clean("remove worktree after merge", Some(¤t_branch), false)?;// STEP 2: Remove worktree via shared remove output handler so final message matches wt remove- let worktree_root = current_wt.root()?.to_path_buf();+ let worktree_root = current_wt.root()?;// After a successful merge, get integration reasonlet (_, integration_reason) = repo.integration_reason(¤t_branch, &target_branch)?;// Compute expected_path for path mismatch detection@@ -306,104 +308,15 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {// 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, &[])?;+ execute_hook(+ &ctx,+ HookType::PostMerge,+ &[("target", target_branch.as_str())],+ HookFailureStrategy::Warn,+ None,+ display_path,+ )?;}Ok(())}--/// Run pre-merge commands sequentially (blocking, fail-fast)-///-/// Runs user hooks first, then project hooks.-/// Approval is handled at the gate (command entry point).-pub fn run_pre_merge_commands(- project_config: &ProjectConfig,- ctx: &CommandContext,- target_branch: &str,- name_filter: Option<&str>,- extra_vars: &[(&str, &str)],-) -> anyhow::Result<()> {- // Combine target with any custom vars (custom vars take precedence, added last)- let mut vars = vec![("target", target_branch)];- vars.extend_from_slice(extra_vars);- let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());- run_hook_with_filter(- ctx,- user_hooks.pre_merge.as_ref(),- project_config.hooks.pre_merge.as_ref(),- HookType::PreMerge,- &vars,- HookFailureStrategy::FailFast,- name_filter,- crate::output::pre_hook_display_path(ctx.worktree_path),- )- .map_err(worktrunk::git::add_hook_skip_hint)-}--/// Execute post-merge commands sequentially in the target worktree (blocking)-///-/// Runs user hooks first, then project hooks.-/// Approval is handled at the gate (command entry point).-///-/// `display_path`: Pass `ctx.hooks_display_path()` for automatic detection, or-/// explicit `Some(path)` when hooks run somewhere the user won't be cd'd to.-pub fn execute_post_merge_commands(- ctx: &CommandContext,- target_branch: &str,- name_filter: Option<&str>,- display_path: Option<&Path>,- extra_vars: &[(&str, &str)],-) -> anyhow::Result<()> {- // Load project config from the main worktree path- let project_config = ctx.repo.load_project_config()?;-- // Combine target with any custom vars (custom vars take precedence, added last)- let mut vars = vec![("target", target_branch)];- vars.extend_from_slice(extra_vars);- let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());- run_hook_with_filter(- ctx,- user_hooks.post_merge.as_ref(),- project_config- .as_ref()- .and_then(|c| c.hooks.post_merge.as_ref()),- HookType::PostMerge,- &vars,- HookFailureStrategy::Warn,- name_filter,- display_path,- )- .map_err(worktrunk::git::add_hook_skip_hint)-}--/// Execute pre-remove commands sequentially in the worktree (blocking)-///-/// Runs user hooks first, then project hooks.-/// Runs before a worktree is removed. Non-zero exit aborts the removal.-/// Approval is handled at the gate (command entry point).-///-/// `display_path`: Pass `ctx.hooks_display_path()` for automatic detection, or-/// explicit `Some(path)` when hooks run somewhere the user won't be cd'd to.-pub fn execute_pre_remove_commands(- ctx: &CommandContext,- name_filter: Option<&str>,- display_path: Option<&Path>,- extra_vars: &[(&str, &str)],-) -> anyhow::Result<()> {- let project_config = ctx.repo.load_project_config()?;- let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());-- run_hook_with_filter(- ctx,- user_hooks.pre_remove.as_ref(),- project_config- .as_ref()- .and_then(|c| c.hooks.pre_remove.as_ref()),- HookType::PreRemove,- extra_vars,- HookFailureStrategy::FailFast,- name_filter,- display_path,- )- .map_err(worktrunk::git::add_hook_skip_hint)-}diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 190cdde43..a814e485f 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -6,9 +6,10 @@ pub(crate) mod config;pub(crate) mod configure_shell;pub(crate) mod context;mod for_each;+mod handle_switch;mod hook_commands;mod hook_filter;-mod hooks;+pub(crate) mod hooks;pub(crate) mod init;pub(crate) mod list;pub(crate) mod merge;@@ -31,10 +32,11 @@ pub(crate) use configure_shell::{handle_configure_shell, handle_show_theme, handle_unconfigure_shell,};pub(crate) use for_each::step_for_each;+pub(crate) use handle_switch::{SwitchOptions, handle_switch};pub(crate) use hook_commands::{add_approvals, clear_approvals, handle_hook_show, run_hook};pub(crate) use init::{handle_completions, handle_init};pub(crate) use list::handle_list;-pub(crate) use merge::{MergeOptions, execute_pre_remove_commands, handle_merge};+pub(crate) use merge::{MergeOptions, handle_merge};#[cfg(unix)]pub(crate) use select::handle_select;pub(crate) use step_commands::{@@ -42,8 +44,8 @@ pub(crate) use step_commands::{step_relocate, step_show_squash_prompt,};pub(crate) use worktree::{- OperationMode, execute_switch, handle_remove, handle_remove_current,- is_worktree_at_expected_path, plan_switch, resolve_worktree_arg, worktree_display_name,+ OperationMode, handle_remove, handle_remove_current, is_worktree_at_expected_path,+ resolve_worktree_arg, worktree_display_name,};// Re-export Shell from the canonical locationdiff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex a6f9ca08a..935b7c74c 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -48,11 +48,12 @@ pub fn step_commit(return Ok(());}- // One-time LLM setup prompt (errors logged internally; don't block commit)+ // Load config once, run LLM setup prompt, then reuse configlet mut config = UserConfig::load().context("Failed to load config")?;+ // One-time LLM setup prompt (errors logged internally; don't block commit)let _ = crate::output::prompt_commit_generation(&mut config);- let env = CommandEnv::for_action("commit")?;+ let env = CommandEnv::for_action("commit", config)?;let ctx = env.context(yes);// Determine effective stage mode: CLI > project config > global config > default@@ -103,19 +104,20 @@ pub enum SquashResult {/// Handle shared squash workflow (used by `wt step squash` and `wt merge`)////// # Arguments-/// * `skip_pre_commit` - If true, skip all pre-commit hooks (both user and project)+/// * `no_verify` - If true, skip all pre-commit hooks (from --no-verify flag)/// * `stage` - CLI-provided stage mode. If None, uses the effective config default.pub fn handle_squash(target: Option<&str>,yes: bool,- skip_pre_commit: bool,+ no_verify: bool,stage: Option<StageMode>,) -> anyhow::Result<SquashResult> {- // One-time LLM setup prompt (errors logged internally; don't block commit)+ // Load config once, run LLM setup prompt, then reuse configlet mut config = UserConfig::load().context("Failed to load config")?;+ // One-time LLM setup prompt (errors logged internally; don't block commit)let _ = crate::output::prompt_commit_generation(&mut config);- let env = CommandEnv::for_action("squash")?;+ let env = CommandEnv::for_action("squash", config)?;let repo = &env.repo;// Squash requires being on a branch (can't squash in detached HEAD)let current_branch = env.require_branch("squash")?.to_string();@@ -128,6 +130,38 @@ pub fn handle_squash(.or_else(|| env.commit().and_then(|c| c.stage)).unwrap_or_default();+ // Check if any pre-commit hooks exist (needed for skip message and approval)+ let project_config = repo.load_project_config()?;+ let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());+ let any_hooks_exist = user_hooks.pre_commit.is_some()+ || project_config+ .as_ref()+ .is_some_and(|c| c.hooks.pre_commit.is_some());++ // "Approve at the Gate": approve pre-commit hooks upfront (unless --no-verify)+ // Shadow no_verify: if user declines approval, skip hooks but continue squash+ let no_verify = if !no_verify {+ let approved = approve_hooks(&ctx, &[HookType::PreCommit])?;+ if !approved {+ eprintln!(+ "{}",+ info_message("Commands declined, squashing without hooks")+ );+ true // Skip hooks+ } else {+ false // Run hooks+ }+ } else {+ // Show skip message when --no-verify was passed and hooks exist+ if any_hooks_exist {+ eprintln!(+ "{}",+ info_message("Skipping pre-commit hooks (--no-verify)")+ );+ }+ true // --no-verify was passed+ };+// Get and validate target ref (any commit-ish for merge-base calculation)let integration_target = repo.require_target_ref(target)?;@@ -147,25 +181,8 @@ pub fn handle_squash(}}- // Run pre-commit hooks unless explicitly skipped- let project_config = repo.load_project_config()?;- let has_project_pre_commit = project_config- .as_ref()- .map(|c| c.hooks.pre_commit.is_some())- .unwrap_or(false);- let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());- let has_user_pre_commit = user_hooks.pre_commit.is_some();- let has_any_pre_commit = has_project_pre_commit || has_user_pre_commit;-- if skip_pre_commit && has_any_pre_commit {- eprintln!(- "{}",- info_message("Skipping pre-commit hooks (--no-verify)")- );- }-// Run pre-commit hooks (user first, then project)- if !skip_pre_commit {+ if !no_verify {let extra_vars = [("target", integration_target.as_str())];run_hook_with_filter(&ctx,@@ -413,13 +430,15 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {// If rebase failed, check if it's due to conflictsif let Err(e) = rebase_result {- if let Some(state) = repo.worktree_state()?- && state.starts_with("REBASING")- {+ // Check if it's a rebase conflict+ let is_rebasing = repo+ .worktree_state()?+ .is_some_and(|s| s.starts_with("REBASING"));+ if is_rebasing {// Extract git's stderr output from the errorlet git_output = e.to_string();return Err(worktrunk::git::GitError::RebaseConflict {- target_branch: integration_target.clone(),+ target_branch: integration_target,git_output,}.into());@@ -436,27 +455,21 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {}// Verify rebase completed successfully (safety check for edge cases)- if let Some(state) = repo.worktree_state()? {- let _ = state; // used for diagnostics+ if repo.worktree_state()?.is_some() {return Err(worktrunk::git::GitError::RebaseConflict {- target_branch: integration_target.clone(),+ target_branch: integration_target,git_output: String::new(),}.into());}// Success- if is_fast_forward {- eprintln!(- "{}",- success_message(cformat!("Fast-forwarded to <bold>{integration_target}</>"))- );+ let msg = if is_fast_forward {+ cformat!("Fast-forwarded to <bold>{integration_target}</>")} else {- eprintln!(- "{}",- success_message(cformat!("Rebased onto <bold>{integration_target}</>"))- );- }+ cformat!("Rebased onto <bold>{integration_target}</>")+ };+ eprintln!("{}", success_message(msg));Ok(RebaseResult::Rebased)}@@ -507,7 +520,7 @@ pub fn step_copy_ignored(branch: branch.to_string(),}})?,- None => repo.current_worktree().root()?.to_path_buf(),+ None => repo.current_worktree().root()?,};if source_path == dest_path {@@ -839,13 +852,6 @@ mod tests {assert!(debug.contains("NoNetChanges"));}- #[test]- fn test_squash_result_clone() {- let original = SquashResult::NoCommitsAhead("develop".to_string());- let cloned = original.clone();- assert!(matches!(cloned, SquashResult::NoCommitsAhead(ref s) if s == "develop"));- }-#[test]fn test_rebase_result_variants() {// RebaseResult doesn't derive Debug/Clone by default, just test matchingdiff --git a/src/commands/worktree/hooks.rs b/src/commands/worktree/hooks.rsindex d3710687f..d65cd2760 100644--- a/src/commands/worktree/hooks.rs+++ b/src/commands/worktree/hooks.rs@@ -9,7 +9,8 @@ use worktrunk::path::to_posix_path;use crate::commands::command_executor::CommandContext;use crate::commands::hooks::{- HookFailureStrategy, prepare_hook_commands, spawn_hook_commands_background,+ HookFailureStrategy, execute_hook, prepare_hook_commands, spawn_hook_background,+ spawn_hook_commands_background,};impl<'a> CommandContext<'a> {@@ -21,14 +22,8 @@ impl<'a> CommandContext<'a> {////// `extra_vars`: Additional template variables (e.g., `base`, `base_worktree_path`).pub fn execute_post_create_commands(&self, extra_vars: &[(&str, &str)]) -> anyhow::Result<()> {- let project_config = self.repo.load_project_config()?;- let user_hooks = self.config.hooks(self.project_id().as_deref());- crate::commands::hooks::run_hook_with_filter(+ execute_hook(self,- user_hooks.post_create.as_ref(),- project_config- .as_ref()- .and_then(|c| c.hooks.post_create.as_ref()),HookType::PostCreate,extra_vars,HookFailureStrategy::Warn,@@ -38,61 +33,21 @@ impl<'a> CommandContext<'a> {}/// Spawn post-start commands in parallel as background processes (non-blocking)- ///- /// `extra_vars`: Additional template variables (e.g., `base`, `base_worktree_path`).- /// `display_path`: When `Some`, shows the path in hook announcements. Pass this when- /// the user's shell won't be in the worktree (shell integration not active).pub fn spawn_post_start_commands(&self,extra_vars: &[(&str, &str)],- display_path: Option<&std::path::Path>,+ display_path: Option<&Path>,) -> anyhow::Result<()> {- let project_config = self.repo.load_project_config()?;- let user_hooks = self.config.hooks(self.project_id().as_deref());-- let commands = prepare_hook_commands(- self,- user_hooks.post_start.as_ref(),- project_config- .as_ref()- .and_then(|c| c.hooks.post_start.as_ref()),- HookType::PostStart,- extra_vars,- None,- display_path,- )?;-- spawn_hook_commands_background(self, commands, HookType::PostStart)+ spawn_hook_background(self, HookType::PostStart, extra_vars, None, display_path)}/// Spawn post-switch commands in parallel as background processes (non-blocking)- ///- /// Runs on every switch, including to existing worktrees and newly created ones.- ///- /// `extra_vars`: Additional template variables (e.g., `base`, `base_worktree_path`).- /// `display_path`: When `Some`, shows the path in hook announcements. Pass this when- /// the user's shell won't be in the worktree (shell integration not active).pub fn spawn_post_switch_commands(&self,extra_vars: &[(&str, &str)],- display_path: Option<&std::path::Path>,+ display_path: Option<&Path>,) -> anyhow::Result<()> {- let project_config = self.repo.load_project_config()?;- let user_hooks = self.config.hooks(self.project_id().as_deref());-- let commands = prepare_hook_commands(- self,- user_hooks.post_switch.as_ref(),- project_config- .as_ref()- .and_then(|c| c.hooks.post_switch.as_ref()),- HookType::PostSwitch,- extra_vars,- None,- display_path,- )?;-- spawn_hook_commands_background(self, commands, HookType::PostSwitch)+ spawn_hook_background(self, HookType::PostSwitch, extra_vars, None, display_path)}/// Spawn post-remove commands in parallel as background processes (non-blocking)diff --git a/src/main.rs b/src/main.rsindex b3f84c5ff..1731ff12f 100644--- a/src/main.rs+++ b/src/main.rs@@ -1,4 +1,4 @@-use std::collections::{HashMap, HashSet};+use std::collections::HashSet;use std::io::Write;use anyhow::Context;@@ -6,7 +6,7 @@ use clap::FromArgMatches;use clap::error::ErrorKind as ClapErrorKind;use color_print::{ceprintln, cformat};use std::process;-use worktrunk::config::{UserConfig, expand_template, set_config_path};+use worktrunk::config::{UserConfig, set_config_path};use worktrunk::git::{Repository, ResolvedWorktree, exit_code, set_base_path};use worktrunk::path::format_path_for_display;use worktrunk::shell::extract_filename_from_path;@@ -41,21 +41,20 @@ pub(crate) use invocation::{pub(crate) use crate::cli::OutputFormat;-use commands::command_executor::{CommandContext, build_hook_context};#[cfg(unix)]use commands::handle_select;-use commands::worktree::{SwitchResult, handle_push};+use commands::worktree::handle_push;use commands::{- MergeOptions, OperationMode, RebaseResult, SquashResult, add_approvals, clear_approvals,- execute_switch, handle_completions, handle_config_create, handle_config_show,+ MergeOptions, OperationMode, RebaseResult, SquashResult, SwitchOptions, add_approvals,+ clear_approvals, handle_completions, handle_config_create, handle_config_show,handle_configure_shell, handle_hints_clear, handle_hints_get, handle_hook_show, handle_init,handle_list, handle_logs_get, handle_merge, handle_rebase, handle_remove,handle_remove_current, handle_show_theme, handle_squash, handle_state_clear,- handle_state_clear_all, handle_state_get, handle_state_set, handle_state_show,- handle_unconfigure_shell, plan_switch, resolve_worktree_arg, run_hook, step_commit,- step_copy_ignored, step_for_each, step_relocate,+ handle_state_clear_all, handle_state_get, handle_state_set, handle_state_show, handle_switch,+ handle_unconfigure_shell, resolve_worktree_arg, run_hook, step_commit, step_copy_ignored,+ step_for_each, step_relocate,};-use output::{execute_user_command, handle_remove_output, handle_switch_output};+use output::handle_remove_output;use cli::{ApprovalsCommand, CiStatusAction, Cli, Commands, ConfigCommand, ConfigShellCommand,@@ -519,43 +518,25 @@ fn main() {if show_prompt {commands::step_show_squash_prompt(target.as_deref())} else {- (|| {- // "Approve at the Gate": approve pre-commit hooks upfront (unless --no-verify)- // Shadow verify: if user declines approval, skip hooks but continue squash- let verify = if verify {- let env = CommandEnv::for_action("squash")?;- let ctx = env.context(yes);- let approved = approve_hooks(&ctx, &[HookType::PreCommit])?;- if !approved {- eprintln!(- "{}",- info_message("Commands declined, squashing without hooks")- );- }- approved- } else {- false- };-- match handle_squash(target.as_deref(), yes, !verify, stage)? {- 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")- );- }+ // Approval is handled inside handle_squash (like step_commit)+ handle_squash(target.as_deref(), yes, !verify, stage).map(|result| match result+ {+ SquashResult::Squashed | SquashResult::NoNetChanges => {}+ SquashResult::NoCommitsAhead(branch) => {+ eprintln!(+ "{}",+ info_message(format!(+ "Nothing to squash; no commits ahead of {branch}"+ ))+ );}- Ok(())- })()+ SquashResult::AlreadySingleCommit => {+ eprintln!(+ "{}",+ info_message("Nothing to squash; already a single commit")+ );+ }+ })}}StepCommand::Push { target } => handle_push(target.as_deref(), "Pushed to", None),@@ -773,163 +754,20 @@ fn main() {} => UserConfig::load().context("Failed to load config").and_then(|mut config| {- let repo = Repository::current().context("Failed to switch worktree")?;-- // Validate FIRST (before approval) - fails fast if branch doesn't exist, etc.- let plan = plan_switch(&repo, &branch, create, base.as_deref(), clobber, &config)?;-- // "Approve at the Gate": collect and approve hooks upfront- // This ensures approval happens once at the command entry point- // If user declines, skip hooks but continue with worktree operation- let approved = if verify {- let ctx = CommandContext::new(- &repo,- &config,- Some(plan.branch()),- plan.worktree_path(),- yes,- );- // Approve different hooks based on whether we're creating or switching- if plan.is_create() {- approve_hooks(- &ctx,- &[- HookType::PostCreate,- HookType::PostStart,- HookType::PostSwitch,- ],- )?- } else {- // When switching to existing, only post-switch needs approval- approve_hooks(&ctx, &[HookType::PostSwitch])?- }- } else {- true // --no-verify: skip all hooks- };-- // Skip hooks if --no-verify or user declined approval- let skip_hooks = !verify || !approved;-- // Show message if user declined approval- if !approved {- eprintln!(- "{}",- info_message(if plan.is_create() {- "Commands declined, continuing worktree creation"- } else {- "Commands declined"- })- );- }-- // Execute the validated plan- let (result, branch_info) = execute_switch(&repo, plan, &config, yes, skip_hooks)?;-- // Show success message (temporal locality: immediately after worktree operation)- // Returns path to display in hooks when user's shell won't be in the worktree- // Also shows worktree-path hint on first --create (before shell integration warning)- let hooks_display_path = handle_switch_output(&result, &branch_info)?;-- // Offer shell integration if not already installed/active- // (only shows prompt/hint when shell integration isn't working)- // With --execute: show hints only (don't interrupt with prompt)- // Best-effort: don't fail switch if offer fails- if !output::is_shell_integration_active() {- let skip_prompt = execute.is_some();- let _ =- output::prompt_shell_integration(&mut config, &binary_name(), skip_prompt);- }-- // Build extra vars for base branch context (used by both hooks and --execute)- // "base" is the branch we branched from when creating a new worktree.- // For existing worktrees, there's no base concept.- let (base_branch, base_worktree_path): (Option<&str>, Option<&str>) = match &result- {- SwitchResult::Created {- base_branch,- base_worktree_path,- ..- } => (base_branch.as_deref(), base_worktree_path.as_deref()),- SwitchResult::Existing { .. } | SwitchResult::AlreadyAt(_) => (None, None),- };- let extra_vars: Vec<(&str, &str)> = [- base_branch.map(|b| ("base", b)),- base_worktree_path.map(|p| ("base_worktree_path", p)),- ]- .into_iter()- .flatten()- .collect();-- // Spawn background hooks after success message- // - post-switch: runs on ALL switches (shows "@ path" when shell won't be there)- // - post-start: runs only when creating a NEW worktree- if !skip_hooks {- let repo = Repository::current()?;- let ctx = CommandContext::new(- &repo,- &config,- Some(&branch_info.branch),- result.path(),- yes,- );-- // Post-switch runs first (immediate "I'm here" signal)- ctx.spawn_post_switch_commands(&extra_vars, hooks_display_path.as_deref())?;-- // Post-start runs only on creation (setup tasks)- if matches!(&result, SwitchResult::Created { .. }) {- ctx.spawn_post_start_commands(&extra_vars, hooks_display_path.as_deref())?;- }- }-- // Execute user command after post-start hooks have been spawned- // Note: execute_args requires execute via clap's `requires` attribute- if let Some(cmd) = execute {- // Build template context for expansion (includes base vars when creating)- let repo = Repository::current()?;- let ctx = CommandContext::new(- &repo,- &config,- Some(&branch_info.branch),- result.path(),+ handle_switch(+ SwitchOptions {+ branch: &branch,+ create,+ base: base.as_deref(),+ execute: execute.as_deref(),+ execute_args: &execute_args,yes,- );- let template_vars = build_hook_context(&ctx, &extra_vars);- let vars: HashMap<&str, &str> = template_vars- .iter()- .map(|(k, v)| (k.as_str(), v.as_str()))- .collect();-- // Expand template variables in command (shell_escape: true for safety)- let expanded_cmd =- expand_template(&cmd, &vars, true, &repo, "--execute command").map_err(- |e| anyhow::anyhow!("Failed to expand --execute template: {}", e),- )?;-- // Append any trailing args (after --) to the execute command- // Each arg is also expanded, then shell-escaped- let full_cmd = if execute_args.is_empty() {- expanded_cmd- } else {- let expanded_args: Result<Vec<_>, _> = execute_args- .iter()- .map(|arg| {- expand_template(arg, &vars, false, &repo, "--execute argument")- .map_err(|e| {- anyhow::anyhow!("Failed to expand argument template: {}", e)- })- })- .collect();- let escaped_args: Vec<_> = expanded_args?- .iter()- .map(|arg| shlex::try_quote(arg).unwrap_or(arg.into()).into_owned())- .collect();- format!("{} {}", expanded_cmd, escaped_args.join(" "))- };- execute_user_command(&full_cmd, hooks_display_path.as_deref())?;- }-- Ok(())+ clobber,+ verify,+ },+ &mut config,+ &binary_name(),+ )}),Commands::Remove {branches,diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 7309f4b56..c22beb5eb 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -12,7 +12,7 @@ use crate::commands::branch_deletion::{BranchDeletionOutcome, BranchDeletionResult, delete_branch_if_safe,};use crate::commands::command_executor::CommandContext;-use crate::commands::execute_pre_remove_commands;+use crate::commands::hooks::{HookFailureStrategy, execute_hook, spawn_hook_background};use crate::commands::process::{HookLog, InternalOp, build_remove_command, spawn_detached};use crate::commands::worktree::{BranchDeletionMode, RemoveResult, SwitchBranchInfo, SwitchResult};use worktrunk::config::UserConfig;@@ -657,7 +657,13 @@ fn spawn_post_switch_after_remove(false, // yes=false for CommandContext);// No base context for remove-triggered switch (we're returning to main, not creating)- ctx.spawn_post_switch_commands(&[], super::post_hook_display_path(main_path))+ spawn_hook_background(+ &ctx,+ worktrunk::HookType::PostSwitch,+ &[],+ None,+ super::post_hook_display_path(main_path),+ )}// ============================================================================@@ -892,7 +898,14 @@ fn handle_removed_worktree_output(} else {Some(worktree_path) // Show path when user is elsewhere};- execute_pre_remove_commands(&ctx, None, display_path, &[])?;+ execute_hook(+ &ctx,+ worktrunk::HookType::PreRemove,+ &[],+ HookFailureStrategy::FailFast,+ None,+ display_path,+ )?;}// Emit cd directive only after pre-remove hooks succeed