Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(switch): consolidate handle_switch into worktree/switch (#2597)
Maximilian Roos3a01e67d1280
diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rsdeleted file mode 100644index aff123a6a..000000000--- a/src/commands/handle_switch.rs+++ /dev/null@@ -1,506 +0,0 @@-//! Switch command handler.--use std::collections::HashMap;-use std::path::{Path, PathBuf};--use anyhow::Context;-use serde::Serialize;-use worktrunk::HookType;-use worktrunk::config::{- UserConfig, ValidationScope, expand_template, template_references_var, validate_template,-};-use worktrunk::git::{GitError, Repository, SwitchSuggestionCtx, current_or_recover};--use crate::cli::SwitchFormat;--use super::command_approval::{approve_hooks, approve_or_skip};-use super::command_executor::FailureStrategy;-use super::command_executor::{CommandContext, build_hook_context};-use super::hooks::{HookAnnouncer, execute_hook};-use super::template_vars::TemplateVars;-use super::worktree::{- SwitchBranchInfo, SwitchPlan, SwitchResult, execute_switch, offer_bare_repo_worktree_path_fix,- path_mismatch, plan_switch,-};-use crate::output::{- execute_user_command, handle_switch_output, is_shell_integration_active,- prompt_shell_integration,-};--/// Structured output for `wt switch --format=json`.-#[derive(Serialize)]-struct SwitchJsonOutput {- action: &'static str,- /// Branch name- #[serde(skip_serializing_if = "Option::is_none")]- branch: Option<String>,- /// Absolute worktree path- path: PathBuf,- /// True if branch was created (--create flag)- #[serde(skip_serializing_if = "Option::is_none")]- created_branch: Option<bool>,- /// Base branch when creating (e.g., "main")- #[serde(skip_serializing_if = "Option::is_none")]- base_branch: Option<String>,- /// Remote tracking branch if auto-created- #[serde(skip_serializing_if = "Option::is_none")]- from_remote: Option<String>,-}--impl SwitchJsonOutput {- fn from_result(result: &SwitchResult, branch_info: &SwitchBranchInfo) -> Self {- let (action, path, created_branch, base_branch, from_remote) = match result {- SwitchResult::AlreadyAt(path) => ("already_at", path, None, None, None),- SwitchResult::Existing { path } => ("existing", path, None, None, None),- SwitchResult::Created {- path,- created_branch,- base_branch,- from_remote,- ..- } => (- "created",- path,- Some(*created_branch),- base_branch.clone(),- from_remote.clone(),- ),- };- Self {- action,- branch: branch_info.branch.clone(),- path: path.clone(),- created_branch,- base_branch,- from_remote,- }- }-}--/// 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,- /// Resolved from --cd/--no-cd flags: Some(true) = cd, Some(false) = no cd, None = use config- pub change_dir: Option<bool>,- pub verify: bool,- pub format: crate::cli::SwitchFormat,-}--/// Run pre-switch hooks before branch resolution or worktree creation.-///-/// Symbolic arguments (`-`, `@`, `^`) are resolved to concrete branch names-/// before building the hook context so `{{ target }}`, `{{ target_worktree_path }}`,-/// and the Active overrides point at the real destination. When resolution-/// fails (e.g., no previous branch for `-`), the raw argument is used — the-/// same error surfaces later from `plan_switch` with the canonical message.-///-/// Directional vars:-/// - `base` / `base_worktree_path`: current (source) branch and worktree-/// - `target` / `target_worktree_path`: destination branch and worktree (if it exists)-pub(crate) fn run_pre_switch_hooks(- repo: &Repository,- config: &UserConfig,- target_branch: &str,- yes: bool,-) -> anyhow::Result<()> {- let current_wt = repo.current_worktree();- let current_path = current_wt.path().to_path_buf();- let resolved_target = repo- .resolve_worktree_name(target_branch)- .unwrap_or_else(|_| target_branch.to_string());- let pre_ctx = CommandContext::new(repo, config, Some(&resolved_target), ¤t_path, yes);-- let pre_switch_approved = approve_hooks(&pre_ctx, &[HookType::PreSwitch])?;- if pre_switch_approved {- // Base vars: source (where the user currently is). Target vars and- // Active overrides come from the destination worktree if it exists —- // for creates the planned path is computed later during plan_switch,- // so worktree_path stays at its default (the source = cwd).- let base_branch = current_wt.branch().ok().flatten().unwrap_or_default();- let dest_path = repo.worktree_for_branch(&resolved_target).ok().flatten();-- let mut vars = TemplateVars::new()- .with_base(&base_branch, ¤t_path)- .with_target(&resolved_target);- if let Some(p) = dest_path.as_deref() {- vars = vars.with_target_worktree_path(p).with_active_worktree(p);- }- let extra_vars = vars.as_extra_vars();-- execute_hook(- &pre_ctx,- HookType::PreSwitch,- &extra_vars,- FailureStrategy::FailFast,- crate::output::pre_hook_display_path(pre_ctx.worktree_path),- )?;- }- Ok(())-}--/// Hook types that apply after a switch operation.-///-/// Creates trigger pre-start + post-start + post-switch hooks;-/// existing worktrees trigger only post-switch.-fn switch_post_hook_types(is_create: bool) -> &'static [HookType] {- if is_create {- &[- HookType::PreStart,- HookType::PostStart,- HookType::PostSwitch,- ]- } else {- &[HookType::PostSwitch]- }-}--/// Approve switch hooks upfront and show "Commands declined" if needed.-///-/// Returns `true` if hooks are approved to run.-/// Returns `false` if hooks should be skipped (`!verify` or user declined).-pub(crate) fn approve_switch_hooks(- repo: &Repository,- config: &UserConfig,- plan: &SwitchPlan,- yes: bool,- verify: bool,-) -> anyhow::Result<bool> {- if !verify {- return Ok(false);- }-- let ctx = CommandContext::new(repo, config, plan.branch(), plan.worktree_path(), yes);- let on_decline = if plan.is_create() {- "Commands declined, continuing worktree creation"- } else {- "Commands declined"- };- approve_or_skip(&ctx, switch_post_hook_types(plan.is_create()), on_decline)-}--/// Spawn post-switch (and post-start for creates) background hooks.-pub(crate) fn spawn_switch_background_hooks(- repo: &Repository,- config: &UserConfig,- result: &SwitchResult,- branch: Option<&str>,- yes: bool,- extra_vars: &[(&str, &str)],- hooks_display_path: Option<&Path>,-) -> anyhow::Result<()> {- let ctx = CommandContext::new(repo, config, branch, result.path(), yes);-- let mut announcer = HookAnnouncer::new(repo, config, false);- announcer.register(&ctx, HookType::PostSwitch, extra_vars, hooks_display_path)?;- if matches!(result, SwitchResult::Created { .. }) {- announcer.register(&ctx, HookType::PostStart, extra_vars, hooks_display_path)?;- }- announcer.flush()-}--/// 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,- change_dir: change_dir_flag,- verify,- format,- } = opts;-- let (repo, is_recovered) = current_or_recover().context("Failed to switch worktree")?;-- // Resolve change_dir: explicit CLI flags > project config > global config > default (true)- // Now that we have the repo, we can resolve project-specific config.- let change_dir = change_dir_flag.unwrap_or_else(|| {- let project_id = repo.project_identifier().ok();- config.resolved(project_id.as_deref()).switch.cd()- });-- // Build switch suggestion context for enriching error hints with --execute/trailing args.- // Without this, errors like "branch already exists" would suggest `wt switch <branch>`- // instead of the full `wt switch <branch> --execute=<cmd> -- <args>`.- let suggestion_ctx = execute.map(|exec| {- let escaped = shell_escape::escape(exec.into());- SwitchSuggestionCtx {- extra_flags: vec![format!("--execute={escaped}")],- trailing_args: execute_args.to_vec(),- }- });-- // Run pre-switch hooks before branch resolution or worktree creation.- // {{ branch }} receives the raw user input (before resolution).- // Skip when recovered — the source worktree is gone, nothing to run hooks against.- if verify && !is_recovered {- run_pre_switch_hooks(&repo, config, branch, yes)?;- }-- // Offer to fix worktree-path for bare repos with hidden directory names (.git, .bare).- offer_bare_repo_worktree_path_fix(&repo, config)?;-- // Validate and resolve the target branch.- let plan = plan_switch(&repo, branch, create, base, clobber, config).map_err(|err| {- match suggestion_ctx {- Some(ref ctx) => match err.downcast::<GitError>() {- Ok(git_err) => GitError::WithSwitchSuggestion {- source: Box::new(git_err),- ctx: ctx.clone(),- }- .into(),- Err(err) => err,- },- None => err,- }- })?;-- // "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 hooks_approved = approve_switch_hooks(&repo, config, &plan, yes, verify)?;-- // Pre-flight: validate all templates before mutation (worktree creation).- // Catches syntax errors and undefined variables early so a broken template- // doesn't leave behind a half-created worktree that blocks re-running.- validate_switch_templates(&repo, config, &plan, execute, execute_args, hooks_approved)?;-- // Capture source (base) worktree identity BEFORE the switch, so post-switch- // hooks can reference where the user came from via {{ base }} / {{ base_worktree_path }}.- let source_branch = repo- .current_worktree()- .branch()- .ok()- .flatten()- .unwrap_or_default();- let source_path = repo- .current_worktree()- .root()- .ok()- .map(|p| worktrunk::path::to_posix_path(&p.to_string_lossy()))- .unwrap_or_default();-- // Execute the validated plan- let (result, branch_info) = execute_switch(&repo, plan, config, yes, hooks_approved)?;-- // --format=json: write structured result to stdout. All behavior (hooks,- // --execute, shell integration) proceeds normally — format only affects output.- if format == SwitchFormat::Json {- let json = SwitchJsonOutput::from_result(&result, &branch_info);- let json = serde_json::to_string(&json).context("Failed to serialize to JSON")?;- println!("{json}");- }-- // Early exit for benchmarking time-to-first-output- if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {- return Ok(());- }-- // Compute path mismatch lazily (deferred from plan_switch for existing worktrees).- // Skip for detached HEAD worktrees (branch is None) — no branch to compute expected path from.- let branch_info = match &result {- SwitchResult::Existing { path } | SwitchResult::AlreadyAt(path) => {- let expected_path = branch_info- .branch- .as_deref()- .and_then(|b| path_mismatch(&repo, b, path, config));- SwitchBranchInfo {- expected_path,- ..branch_info- }- }- _ => branch_info,- };-- // 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)- //- // When recovered from a deleted worktree, current_dir() and current_worktree().root()- // both fail — fall back to repo_path() (the main worktree root).- let fallback_path = repo.repo_path()?.to_path_buf();- let cwd = std::env::current_dir().unwrap_or(fallback_path.clone());- let source_root = repo.current_worktree().root().unwrap_or(fallback_path);- let hooks_display_path =- handle_switch_output(&result, &branch_info, change_dir, Some(&source_root), &cwd)?;-- // 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)- // Skip when change_dir is false — user opted out of cd, so shell integration is irrelevant- // Best-effort: don't fail switch if offer fails- if change_dir && !is_shell_integration_active() {- let skip_prompt = execute.is_some();- let _ = prompt_shell_integration(config, binary_name, skip_prompt);- }-- // Build template vars for base/target context (used by both hooks and- // --execute). "base" is the source worktree the user switched from (all- // switches), or the branch they branched from (creates). "target" matches- // the bare vars (the destination) — kept symmetric with pre-switch.- let template_vars =- TemplateVars::for_post_switch(&result, &branch_info, &source_branch, &source_path);- let extra_vars = template_vars.as_extra_vars();-- // 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- // Batch hooks into a single message when both types are present- if hooks_approved {- spawn_switch_background_hooks(- &repo,- config,- &result,- branch_info.branch.as_deref(),- yes,- &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,- branch_info.branch.as_deref(),- result.path(),- yes,- );- let template_vars = build_hook_context(&ctx, &extra_vars, None)?;- 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")?;-- // 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"))- .collect();- let escaped_args: Vec<_> = expanded_args?- .iter()- .map(|arg| shell_escape::escape(arg.into()).into_owned())- .collect();- format!("{} {}", expanded_cmd, escaped_args.join(" "))- };- execute_user_command(&full_cmd, hooks_display_path.as_deref())?;- }-- Ok(())-}--/// Validate all templates that will be expanded after worktree creation.-///-/// Catches syntax errors and undefined variable references *before* the-/// irreversible worktree creation, so a broken template doesn't leave behind-/// a worktree that blocks re-running the command.-///-/// This is a best-effort pre-flight check: it catches definite errors (syntax,-/// unknown variables) but cannot catch failures from conditional variables that-/// are absent at expansion time (e.g., `upstream` when no tracking is configured).-/// Such late failures propagate as normal errors — no panics.-///-/// ## Why only switch needs pre-flight validation-///-/// Switch is the only command where template failure after mutation creates a-/// **blocking half-state**: `wt switch -c <branch>` creates a worktree, then if-/// hook/--execute expansion fails, the worktree exists and the same command-/// can't be re-run (branch already exists). Other commands don't have this-/// problem:-///-/// - **Pre-operation hooks** (pre-merge, pre-remove, pre-commit) run before the-/// irreversible operation, so template errors abort cleanly.-/// - **Post-operation hooks** (post-merge, post-remove) run after the operation-/// completed successfully — template failure is a missed notification, not a-/// blocking state. The user can fix the template and run `wt hook` manually.-///-/// Validates:-/// - `--execute` command template (if present)-/// - `--execute` trailing arg templates (if present)-/// - Hook templates (post-create, post-start, post-switch) from user and project config-fn validate_switch_templates(- repo: &Repository,- config: &UserConfig,- plan: &SwitchPlan,- execute: Option<&str>,- execute_args: &[String],- hooks_approved: bool,-) -> anyhow::Result<()> {- // Validate --execute template and trailing args- if let Some(cmd) = execute {- validate_template(- cmd,- ValidationScope::SwitchExecute,- repo,- "--execute command",- )?;- for arg in execute_args {- validate_template(- arg,- ValidationScope::SwitchExecute,- repo,- "--execute argument",- )?;- }- }-- // Validate hook templates only when hooks will actually run- if !hooks_approved {- return Ok(());- }-- let project_config = repo.load_project_config()?;- let user_hooks = config.hooks(repo.project_identifier().ok().as_deref());-- for &hook_type in switch_post_hook_types(plan.is_create()) {- let (user_cfg, proj_cfg) =- super::hooks::lookup_hook_configs(&user_hooks, project_config.as_ref(), hook_type);- for (source, cfg) in [("user", user_cfg), ("project", proj_cfg)] {- if let Some(cfg) = cfg {- for cmd in cfg.commands() {- // Skip full validation for lazy templates ({{ vars.X }}) —- // they're expanded at runtime after prior pipeline steps set- // the vars. Syntax is still checked by expand_commands.- if template_references_var(&cmd.template, "vars") {- continue;- }- let name = match &cmd.name {- Some(n) => format!("{source} {hook_type}:{n}"),- None => format!("{source} {hook_type} hook"),- };- validate_template(- &cmd.template,- ValidationScope::Hook(hook_type),- repo,- &name,- )?;- }- }- }- }-- Ok(())-}diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex b92a1615c..1e1e1ed90 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -8,7 +8,6 @@ pub(crate) mod context;pub(crate) mod custom;mod eval;mod for_each;-mod handle_switch;mod hook_announcement;mod hook_commands;mod hook_filter;@@ -47,7 +46,6 @@ pub(crate) use configure_shell::{pub(crate) use custom::handle_custom_command;pub(crate) use eval::step_eval;pub(crate) use for_each::step_for_each;-pub(crate) use handle_switch::{SwitchOptions, handle_switch};pub(crate) use hook_commands::{HookCliArgs, handle_hook_show, run_hook};pub(crate) use init::{handle_completions, handle_init};pub(crate) use list::handle_list;@@ -62,7 +60,8 @@ pub(crate) use step::{step_show_squash_prompt,};pub(crate) use worktree::{- OperationMode, is_worktree_at_expected_path, resolve_worktree_arg, worktree_display_name,+ OperationMode, SwitchOptions, is_worktree_at_expected_path, resolve_worktree_arg, run_switch,+ worktree_display_name,};// Re-export Shell from the canonical locationdiff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex caf9b10a5..e393c11da 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -109,9 +109,6 @@ use skim::reader::CommandCollector;use worktrunk::git::{Repository, current_or_recover};use super::command_executor::FailureStrategy;-use super::handle_switch::{- approve_switch_hooks, run_pre_switch_hooks, spawn_switch_background_hooks,-};use super::hooks::{HookAnnouncer, execute_hook};use super::list::collect;use super::list::progressive::RenderTarget;@@ -119,8 +116,9 @@ use super::repository_ext::{RemoveTarget, RepositoryCliExt};use super::template_vars::TemplateVars;use super::worktree::hooks::PostRemoveContext;use super::worktree::{- RemoveResult, SwitchBranchInfo, SwitchResult, execute_switch,- offer_bare_repo_worktree_path_fix, path_mismatch, plan_switch,+ RemoveResult, SwitchBranchInfo, SwitchResult, approve_switch_hooks, execute_switch,+ offer_bare_repo_worktree_path_fix, path_mismatch, plan_switch, run_pre_switch_hooks,+ spawn_switch_background_hooks,};use crate::commands::command_executor::CommandContext;use crate::output::handle_switch_output;diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rsindex 18bf59731..64f3586fe 100644--- a/src/commands/worktree/mod.rs+++ b/src/commands/worktree/mod.rs@@ -91,11 +91,17 @@ mod types;// Re-export public types and functionspub use finish::{FinishAfterMergeArgs, finish_after_merge};pub use push::{PushKind, PushOutcome, PushResult, handle_no_ff_merge, handle_push};+#[cfg(unix)]+pub use resolve::offer_bare_repo_worktree_path_fix;pub use resolve::{- compute_worktree_path, is_worktree_at_expected_path, offer_bare_repo_worktree_path_fix,- path_mismatch, resolve_worktree_arg, worktree_display_name,+ compute_worktree_path, is_worktree_at_expected_path, path_mismatch, resolve_worktree_arg,+ worktree_display_name,};-pub use switch::{execute_switch, plan_switch};-pub use types::{- MergeOperations, OperationMode, RemoveResult, SwitchBranchInfo, SwitchPlan, SwitchResult,+pub use switch::{SwitchOptions, run_switch};+#[cfg(unix)]+pub(crate) use switch::{+ approve_switch_hooks, run_pre_switch_hooks, spawn_switch_background_hooks,};+#[cfg(unix)]+pub use switch::{execute_switch, plan_switch};+pub use types::{MergeOperations, OperationMode, RemoveResult, SwitchBranchInfo, SwitchResult};diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 5965dc377..a6104cc0e 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -1,27 +1,45 @@//! Worktree switch operations.//!-//! Functions for planning and executing worktree switches.+//! Planning and executing worktree switches, plus the `wt switch` entry point+//! that wires hooks, approvals, output, and shell integration around them.-use std::path::Path;+use std::collections::HashMap;+use std::path::{Path, PathBuf};use crate::display::format_relative_time_short;use anyhow::Context;use color_print::cformat;use dunce::canonicalize;-use worktrunk::config::UserConfig;+use serde::Serialize;+use worktrunk::HookType;+use worktrunk::config::{+ UserConfig, ValidationScope, expand_template, template_references_var, validate_template,+};use worktrunk::git::remote_ref::{self, GitHubProvider, GitLabProvider, RemoteRefInfo, RemoteRefProvider,};-use worktrunk::git::{GitError, RefContext, RefType, Repository};+use worktrunk::git::{+ GitError, RefContext, RefType, Repository, SwitchSuggestionCtx, current_or_recover,+};use worktrunk::styling::{eprintln, format_with_gutter, hint_message, info_message, progress_message, suggest_command,warning_message,};-use super::resolve::{compute_clobber_backup, compute_worktree_path};+use super::resolve::{+ compute_clobber_backup, compute_worktree_path, offer_bare_repo_worktree_path_fix, path_mismatch,+};use super::types::{CreationMethod, SwitchBranchInfo, SwitchPlan, SwitchResult};-use crate::commands::command_executor::CommandContext;+use crate::cli::SwitchFormat;+use crate::commands::command_approval::{approve_hooks, approve_or_skip};+use crate::commands::command_executor::FailureStrategy;+use crate::commands::command_executor::{CommandContext, build_hook_context};+use crate::commands::hooks::{HookAnnouncer, execute_hook};use crate::commands::template_vars::TemplateVars;+use crate::output::{+ execute_user_command, handle_switch_output, is_shell_integration_active,+ prompt_shell_integration,+};/// Result of resolving the switch target.struct ResolvedTarget {@@ -1023,3 +1041,484 @@ fn format_last_fetch_ago(repo: &Repository) -> Option<String> {Some(format!("last fetched {relative} ago"))}}++/// Structured output for `wt switch --format=json`.+#[derive(Serialize)]+struct SwitchJsonOutput {+ action: &'static str,+ /// Branch name+ #[serde(skip_serializing_if = "Option::is_none")]+ branch: Option<String>,+ /// Absolute worktree path+ path: PathBuf,+ /// True if branch was created (--create flag)+ #[serde(skip_serializing_if = "Option::is_none")]+ created_branch: Option<bool>,+ /// Base branch when creating (e.g., "main")+ #[serde(skip_serializing_if = "Option::is_none")]+ base_branch: Option<String>,+ /// Remote tracking branch if auto-created+ #[serde(skip_serializing_if = "Option::is_none")]+ from_remote: Option<String>,+}++impl SwitchJsonOutput {+ fn from_result(result: &SwitchResult, branch_info: &SwitchBranchInfo) -> Self {+ let (action, path, created_branch, base_branch, from_remote) = match result {+ SwitchResult::AlreadyAt(path) => ("already_at", path, None, None, None),+ SwitchResult::Existing { path } => ("existing", path, None, None, None),+ SwitchResult::Created {+ path,+ created_branch,+ base_branch,+ from_remote,+ ..+ } => (+ "created",+ path,+ Some(*created_branch),+ base_branch.clone(),+ from_remote.clone(),+ ),+ };+ Self {+ action,+ branch: branch_info.branch.clone(),+ path: path.clone(),+ created_branch,+ base_branch,+ from_remote,+ }+ }+}++/// 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,+ /// Resolved from --cd/--no-cd flags: Some(true) = cd, Some(false) = no cd, None = use config+ pub change_dir: Option<bool>,+ pub verify: bool,+ pub format: crate::cli::SwitchFormat,+}++/// Run pre-switch hooks before branch resolution or worktree creation.+///+/// Symbolic arguments (`-`, `@`, `^`) are resolved to concrete branch names+/// before building the hook context so `{{ target }}`, `{{ target_worktree_path }}`,+/// and the Active overrides point at the real destination. When resolution+/// fails (e.g., no previous branch for `-`), the raw argument is used — the+/// same error surfaces later from `plan_switch` with the canonical message.+///+/// Directional vars:+/// - `base` / `base_worktree_path`: current (source) branch and worktree+/// - `target` / `target_worktree_path`: destination branch and worktree (if it exists)+pub(crate) fn run_pre_switch_hooks(+ repo: &Repository,+ config: &UserConfig,+ target_branch: &str,+ yes: bool,+) -> anyhow::Result<()> {+ let current_wt = repo.current_worktree();+ let current_path = current_wt.path().to_path_buf();+ let resolved_target = repo+ .resolve_worktree_name(target_branch)+ .unwrap_or_else(|_| target_branch.to_string());+ let pre_ctx = CommandContext::new(repo, config, Some(&resolved_target), ¤t_path, yes);++ let pre_switch_approved = approve_hooks(&pre_ctx, &[HookType::PreSwitch])?;+ if pre_switch_approved {+ // Base vars: source (where the user currently is). Target vars and+ // Active overrides come from the destination worktree if it exists —+ // for creates the planned path is computed later during plan_switch,+ // so worktree_path stays at its default (the source = cwd).+ let base_branch = current_wt.branch().ok().flatten().unwrap_or_default();+ let dest_path = repo.worktree_for_branch(&resolved_target).ok().flatten();++ let mut vars = TemplateVars::new()+ .with_base(&base_branch, ¤t_path)+ .with_target(&resolved_target);+ if let Some(p) = dest_path.as_deref() {+ vars = vars.with_target_worktree_path(p).with_active_worktree(p);+ }+ let extra_vars = vars.as_extra_vars();++ execute_hook(+ &pre_ctx,+ HookType::PreSwitch,+ &extra_vars,+ FailureStrategy::FailFast,+ crate::output::pre_hook_display_path(pre_ctx.worktree_path),+ )?;+ }+ Ok(())+}++/// Hook types that apply after a switch operation.+///+/// Creates trigger pre-start + post-start + post-switch hooks;+/// existing worktrees trigger only post-switch.+fn switch_post_hook_types(is_create: bool) -> &'static [HookType] {+ if is_create {+ &[+ HookType::PreStart,+ HookType::PostStart,+ HookType::PostSwitch,+ ]+ } else {+ &[HookType::PostSwitch]+ }+}++/// Approve switch hooks upfront and show "Commands declined" if needed.+///+/// Returns `true` if hooks are approved to run.+/// Returns `false` if hooks should be skipped (`!verify` or user declined).+pub(crate) fn approve_switch_hooks(+ repo: &Repository,+ config: &UserConfig,+ plan: &SwitchPlan,+ yes: bool,+ verify: bool,+) -> anyhow::Result<bool> {+ if !verify {+ return Ok(false);+ }++ let ctx = CommandContext::new(repo, config, plan.branch(), plan.worktree_path(), yes);+ let on_decline = if plan.is_create() {+ "Commands declined, continuing worktree creation"+ } else {+ "Commands declined"+ };+ approve_or_skip(&ctx, switch_post_hook_types(plan.is_create()), on_decline)+}++/// Spawn post-switch (and post-start for creates) background hooks.+pub(crate) fn spawn_switch_background_hooks(+ repo: &Repository,+ config: &UserConfig,+ result: &SwitchResult,+ branch: Option<&str>,+ yes: bool,+ extra_vars: &[(&str, &str)],+ hooks_display_path: Option<&Path>,+) -> anyhow::Result<()> {+ let ctx = CommandContext::new(repo, config, branch, result.path(), yes);++ let mut announcer = HookAnnouncer::new(repo, config, false);+ announcer.register(&ctx, HookType::PostSwitch, extra_vars, hooks_display_path)?;+ if matches!(result, SwitchResult::Created { .. }) {+ announcer.register(&ctx, HookType::PostStart, extra_vars, hooks_display_path)?;+ }+ announcer.flush()+}++/// Handle the switch command.+pub fn run_switch(+ opts: SwitchOptions<'_>,+ config: &mut UserConfig,+ binary_name: &str,+) -> anyhow::Result<()> {+ let SwitchOptions {+ branch,+ create,+ base,+ execute,+ execute_args,+ yes,+ clobber,+ change_dir: change_dir_flag,+ verify,+ format,+ } = opts;++ let (repo, is_recovered) = current_or_recover().context("Failed to switch worktree")?;++ // Resolve change_dir: explicit CLI flags > project config > global config > default (true)+ // Now that we have the repo, we can resolve project-specific config.+ let change_dir = change_dir_flag.unwrap_or_else(|| {+ let project_id = repo.project_identifier().ok();+ config.resolved(project_id.as_deref()).switch.cd()+ });++ // Build switch suggestion context for enriching error hints with --execute/trailing args.+ // Without this, errors like "branch already exists" would suggest `wt switch <branch>`+ // instead of the full `wt switch <branch> --execute=<cmd> -- <args>`.+ let suggestion_ctx = execute.map(|exec| {+ let escaped = shell_escape::escape(exec.into());+ SwitchSuggestionCtx {+ extra_flags: vec![format!("--execute={escaped}")],+ trailing_args: execute_args.to_vec(),+ }+ });++ // Run pre-switch hooks before branch resolution or worktree creation.+ // {{ branch }} receives the raw user input (before resolution).+ // Skip when recovered — the source worktree is gone, nothing to run hooks against.+ if verify && !is_recovered {+ run_pre_switch_hooks(&repo, config, branch, yes)?;+ }++ // Offer to fix worktree-path for bare repos with hidden directory names (.git, .bare).+ offer_bare_repo_worktree_path_fix(&repo, config)?;++ // Validate and resolve the target branch.+ let plan = plan_switch(&repo, branch, create, base, clobber, config).map_err(|err| {+ match suggestion_ctx {+ Some(ref ctx) => match err.downcast::<GitError>() {+ Ok(git_err) => GitError::WithSwitchSuggestion {+ source: Box::new(git_err),+ ctx: ctx.clone(),+ }+ .into(),+ Err(err) => err,+ },+ None => err,+ }+ })?;++ // "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 hooks_approved = approve_switch_hooks(&repo, config, &plan, yes, verify)?;++ // Pre-flight: validate all templates before mutation (worktree creation).+ // Catches syntax errors and undefined variables early so a broken template+ // doesn't leave behind a half-created worktree that blocks re-running.+ validate_switch_templates(&repo, config, &plan, execute, execute_args, hooks_approved)?;++ // Capture source (base) worktree identity BEFORE the switch, so post-switch+ // hooks can reference where the user came from via {{ base }} / {{ base_worktree_path }}.+ let source_branch = repo+ .current_worktree()+ .branch()+ .ok()+ .flatten()+ .unwrap_or_default();+ let source_path = repo+ .current_worktree()+ .root()+ .ok()+ .map(|p| worktrunk::path::to_posix_path(&p.to_string_lossy()))+ .unwrap_or_default();++ // Execute the validated plan+ let (result, branch_info) = execute_switch(&repo, plan, config, yes, hooks_approved)?;++ // --format=json: write structured result to stdout. All behavior (hooks,+ // --execute, shell integration) proceeds normally — format only affects output.+ if format == SwitchFormat::Json {+ let json = SwitchJsonOutput::from_result(&result, &branch_info);+ let json = serde_json::to_string(&json).context("Failed to serialize to JSON")?;+ println!("{json}");+ }++ // Early exit for benchmarking time-to-first-output+ if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {+ return Ok(());+ }++ // Compute path mismatch lazily (deferred from plan_switch for existing worktrees).+ // Skip for detached HEAD worktrees (branch is None) — no branch to compute expected path from.+ let branch_info = match &result {+ SwitchResult::Existing { path } | SwitchResult::AlreadyAt(path) => {+ let expected_path = branch_info+ .branch+ .as_deref()+ .and_then(|b| path_mismatch(&repo, b, path, config));+ SwitchBranchInfo {+ expected_path,+ ..branch_info+ }+ }+ _ => branch_info,+ };++ // 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)+ //+ // When recovered from a deleted worktree, current_dir() and current_worktree().root()+ // both fail — fall back to repo_path() (the main worktree root).+ let fallback_path = repo.repo_path()?.to_path_buf();+ let cwd = std::env::current_dir().unwrap_or(fallback_path.clone());+ let source_root = repo.current_worktree().root().unwrap_or(fallback_path);+ let hooks_display_path =+ handle_switch_output(&result, &branch_info, change_dir, Some(&source_root), &cwd)?;++ // 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)+ // Skip when change_dir is false — user opted out of cd, so shell integration is irrelevant+ // Best-effort: don't fail switch if offer fails+ if change_dir && !is_shell_integration_active() {+ let skip_prompt = execute.is_some();+ let _ = prompt_shell_integration(config, binary_name, skip_prompt);+ }++ // Build template vars for base/target context (used by both hooks and+ // --execute). "base" is the source worktree the user switched from (all+ // switches), or the branch they branched from (creates). "target" matches+ // the bare vars (the destination) — kept symmetric with pre-switch.+ let template_vars =+ TemplateVars::for_post_switch(&result, &branch_info, &source_branch, &source_path);+ let extra_vars = template_vars.as_extra_vars();++ // 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+ // Batch hooks into a single message when both types are present+ if hooks_approved {+ spawn_switch_background_hooks(+ &repo,+ config,+ &result,+ branch_info.branch.as_deref(),+ yes,+ &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,+ branch_info.branch.as_deref(),+ result.path(),+ yes,+ );+ let template_vars = build_hook_context(&ctx, &extra_vars, None)?;+ 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")?;++ // 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"))+ .collect();+ let escaped_args: Vec<_> = expanded_args?+ .iter()+ .map(|arg| shell_escape::escape(arg.into()).into_owned())+ .collect();+ format!("{} {}", expanded_cmd, escaped_args.join(" "))+ };+ execute_user_command(&full_cmd, hooks_display_path.as_deref())?;+ }++ Ok(())+}++/// Validate all templates that will be expanded after worktree creation.+///+/// Catches syntax errors and undefined variable references *before* the+/// irreversible worktree creation, so a broken template doesn't leave behind+/// a worktree that blocks re-running the command.+///+/// This is a best-effort pre-flight check: it catches definite errors (syntax,+/// unknown variables) but cannot catch failures from conditional variables that+/// are absent at expansion time (e.g., `upstream` when no tracking is configured).+/// Such late failures propagate as normal errors — no panics.+///+/// ## Why only switch needs pre-flight validation+///+/// Switch is the only command where template failure after mutation creates a+/// **blocking half-state**: `wt switch -c <branch>` creates a worktree, then if+/// hook/--execute expansion fails, the worktree exists and the same command+/// can't be re-run (branch already exists). Other commands don't have this+/// problem:+///+/// - **Pre-operation hooks** (pre-merge, pre-remove, pre-commit) run before the+/// irreversible operation, so template errors abort cleanly.+/// - **Post-operation hooks** (post-merge, post-remove) run after the operation+/// completed successfully — template failure is a missed notification, not a+/// blocking state. The user can fix the template and run `wt hook` manually.+///+/// Validates:+/// - `--execute` command template (if present)+/// - `--execute` trailing arg templates (if present)+/// - Hook templates (post-create, post-start, post-switch) from user and project config+fn validate_switch_templates(+ repo: &Repository,+ config: &UserConfig,+ plan: &SwitchPlan,+ execute: Option<&str>,+ execute_args: &[String],+ hooks_approved: bool,+) -> anyhow::Result<()> {+ // Validate --execute template and trailing args+ if let Some(cmd) = execute {+ validate_template(+ cmd,+ ValidationScope::SwitchExecute,+ repo,+ "--execute command",+ )?;+ for arg in execute_args {+ validate_template(+ arg,+ ValidationScope::SwitchExecute,+ repo,+ "--execute argument",+ )?;+ }+ }++ // Validate hook templates only when hooks will actually run+ if !hooks_approved {+ return Ok(());+ }++ let project_config = repo.load_project_config()?;+ let user_hooks = config.hooks(repo.project_identifier().ok().as_deref());++ for &hook_type in switch_post_hook_types(plan.is_create()) {+ let (user_cfg, proj_cfg) = crate::commands::hooks::lookup_hook_configs(+ &user_hooks,+ project_config.as_ref(),+ hook_type,+ );+ for (source, cfg) in [("user", user_cfg), ("project", proj_cfg)] {+ if let Some(cfg) = cfg {+ for cmd in cfg.commands() {+ // Skip full validation for lazy templates ({{ vars.X }}) —+ // they're expanded at runtime after prior pipeline steps set+ // the vars. Syntax is still checked by expand_commands.+ if template_references_var(&cmd.template, "vars") {+ continue;+ }+ let name = match &cmd.name {+ Some(n) => format!("{source} {hook_type}:{n}"),+ None => format!("{source} {hook_type} hook"),+ };+ validate_template(+ &cmd.template,+ ValidationScope::Hook(hook_type),+ repo,+ &name,+ )?;+ }+ }+ }+ }++ Ok(())+}diff --git a/src/git/error.rs b/src/git/error.rsindex 81a062823..a0eff75ff 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -236,7 +236,7 @@ impl SwitchSuggestionCtx {/// separator when this context is applied.fn apply(&self, cmd: String) -> String {let mut result = cmd;- // Flags are pre-escaped at construction (handle_switch.rs uses shell_escape)+ // Flags are pre-escaped at construction (worktree/switch.rs uses shell_escape)for flag in &self.extra_flags {result.push(' ');result.push_str(flag);diff --git a/src/main.rs b/src/main.rsindex ef4f8ad5a..a70319c0f 100644--- a/src/main.rs+++ b/src/main.rs@@ -56,10 +56,9 @@ use commands::{handle_hints_get, handle_hook_show, handle_init, handle_list, handle_logs_list, handle_merge,handle_opencode_install, handle_opencode_uninstall, handle_promote, handle_rebase,handle_show_theme, handle_squash, handle_state_clear, handle_state_clear_all, handle_state_get,- handle_state_set, handle_state_show, handle_switch, handle_unconfigure_shell,- handle_vars_clear, handle_vars_get, handle_vars_list, handle_vars_set, resolve_worktree_arg,- run_hook, step_commit, step_copy_ignored, step_diff, step_eval, step_for_each, step_prune,- step_relocate,+ handle_state_set, handle_state_show, handle_unconfigure_shell, handle_vars_clear,+ handle_vars_get, handle_vars_list, handle_vars_set, resolve_worktree_arg, run_hook, run_switch,+ step_commit, step_copy_ignored, step_diff, step_eval, step_for_each, step_prune, step_relocate,};use output::handle_remove_output;use worktrunk::git::BranchDeletionMode;@@ -684,7 +683,7 @@ fn handle_switch_command(args: SwitchArgs, yes: bool) -> anyhow::Result<()> {}};- handle_switch(+ run_switch(SwitchOptions {branch: &branch,create: args.create,diff --git a/tests/integration_tests/output_system_guard.rs b/tests/integration_tests/output_system_guard.rsindex 5aae3f595..cc06ca96c 100644--- a/tests/integration_tests/output_system_guard.rs+++ b/tests/integration_tests/output_system_guard.rs@@ -54,7 +54,7 @@ const STDOUT_ALLOWED_PATHS: &[&str] = &[// --no-cd flag: branch name output for scripting"picker/mod.rs",// JSON output for wt switch --format=json- "handle_switch.rs",+ "worktree/switch.rs",// JSON output for wt config show --format=json"config/show.rs",// Migrated TOML output for wt config update --print (pipeable)