Skip to content

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

refactor(switch): unify the picker and argument-path switch pipelines (#2858)

Maximilian Roose4dd59173195
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cf5ab40e1..450477728 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,8 @@
### Fixed
+- **Picker prompts for approval before running project `pre-switch` hooks**: Selecting a worktree in the interactive picker (`wt switch` with no argument) ran a project-defined `pre-switch` hook from `.config/wt.toml` without the approval prompt that gates every other hook — unapproved code from a freshly cloned repo executing silently. The picker now routes `pre-switch` hooks through the same approval gate as `wt switch <branch>` and as its own `post-switch`/`pre-start`/`post-start` hooks. ([#2858](https://github.com/max-sixty/worktrunk/pull/2858))
+
- **Interactive picker switches with `cd = false`**: With `[switch] cd = false` (or `wt switch --no-cd`), opening the picker (`wt switch` with no branch argument) and selecting a worktree printed the branch name and exited — no switch, no hooks, and `Alt-c` created nothing. The picker now runs the same switch pipeline as `wt switch <branch>`, suppressing only the cd directive: `pre-switch`/`post-switch` hooks fire and `Alt-c` creates the worktree. `--format=json` works in the picker too, and replaces the old print-only output for scripting — it both switches and prints a structured result (`action`, `branch`, `path`) to stdout. ([#2837](https://github.com/max-sixty/worktrunk/issues/2837))
- **`wt remove` reaps a wedged fsmonitor daemon**: When `core.fsmonitor=true`, git runs a per-worktree `git fsmonitor--daemon`. Removal already sent `git fsmonitor--daemon stop`, but `stop` is an IPC request to the daemon itself, so a daemon that had stopped answering its socket ignored it and then leaked forever once its worktree was gone (dozens could accumulate, and one wedged daemon hangs `wt list`). Removal now resolves the daemon's PID from its IPC socket and force-terminates it (SIGTERM, brief wait, SIGKILL) when `stop` doesn't take. The signal only ever targets the daemon whose socket resolves to the worktree being removed.
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index 56ae45138..932b83732 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -115,15 +115,9 @@ use super::hooks::HookAnnouncer;
use super::list::collect;
use super::list::progressive::RenderTarget;
use super::repository_ext::{RemoveTarget, RepositoryCliExt};
-use super::template_vars::TemplateVars;
-use super::worktree::{
- RemoveResult, SwitchBranchInfo, SwitchResult, approve_switch_hooks, emit_switch_json,
- execute_switch, offer_bare_repo_worktree_path_fix, path_mismatch, plan_switch,
- run_pre_switch_hooks, spawn_switch_background_hooks, switch_hook_project_config,
- validate_switch_templates,
-};
+use super::worktree::{RemoveResult, SwitchPipeline};
use crate::cli::SwitchFormat;
-use crate::output::{handle_remove_output, handle_switch_output};
+use crate::output::handle_remove_output;
use worktrunk::git::{BranchDeletionMode, delete_branch_if_safe};
use items::{PreviewCache, WorktreeSkimItem};
@@ -802,101 +796,42 @@ pub fn handle_picker(
let query = out.query.trim().to_string();
let identifier = resolve_identifier(&action, query, selected_name)?;
- // Load config — reuse recovered repo if we recovered earlier
+ // Load config — reuse the recovered repo if we recovered earlier.
let repo = if is_recovered {
repo.clone()
} else {
Repository::current().context("Failed to switch worktree")?
};
- // Clone user out so `offer_bare_repo_worktree_path_fix` can mutate
- // locally. Project config is loaded on demand by downstream
- // `run_pre_switch_hooks` / `plan_switch`.
+ // Clone user config out — `SwitchPipeline` takes `&mut UserConfig` (the
+ // bare-repo path-fix offer and the shell-integration offer record onto
+ // it). Project config is loaded on demand inside the pipeline.
let mut config = repo.user_config().clone();
- offer_bare_repo_worktree_path_fix(&repo, &mut config)?;
- // 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 !is_recovered {
- run_pre_switch_hooks(&repo, &config, &identifier, true)?;
- }
-
- // Switch to existing worktree or create new one
- let plan = plan_switch(&repo, &identifier, should_create, None, false, &config)?;
- // Resolve the config the post-switch hooks will run against (the
- // new/destination worktree's, or for `--create` the base ref's) so the
- // approval prompt lists the exact commands `execute_switch` will run.
- let hook_project_config = switch_hook_project_config(&repo, &plan)?;
- let (hooks_approved, hook_plan) = approve_switch_hooks(
- &repo,
- &config,
- &plan,
- false,
- true,
- hook_project_config.as_ref(),
- )?;
-
- // Pre-flight: validate all templates before mutation (worktree creation).
- // Without this, picker-create would have the half-state risk that
- // `wt switch --create` already guards against — a broken template would
- // fail after `git worktree add`, leaving the worktree behind.
- validate_switch_templates(
- &repo,
- &config,
- &plan,
- None,
- &[],
- hooks_approved,
- hook_project_config.as_ref(),
- )?;
-
- let (result, branch_info) =
- execute_switch(&repo, plan, &config, false, hooks_approved, &hook_plan)?;
-
- // --format=json: structured result to stdout, identical to the
- // argument path. All switch behavior above proceeds normally.
- emit_switch_json(format, &result, &branch_info)?;
-
- // Compute path mismatch lazily (deferred from plan_switch for existing worktrees).
- // Skip for detached HEAD worktrees (branch is None).
- 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; emit cd directive if shell integration is active
- // When recovered from a deleted worktree, fall back to repo_path().
- 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)?;
-
- // Spawn background hooks after success message. Picker doesn't capture
- // pre-switch source identity, so existing-switch `base` vars stay
- // unset; result-derived `base` (creates) and `target` flow as usual.
- if hooks_approved {
- let template_vars = TemplateVars::for_post_switch(&result, &branch_info, "", "");
- let extra_vars = template_vars.as_extra_vars();
- spawn_switch_background_hooks(
- &config,
- &result,
- branch_info.branch.as_deref(),
- false,
- &extra_vars,
- hooks_display_path.as_deref(),
- &hook_plan,
- )?;
+ // Run the switch — the same `SwitchPipeline` as `wt switch <branch>`,
+ // so hooks, approval, and output cannot drift from the argument path.
+ // The picker has no `--execute`, offers no shell integration, and does
+ // not capture pre-switch source identity (`capture_source: false` — an
+ // existing switch's `{{ base }}` / `{{ base_worktree_path }}` stay
+ // unset; result-derived `base` for creates and `target` still flow).
+ SwitchPipeline {
+ repo: &repo,
+ config: &mut config,
+ identifier: &identifier,
+ create: should_create,
+ base: None,
+ clobber: false,
+ verify: true,
+ yes: false,
+ change_dir,
+ format,
+ is_recovered,
+ suggestion_ctx: None,
+ capture_source: false,
+ execute: None,
+ execute_args: &[],
+ shell_integration_binary: None,
}
+ .run()?;
}
Ok(())
diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rs
index 0f1c0cd1f..55c4caf09 100644
--- a/src/commands/worktree/mod.rs
+++ b/src/commands/worktree/mod.rs
@@ -91,18 +91,11 @@ mod types;
// Re-export public types and functions
pub 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, path_mismatch, resolve_worktree_arg,
worktree_display_name,
};
-pub use switch::{SwitchOptions, run_switch};
#[cfg(unix)]
-pub(crate) use switch::{
- approve_switch_hooks, emit_switch_json, run_pre_switch_hooks, spawn_switch_background_hooks,
- switch_hook_project_config, validate_switch_templates,
-};
-#[cfg(unix)]
-pub use switch::{execute_switch, plan_switch};
+pub(crate) use switch::SwitchPipeline;
+pub use switch::{SwitchOptions, run_switch};
pub use types::{MergeOperations, OperationMode, RemoveResult, SwitchBranchInfo, SwitchResult};
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 934b99cf1..c0d4715c6 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -1,7 +1,8 @@
//! Worktree switch operations.
//!
-//! Planning and executing worktree switches, plus the `wt switch` entry point
-//! that wires hooks, approvals, output, and shell integration around them.
+//! Planning and executing worktree switches, plus [`SwitchPipeline`] — the
+//! full switch sequence (bare-repo fix-up, hooks, approval, execution, output)
+//! shared by the `wt switch` argument path and the interactive picker.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
@@ -784,7 +785,7 @@ fn setup_fork_branch(
///
/// Warnings (remote branch shadow, --base without --create, invalid default branch)
/// are printed during planning since they're informational, not blocking.
-pub fn plan_switch(
+fn plan_switch(
repo: &Repository,
branch: &str,
create: bool,
@@ -871,7 +872,7 @@ pub fn plan_switch(
/// `SwitchBranchInfo` has `expected_path: None` — callers fill it in after
/// first output to avoid computing path mismatch on the hot path.
/// For `SwitchPlan::Create`, creates the worktree and runs hooks.
-pub fn execute_switch(
+fn execute_switch(
repo: &Repository,
plan: SwitchPlan,
config: &UserConfig,
@@ -1274,10 +1275,8 @@ impl SwitchJsonOutput {
/// Emit the structured `--format=json` result to stdout when requested.
///
-/// Shared by the argument path and the interactive picker so `wt switch
-/// --format=json` produces identical output regardless of how the branch
-/// was chosen. A no-op for `SwitchFormat::Text`.
-pub(crate) fn emit_switch_json(
+/// A no-op for `SwitchFormat::Text`.
+fn emit_switch_json(
format: SwitchFormat,
result: &SwitchResult,
branch_info: &SwitchBranchInfo,
@@ -1317,7 +1316,7 @@ pub struct SwitchOptions<'a> {
/// 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(
+fn run_pre_switch_hooks(
repo: &Repository,
config: &UserConfig,
target_branch: &str,
@@ -1434,7 +1433,7 @@ fn base_ref_for_create(
/// May `git fetch` a `pr:`/`mr:` fork head ref — `wt switch pr:`/`mr:` is the
/// user explicitly invoking network work, so fetching at the approval gate is
/// in keeping; `execute_switch` re-fetches (idempotent).
-pub(crate) fn switch_hook_project_config(
+fn switch_hook_project_config(
repo: &Repository,
plan: &SwitchPlan,
) -> anyhow::Result<Option<ProjectConfig>> {
@@ -1481,7 +1480,7 @@ fn hook_repo_for_worktree(worktree_path: &Path) -> anyhow::Result<Repository> {
/// Returns `(hooks_approved, plan)`. `hooks_approved` is `false` and the plan
/// empty when `!verify` or the user declined; the covered switch hooks
/// (`pre-start` / `post-start` / `post-switch`) execute only from `plan`.
-pub(crate) fn approve_switch_hooks(
+fn approve_switch_hooks(
repo: &Repository,
config: &UserConfig,
plan: &SwitchPlan,
@@ -1521,7 +1520,7 @@ pub(crate) fn approve_switch_hooks(
}
/// Spawn post-switch (and post-start for creates) background hooks.
-pub(crate) fn spawn_switch_background_hooks(
+fn spawn_switch_background_hooks(
config: &UserConfig,
result: &SwitchResult,
branch: Option<&str>,
@@ -1587,6 +1586,313 @@ fn capture_switch_source(repo: &Repository, is_recovered: bool) -> (String, Stri
(source_branch, source_path)
}
+/// The full switch sequence shared by the argument path ([`run_switch`]) and
+/// the interactive picker.
+///
+/// Each caller only resolves a branch identifier and loads config; everything
+/// else runs in [`SwitchPipeline::run`] — the bare-repo path-fix offer,
+/// pre-switch hooks, source-identity capture, `plan_switch` →
+/// `approve_switch_hooks` → `validate_switch_templates` → `execute_switch` →
+/// output → background hooks → `--execute`. One sequence, so the two entry
+/// points cannot drift. In particular the single `verify` / `yes` pair gates
+/// every hook, so the picker and the argument path cannot diverge on hook
+/// approval — the picker once auto-approved `pre-switch` hooks because it kept
+/// its own copy of that call.
+///
+/// The picker-vs-argument differences are field values, not separate code: the
+/// picker passes `verify: true`, `yes: false`, `capture_source: false`,
+/// `suggestion_ctx: None`, `execute: None`, and `shell_integration_binary:
+/// None`.
+pub(crate) struct SwitchPipeline<'a> {
+ pub repo: &'a Repository,
+ /// Mutable because the bare-repo path-fix offer
+ /// (`offer_bare_repo_worktree_path_fix`) and the shell-integration offer
+ /// (`prompt_shell_integration`) record onto it; every other step reborrows
+ /// it shared.
+ pub config: &'a mut UserConfig,
+ /// Branch identifier — a CLI argument or the picker's selection. Symbolic
+ /// forms (`-`, `@`, `pr:`/`mr:`) are resolved downstream by `plan_switch`.
+ pub identifier: &'a str,
+ pub create: bool,
+ pub base: Option<&'a str>,
+ pub clobber: bool,
+ pub verify: bool,
+ /// `--yes`: skip approval prompts and force past clobber checks.
+ pub yes: bool,
+ pub change_dir: bool,
+ pub format: SwitchFormat,
+ /// True when `current_or_recover` recovered from a deleted CWD. Suppresses
+ /// pre-switch hooks (no source worktree to run them against) and source
+ /// capture.
+ pub is_recovered: bool,
+ /// Error-enrichment context for a failed `plan_switch`, so the hint
+ /// suggests the full `wt switch … --execute=… -- …`. `None` for the
+ /// picker, which has no `--execute`.
+ pub suggestion_ctx: Option<SwitchSuggestionCtx>,
+ /// Whether to capture the source worktree's branch/root before the switch,
+ /// for post-switch `{{ base }}` / `{{ base_worktree_path }}`. The argument
+ /// path captures; the picker does not — it does not track where the user
+ /// came from, so an existing switch's base vars stay unset.
+ pub capture_source: bool,
+ /// `--execute` command and its trailing args. `None` / empty for the picker.
+ pub execute: Option<&'a str>,
+ pub execute_args: &'a [String],
+ /// Binary name for the shell-integration offer. `Some` only on the argument
+ /// path; the picker does not offer shell integration.
+ pub shell_integration_binary: Option<&'a str>,
+}
+
+impl SwitchPipeline<'_> {
+ /// Plan, approve, execute, and report the switch, then spawn its
+ /// background hooks and run any `--execute` command.
+ pub(crate) fn run(self) -> anyhow::Result<()> {
+ let Self {
+ repo,
+ config,
+ identifier,
+ create,
+ base,
+ clobber,
+ verify,
+ yes,
+ change_dir,
+ format,
+ is_recovered,
+ suggestion_ctx,
+ capture_source,
+ execute,
+ execute_args,
+ shell_integration_binary,
+ } = self;
+
+ // Offer to fix worktree-path for bare repos with hidden directory names
+ // (.git, .bare) before anything reads worktree-path config.
+ offer_bare_repo_worktree_path_fix(repo, config)?;
+
+ // 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. `yes` is the single switch-wide flag, so the picker (no
+ // `--yes`) and the argument path gate `pre-switch` hooks identically.
+ if verify && !is_recovered {
+ run_pre_switch_hooks(repo, config, identifier, yes)?;
+ }
+
+ // Capture source (base) worktree identity BEFORE the switch, for
+ // post-switch {{ base }} / {{ base_worktree_path }}. Done here — after
+ // pre-switch hooks, before plan / approve / validate, none of which
+ // move the current worktree. The picker passes `capture_source: false`;
+ // it does not track where the user came from.
+ let (source_branch, source_path) = if capture_source {
+ capture_switch_source(repo, is_recovered)
+ } else {
+ (String::new(), String::new())
+ };
+
+ // Validate and resolve the target branch.
+ let plan = plan_switch(repo, identifier, 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,
+ }
+ })?;
+
+ // Resolve the `.config/wt.toml` the post-switch hooks will run against —
+ // the new/destination worktree's (for `--create`, the base ref's, read
+ // via `git show` since the worktree doesn't exist yet). Computed once so
+ // the approval prompt and the template pre-flight below agree with what
+ // `execute_switch` / `spawn_switch_background_hooks` resolve at run time.
+ // (May `git fetch` a `pr:`/`mr:` fork head — explicit network work.)
+ //
+ // Skip entirely when `--no-hooks` / `--no-verify` is in effect: with
+ // hooks disabled, the result is never used, and resolving it could fetch
+ // from a PR ref or read a primary `.config/wt.toml` the user asked us
+ // not to touch.
+ let hook_project_config = if verify {
+ switch_hook_project_config(repo, &plan)?
+ } else {
+ None
+ };
+
+ // "Approve at the Gate": collect and approve hooks upfront. Approval
+ // happens once at the command entry point. If the user declines, skip
+ // hooks but continue with the worktree operation.
+ let (hooks_approved, hook_plan) = approve_switch_hooks(
+ repo,
+ config,
+ &plan,
+ yes,
+ verify,
+ hook_project_config.as_ref(),
+ )?;
+
+ // 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,
+ hook_project_config.as_ref(),
+ )?;
+
+ // Execute the validated plan.
+ let (result, branch_info) =
+ execute_switch(repo, plan, config, yes, hooks_approved, &hook_plan)?;
+
+ // --format=json: write structured result to stdout. All behavior
+ // (hooks, --execute, shell integration) proceeds normally — format only
+ // affects output.
+ emit_switch_json(format, &result, &branch_info)?;
+
+ // 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 detached HEAD worktrees (branch is None) — no branch
+ // to compute the 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 the
+ // worktree operation). Returns the path to display in hooks when the
+ // user's shell won't be in the worktree, and shows the worktree-path
+ // hint on first --create (before the shell integration warning).
+ //
+ // When the user's CWD has been deleted, `std::env::current_dir()`
+ // fails — fall back to `repo_path()` (the main worktree root).
+ // `current_worktree().root()` resolves against the Repository's
+ // discovery path, which is alive even after recovery, but we keep the
+ // same fallback for any pathological case where rev-parse fails.
+ 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
+ // the prompt/hint when shell integration isn't working). With
+ // --execute, show hints only — don't interrupt with a prompt. Skip when
+ // change_dir is false (the user opted out of cd, so shell integration
+ // is irrelevant) and on the picker path (no `binary_name`).
+ // Best-effort: don't fail the switch if the offer fails.
+ if let Some(binary_name) = shell_integration_binary
+ && change_dir
+ && !is_shell_integration_active()
+ {
+ let skip_prompt = execute.is_some();
+ let _ = prompt_shell_integration(repo, 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 the success message.
+ // - post-switch: runs on ALL switches (shows "@ path" when the shell
+ // won't be there)
+ // - post-start: runs only when creating a NEW worktree
+ if hooks_approved {
+ spawn_switch_background_hooks(
+ config,
+ &result,
+ branch_info.branch.as_deref(),
+ yes,
+ &extra_vars,
+ hooks_display_path.as_deref(),
+ &hook_plan,
+ )?;
+ }
+
+ // Execute the 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();
+
+ // The `--execute` payload is parsed by the active directive shell:
+ // the PowerShell wrapper `Invoke-Expression`s the EXEC directive
+ // file, every other wrapper (and the direct `sh -c` non-integration
+ // path) is POSIX. Escape interpolated values for whichever it is —
+ // the one place the escaping is shell-aware (hooks/aliases stay
+ // POSIX). See `worktrunk::shell_exec::directive_shell_escape_mode`.
+ let escape_mode = directive_shell_escape_mode();
+
+ // Expand template variables in command, escaped for the directive shell.
+ let expanded_cmd = expand_template(cmd, &vars, escape_mode, repo, "--execute command")?;
+
+ // Append any trailing args (after --) to the execute command.
+ // Each arg is template-expanded literally, then escaped for the
+ // directive shell so the wrapper parses it as one literal argument.
+ 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,
+ ShellEscapeMode::Literal,
+ repo,
+ "--execute argument",
+ )
+ })
+ .collect();
+ let escaped_args: Vec<_> = expanded_args?
+ .iter()
+ .map(|arg| shell_escape_for(escape_mode, arg))
+ .collect();
+ format!("{} {}", expanded_cmd, escaped_args.join(" "))
+ };
+ execute_user_command(&full_cmd, hooks_display_path.as_deref())?;
+ }
+
+ Ok(())
+ }
+}
+
/// Handle the switch command.
pub fn run_switch(
opts: SwitchOptions<'_>,
@@ -1626,211 +1932,25 @@ pub fn run_switch(
}
});
- // 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,
- }
- })?;
-
- // Resolve the `.config/wt.toml` the post-switch hooks will run against —
- // the new/destination worktree's (for `--create`, the base ref's, read via
- // `git show` since the worktree doesn't exist yet). Computed once so the
- // approval prompt and the template pre-flight below agree with what
- // `execute_switch` / `spawn_switch_background_hooks` resolve at run time.
- // (May `git fetch` a `pr:`/`mr:` fork head — explicit network work.)
- //
- // Skip entirely when `--no-hooks` / `--no-verify` is in effect: with hooks
- // disabled, the result is never used, and resolving it could fetch from a
- // PR ref or read a primary `.config/wt.toml` the user asked us not to
- // touch.
- let hook_project_config = if verify {
- switch_hook_project_config(&repo, &plan)?
- } else {
- None
- };
-
- // "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, hook_plan) = approve_switch_hooks(
- &repo,
+ SwitchPipeline {
+ repo: &repo,
config,
- &plan,
- yes,
+ identifier: branch,
+ create,
+ base,
+ clobber,
verify,
- hook_project_config.as_ref(),
- )?;
-
- // 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,
+ yes,
+ change_dir,
+ format,
+ is_recovered,
+ suggestion_ctx,
+ capture_source: true,
execute,
execute_args,
- hooks_approved,
- hook_project_config.as_ref(),
- )?;
-
- // 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, source_path) = capture_switch_source(&repo, is_recovered);
-
- // Execute the validated plan
- let (result, branch_info) =
- execute_switch(&repo, plan, config, yes, hooks_approved, &hook_plan)?;
-
- // --format=json: write structured result to stdout. All behavior (hooks,
- // --execute, shell integration) proceeds normally — format only affects output.
- emit_switch_json(format, &result, &branch_info)?;
-
- // 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 the user's CWD has been deleted, `std::env::current_dir()` fails —
- // fall back to `repo_path()` (the main worktree root). `current_worktree()
- // .root()` resolves against the Repository's discovery path, which is alive
- // even after recovery, but we keep the same fallback for any pathological
- // case where rev-parse fails.
- 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(&repo, config, binary_name, skip_prompt);
+ shell_integration_binary: Some(binary_name),
}
-
- // 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(
- config,
- &result,
- branch_info.branch.as_deref(),
- yes,
- &extra_vars,
- hooks_display_path.as_deref(),
- &hook_plan,
- )?;
- }
-
- // 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();
-
- // The `--execute` payload is parsed by the active directive shell: the
- // PowerShell wrapper `Invoke-Expression`s the EXEC directive file, every
- // other wrapper (and the direct `sh -c` non-integration path) is POSIX.
- // Escape interpolated values for whichever it is — the one place the
- // escaping is shell-aware (hooks/aliases stay POSIX). See
- // `worktrunk::shell_exec::directive_shell_escape_mode`.
- let escape_mode = directive_shell_escape_mode();
-
- // Expand template variables in command, escaped for the directive shell.
- let expanded_cmd = expand_template(cmd, &vars, escape_mode, &repo, "--execute command")?;
-
- // Append any trailing args (after --) to the execute command.
- // Each arg is template-expanded literally, then escaped for the
- // directive shell so the wrapper parses it as one literal argument.
- 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,
- ShellEscapeMode::Literal,
- &repo,
- "--execute argument",
- )
- })
- .collect();
- let escaped_args: Vec<_> = expanded_args?
- .iter()
- .map(|arg| shell_escape_for(escape_mode, arg))
- .collect();
- format!("{} {}", expanded_cmd, escaped_args.join(" "))
- };
- execute_user_command(&full_cmd, hooks_display_path.as_deref())?;
- }
-
- Ok(())
+ .run()
}
/// Validate all templates that will be expanded after worktree creation.
@@ -1867,7 +1987,7 @@ pub fn run_switch(
/// - `--execute` command template (if present)
/// - `--execute` trailing arg templates (if present)
/// - Hook templates (pre-start, post-start, post-switch) from user and project config
-pub(crate) fn validate_switch_templates(
+fn validate_switch_templates(
repo: &Repository,
config: &UserConfig,
plan: &SwitchPlan,
diff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rs
index 68b8210e9..f18446876 100644
--- a/tests/integration_tests/switch_picker.rs
+++ b/tests/integration_tests/switch_picker.rs
@@ -1235,3 +1235,54 @@ fn test_switch_picker_no_cd_switches_without_cd_directive(mut repo: TestRepo) {
cd_content
);
}
+
+/// A project `pre-switch` hook must pass through the approval gate when the
+/// picker switches — the picker has no `--yes`, so an unapproved project
+/// command is shown for approval, never auto-run.
+///
+/// Regression: the picker previously passed `yes = true` to
+/// `run_pre_switch_hooks`, silently executing project `pre-switch` commands
+/// without a prompt — inconsistent with every other hook the picker gates, and
+/// a hole in "Project Commands Run Only After Approval". Here the hook is
+/// declined at the prompt; it must not run, and the switch must still succeed.
+#[rstest]
+fn test_switch_picker_pre_switch_hook_requires_approval(mut repo: TestRepo) {
+ repo.remove_fixture_worktrees();
+ repo.run_git(&["remote", "remove", "origin"]);
+ repo.add_worktree("target-branch");
+
+ // Project `pre-switch` hook (in `.config/wt.toml`, so it routes through the
+ // approval gate) that touches a marker outside the worktree if it runs.
+ let marker_dir = tempfile::tempdir().unwrap();
+ let marker = marker_dir.path().join("pre-switch-ran");
+ repo.write_project_config(&format!(
+ "pre-switch = {:?}\n",
+ format!("touch {}", marker.display())
+ ));
+
+ let env_vars = repo.test_env_vars();
+ // Select target-branch, press Enter, then decline the approval prompt.
+ let result = exec_in_pty_with_input_expectations(
+ wt_bin().to_str().unwrap(),
+ &["switch"],
+ repo.root_path(),
+ &env_vars,
+ &[
+ // Preview-pane gate: see test_switch_picker_emits_cd_directive_by_default.
+ ("target", Some("target-branch has no uncommitted changes")),
+ ("\r", Some("needs approval")), // Enter; wait for the approval prompt
+ ("n\n", None), // decline
+ ],
+ );
+
+ let screen = result.screen();
+ assert_eq!(
+ result.exit_code, 0,
+ "switch should still succeed after declining the pre-switch hook.\nScreen:\n{screen}"
+ );
+ assert!(
+ screen.contains("needs approval"),
+ "picker must prompt before running a project pre-switch hook.\nScreen:\n{screen}"
+ );
+ assert!(!marker.exists(), "a declined pre-switch hook must not run");
+}