|
| 1 | +//! Switch command handler. |
| 2 | +
|
| 3 | +use std::collections::HashMap; |
| 4 | + |
| 5 | +use anyhow::Context; |
| 6 | +use worktrunk::HookType; |
| 7 | +use worktrunk::config::{UserConfig, expand_template}; |
| 8 | +use worktrunk::git::Repository; |
| 9 | +use worktrunk::styling::{eprintln, info_message}; |
| 10 | + |
| 11 | +use super::command_approval::approve_hooks; |
| 12 | +use super::command_executor::{CommandContext, build_hook_context}; |
| 13 | +use super::worktree::{SwitchResult, execute_switch, plan_switch}; |
| 14 | +use crate::output::{ |
| 15 | + execute_user_command, handle_switch_output, is_shell_integration_active, |
| 16 | + prompt_shell_integration, |
| 17 | +}; |
| 18 | + |
| 19 | +/// Options for the switch command |
| 20 | +pub struct SwitchOptions<'a> { |
| 21 | + pub branch: &'a str, |
| 22 | + pub create: bool, |
| 23 | + pub base: Option<&'a str>, |
| 24 | + pub execute: Option<&'a str>, |
| 25 | + pub execute_args: &'a [String], |
| 26 | + pub yes: bool, |
| 27 | + pub clobber: bool, |
| 28 | + pub verify: bool, |
| 29 | +} |
| 30 | + |
| 31 | +/// Handle the switch command. |
| 32 | +pub fn handle_switch( |
| 33 | + opts: SwitchOptions<'_>, |
| 34 | + config: &mut UserConfig, |
| 35 | + binary_name: &str, |
| 36 | +) -> anyhow::Result<()> { |
| 37 | + let SwitchOptions { |
| 38 | + branch, |
| 39 | + create, |
| 40 | + base, |
| 41 | + execute, |
| 42 | + execute_args, |
| 43 | + yes, |
| 44 | + clobber, |
| 45 | + verify, |
| 46 | + } = opts; |
| 47 | + |
| 48 | + let repo = Repository::current().context("Failed to switch worktree")?; |
| 49 | + |
| 50 | + // Validate FIRST (before approval) - fails fast if branch doesn't exist, etc. |
| 51 | + let plan = plan_switch(&repo, branch, create, base, clobber, config)?; |
| 52 | + |
| 53 | + // "Approve at the Gate": collect and approve hooks upfront |
| 54 | + // This ensures approval happens once at the command entry point |
| 55 | + // If user declines, skip hooks but continue with worktree operation |
| 56 | + let approved = if verify { |
| 57 | + let ctx = CommandContext::new( |
| 58 | + &repo, |
| 59 | + config, |
| 60 | + Some(plan.branch()), |
| 61 | + plan.worktree_path(), |
| 62 | + yes, |
| 63 | + ); |
| 64 | + // Approve different hooks based on whether we're creating or switching |
| 65 | + if plan.is_create() { |
| 66 | + approve_hooks( |
| 67 | + &ctx, |
| 68 | + &[ |
| 69 | + HookType::PostCreate, |
| 70 | + HookType::PostStart, |
| 71 | + HookType::PostSwitch, |
| 72 | + ], |
| 73 | + )? |
| 74 | + } else { |
| 75 | + // When switching to existing, only post-switch needs approval |
| 76 | + approve_hooks(&ctx, &[HookType::PostSwitch])? |
| 77 | + } |
| 78 | + } else { |
| 79 | + true // --no-verify: skip all hooks |
| 80 | + }; |
| 81 | + |
| 82 | + // Skip hooks if --no-verify or user declined approval |
| 83 | + let skip_hooks = !verify || !approved; |
| 84 | + |
| 85 | + // Show message if user declined approval |
| 86 | + if !approved { |
| 87 | + eprintln!( |
| 88 | + "{}", |
| 89 | + info_message(if plan.is_create() { |
| 90 | + "Commands declined, continuing worktree creation" |
| 91 | + } else { |
| 92 | + "Commands declined" |
| 93 | + }) |
| 94 | + ); |
| 95 | + } |
| 96 | + |
| 97 | + // Execute the validated plan |
| 98 | + let (result, branch_info) = execute_switch(&repo, plan, config, yes, skip_hooks)?; |
| 99 | + |
| 100 | + // Show success message (temporal locality: immediately after worktree operation) |
| 101 | + // Returns path to display in hooks when user's shell won't be in the worktree |
| 102 | + // Also shows worktree-path hint on first --create (before shell integration warning) |
| 103 | + let hooks_display_path = handle_switch_output(&result, &branch_info)?; |
| 104 | + |
| 105 | + // Offer shell integration if not already installed/active |
| 106 | + // (only shows prompt/hint when shell integration isn't working) |
| 107 | + // With --execute: show hints only (don't interrupt with prompt) |
| 108 | + // Best-effort: don't fail switch if offer fails |
| 109 | + if !is_shell_integration_active() { |
| 110 | + let skip_prompt = execute.is_some(); |
| 111 | + let _ = prompt_shell_integration(config, binary_name, skip_prompt); |
| 112 | + } |
| 113 | + |
| 114 | + // Build extra vars for base branch context (used by both hooks and --execute) |
| 115 | + // "base" is the branch we branched from when creating a new worktree. |
| 116 | + // For existing worktrees, there's no base concept. |
| 117 | + let (base_branch, base_worktree_path): (Option<&str>, Option<&str>) = match &result { |
| 118 | + SwitchResult::Created { |
| 119 | + base_branch, |
| 120 | + base_worktree_path, |
| 121 | + .. |
| 122 | + } => (base_branch.as_deref(), base_worktree_path.as_deref()), |
| 123 | + SwitchResult::Existing { .. } | SwitchResult::AlreadyAt(_) => (None, None), |
| 124 | + }; |
| 125 | + let extra_vars: Vec<(&str, &str)> = [ |
| 126 | + base_branch.map(|b| ("base", b)), |
| 127 | + base_worktree_path.map(|p| ("base_worktree_path", p)), |
| 128 | + ] |
| 129 | + .into_iter() |
| 130 | + .flatten() |
| 131 | + .collect(); |
| 132 | + |
| 133 | + // Spawn background hooks after success message |
| 134 | + // - post-switch: runs on ALL switches (shows "@ path" when shell won't be there) |
| 135 | + // - post-start: runs only when creating a NEW worktree |
| 136 | + if !skip_hooks { |
| 137 | + let ctx = CommandContext::new(&repo, config, Some(&branch_info.branch), result.path(), yes); |
| 138 | + |
| 139 | + // Post-switch runs first (immediate "I'm here" signal) |
| 140 | + ctx.spawn_post_switch_commands(&extra_vars, hooks_display_path.as_deref())?; |
| 141 | + |
| 142 | + // Post-start runs only on creation (setup tasks) |
| 143 | + if matches!(&result, SwitchResult::Created { .. }) { |
| 144 | + ctx.spawn_post_start_commands(&extra_vars, hooks_display_path.as_deref())?; |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + // Execute user command after post-start hooks have been spawned |
| 149 | + // Note: execute_args requires execute via clap's `requires` attribute |
| 150 | + if let Some(cmd) = execute { |
| 151 | + // Build template context for expansion (includes base vars when creating) |
| 152 | + let ctx = CommandContext::new(&repo, config, Some(&branch_info.branch), result.path(), yes); |
| 153 | + let template_vars = build_hook_context(&ctx, &extra_vars); |
| 154 | + let vars: HashMap<&str, &str> = template_vars |
| 155 | + .iter() |
| 156 | + .map(|(k, v)| (k.as_str(), v.as_str())) |
| 157 | + .collect(); |
| 158 | + |
| 159 | + // Expand template variables in command (shell_escape: true for safety) |
| 160 | + let expanded_cmd = expand_template(cmd, &vars, true, &repo, "--execute command") |
| 161 | + .map_err(|e| anyhow::anyhow!("Failed to expand --execute template: {}", e))?; |
| 162 | + |
| 163 | + // Append any trailing args (after --) to the execute command |
| 164 | + // Each arg is also expanded, then shell-escaped |
| 165 | + let full_cmd = if execute_args.is_empty() { |
| 166 | + expanded_cmd |
| 167 | + } else { |
| 168 | + let expanded_args: Result<Vec<_>, _> = execute_args |
| 169 | + .iter() |
| 170 | + .map(|arg| { |
| 171 | + expand_template(arg, &vars, false, &repo, "--execute argument") |
| 172 | + .map_err(|e| anyhow::anyhow!("Failed to expand argument template: {}", e)) |
| 173 | + }) |
| 174 | + .collect(); |
| 175 | + let escaped_args: Vec<_> = expanded_args? |
| 176 | + .iter() |
| 177 | + .map(|arg| shlex::try_quote(arg).unwrap_or(arg.into()).into_owned()) |
| 178 | + .collect(); |
| 179 | + format!("{} {}", expanded_cmd, escaped_args.join(" ")) |
| 180 | + }; |
| 181 | + execute_user_command(&full_cmd, hooks_display_path.as_deref())?; |
| 182 | + } |
| 183 | + |
| 184 | + Ok(()) |
| 185 | +} |
0 commit comments