Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(commands): unify hook template-variable assembly into `TemplateVars` (#2470)
Maximilian Roosa6be4b775a0e
diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rsindex 0a3aa5674..45d15234d 100644--- a/src/commands/handle_switch.rs+++ b/src/commands/handle_switch.rs@@ -18,6 +18,7 @@ use super::command_approval::approve_hooks;use super::command_executor::FailureStrategy;use super::command_executor::{CommandContext, build_hook_context};use super::hooks::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,@@ -118,39 +119,20 @@ pub(crate) fn run_pre_switch_hooks(let pre_switch_approved = approve_hooks(&pre_ctx, &[HookType::PreSwitch])?;if pre_switch_approved {- // Base vars: source (where the user currently is)+ // 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 base_path_str = worktrunk::path::to_posix_path(¤t_path.to_string_lossy());-- let mut extra_vars: Vec<(&str, &str)> = vec![- ("base", &base_branch),- ("base_worktree_path", &base_path_str),- ];-- // Target vars and Active overrides: destination worktree.- // For existing worktrees: override bare vars (worktree_path, worktree_name,- // worktree) to point to the destination (Active), not the source.let dest_path = repo.worktree_for_branch(&resolved_target).ok().flatten();- let dest_name = dest_path- .as_ref()- .and_then(|p| p.file_name())- .and_then(|n| n.to_str())- .map(|s| s.to_string());- let dest_path_str = dest_path.map(|p| worktrunk::path::to_posix_path(&p.to_string_lossy()));-- extra_vars.push(("target", &resolved_target));- if let Some(ref p) = dest_path_str {- // Existing destination: override bare vars to Active (destination)- extra_vars.push(("target_worktree_path", p));- extra_vars.push(("worktree_path", p));- extra_vars.push(("worktree", p)); // deprecated alias- if let Some(ref name) = dest_name {- extra_vars.push(("worktree_name", name));- }++ 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);}- // For creates (dest_path_str is None): worktree_path keeps its default- // (the source worktree = cwd). The planned destination path is computed- // later during plan_switch, after pre-switch hooks complete.+ let extra_vars = vars.as_extra_vars();execute_hook(&pre_ctx,@@ -212,43 +194,6 @@ pub(crate) fn approve_switch_hooks(Ok(approved)}-/// Compute extra template variables from a switch result.-///-/// Returns base branch context (`base`, `base_worktree_path`) and, for-/// `pr:N` / `mr:N` creations, `pr_number` and `pr_url` for hooks and template-/// expansion. The caller owns the `pr_number` string buffer because the-/// returned slice borrows from it.-pub(crate) fn switch_extra_vars<'a>(- result: &'a SwitchResult,- pr_number_buf: &'a mut String,-) -> Vec<(&'a str, &'a str)> {- match result {- SwitchResult::Created {- base_branch,- base_worktree_path,- pr_number,- pr_url,- ..- } => {- if let Some(n) = pr_number {- *pr_number_buf = n.to_string();- }- [- base_branch.as_deref().map(|b| ("base", b)),- base_worktree_path- .as_deref()- .map(|p| ("base_worktree_path", p)),- pr_number.map(|_| ("pr_number", pr_number_buf.as_str())),- pr_url.as_deref().map(|u| ("pr_url", u)),- ]- .into_iter()- .flatten()- .collect()- }- SwitchResult::Existing { .. } | SwitchResult::AlreadyAt(_) => Vec::new(),- }-}-/// Spawn post-switch (and post-start for creates) background hooks.pub(crate) fn spawn_switch_background_hooks(repo: &Repository,@@ -432,31 +377,13 @@ pub fn handle_switch(let _ = prompt_shell_integration(config, binary_name, skip_prompt);}- // Build extra 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) — documented as- // "target = bare vars" for switch/create and kept symmetric with pre-switch.- let target_path_str = worktrunk::path::to_posix_path(&result.path().to_string_lossy());-- let mut pr_number_buf = String::new();- let mut extra_vars = switch_extra_vars(&result, &mut pr_number_buf);- if let Some(target_branch) = branch_info.branch.as_deref() {- extra_vars.push(("target", target_branch));- }- extra_vars.push(("target_worktree_path", &target_path_str));- // For existing switches, add source worktree as base- if matches!(- result,- SwitchResult::Existing { .. } | SwitchResult::AlreadyAt(_)- ) {- if !source_branch.is_empty() {- extra_vars.push(("base", &source_branch));- }- if !source_path.is_empty() {- extra_vars.push(("base_worktree_path", &source_path));- }- }+ // 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)diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 2a5970f44..72753d2ca 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -14,6 +14,7 @@ use super::project_config::{ApprovableCommand, collect_commands_for_hooks};use super::repository_ext::{RepositoryCliExt, check_not_default_branch, compute_integration_reason, is_primary_worktree,};+use super::template_vars::TemplateVars;use super::worktree::{MergeOperations, PushKind, RemoveResult, handle_no_ff_merge, handle_push, path_mismatch,};@@ -220,24 +221,18 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {false // Already rebased, no rebase occurred};- // Target worktree path for template variables (pre-merge and post-merge hooks).- // Computed once here so both hook sites can reference it.- let target_wt_path_str = target_worktree_path- .as_deref()- .map(|p| worktrunk::path::to_posix_path(&p.to_string_lossy()));-// Run pre-merge checks unless --no-hooks was specified// Do this after commit/squash/rebase to validate the final state that will be pushedif verify {let ctx = env.context(yes);- let mut extra: Vec<(&str, &str)> = vec![("target", target_branch.as_str())];- if let Some(ref p) = target_wt_path_str {- extra.push(("target_worktree_path", p));+ let mut vars = TemplateVars::new().with_target(&target_branch);+ if let Some(p) = target_worktree_path.as_deref() {+ vars = vars.with_target_worktree_path(p);}execute_hook(&ctx,HookType::PreMerge,- &extra,+ &vars.as_extra_vars(),FailureStrategy::FailFast,&[],crate::output::pre_hook_display_path(ctx.worktree_path),@@ -259,30 +254,23 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {}// Destination: prefer the target branch's worktree; fall back to home path.- let destination_path = match target_worktree_path {- Some(path) => path,+ let destination_path = match target_worktree_path.as_deref() {+ Some(path) => path.to_path_buf(),None => repo.home_path()?,};- // Capture feature worktree identity BEFORE removal for post-merge template vars.- // After removal the feature worktree is gone, but post-merge hooks need to- // reference it as the Active identity (branch, worktree_path, commit).- let feature_path_str = worktrunk::path::to_posix_path(&env.worktree_path.to_string_lossy());- let feature_name = env- .worktree_path- .file_name()- .and_then(|n| n.to_str())- .unwrap_or("unknown")- .to_string();+ // Capture feature worktree identity BEFORE removal as Active overrides for+ // post-merge hooks. After removal the feature worktree is gone, but+ // post-merge hooks need to reference its branch, path, and commit.+ let mut feature_vars = TemplateVars::new().with_active_worktree(&env.worktree_path);let feature_commit = repo.current_worktree().run_command(&["rev-parse", "HEAD"]).ok().map(|s| s.trim().to_string());- let feature_short_commit = feature_commit- .as_ref()- .filter(|c| c.len() >= 7)- .map(|c| c[..7].to_string());+ if let Some(commit) = feature_commit.as_deref() {+ feature_vars = feature_vars.with_active_commit(commit);+ }// One announcer for the whole command's background hooks: post-remove +// post-switch (from worktree removal) and post-merge share a single@@ -354,23 +342,16 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {crate::output::pre_hook_display_path(&destination_path)};- // Override bare vars to Active (feature branch identity)- let mut extra: Vec<(&str, &str)> = vec![("target", target_branch.as_str())];- if let Some(ref p) = target_wt_path_str {- extra.push(("target_worktree_path", p));- }- // Active = feature: override worktree_path and friends- extra.push(("worktree_path", &feature_path_str));- extra.push(("worktree", &feature_path_str)); // deprecated alias- extra.push(("worktree_name", &feature_name));- if let Some(ref c) = feature_commit {- extra.push(("commit", c));- }- if let Some(ref sc) = feature_short_commit {- extra.push(("short_commit", sc));+ let mut vars = feature_vars.with_target(&target_branch);+ if let Some(p) = target_worktree_path.as_deref() {+ vars = vars.with_target_worktree_path(p);}-- announcer.register(&ctx, HookType::PostMerge, &extra, display_path)?;+ announcer.register(+ &ctx,+ HookType::PostMerge,+ &vars.as_extra_vars(),+ display_path,+ )?;}announcer.flush()?;diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex ee4bf43d3..7230cc99e 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -25,6 +25,7 @@ pub(crate) mod repository_ext;mod run_pipeline;pub(crate) mod statusline;pub(crate) mod step_commands;+pub(crate) mod template_vars;pub(crate) mod worktree;pub(crate) use alias::{diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex e0e3925c4..8bbc1f6c0 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -110,12 +110,13 @@ 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, switch_extra_vars,+ approve_switch_hooks, run_pre_switch_hooks, spawn_switch_background_hooks,};use super::hooks::{execute_hook, spawn_background_hooks};use super::list::collect;use super::list::progressive::RenderTarget;use super::repository_ext::{RemoveTarget, RepositoryCliExt};+use super::template_vars::TemplateVars;use super::worktree::hooks::PostRemoveContext;use super::worktree::{RemoveResult, SwitchBranchInfo, SwitchResult, execute_switch,@@ -758,10 +759,12 @@ pub fn handle_picker(let hooks_display_path =handle_switch_output(&result, &branch_info, change_dir, Some(&source_root), &cwd)?;- // Spawn background hooks after success message+ // 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 mut pr_number_buf = String::new();- let extra_vars = switch_extra_vars(&result, &mut pr_number_buf);+ let template_vars = TemplateVars::for_post_switch(&result, &branch_info, "", "");+ let extra_vars = template_vars.as_extra_vars();spawn_switch_background_hooks(&repo,&config,diff --git a/src/commands/template_vars.rs b/src/commands/template_vars.rsnew file mode 100644index 000000000..6af7f653b--- /dev/null+++ b/src/commands/template_vars.rs@@ -0,0 +1,329 @@+//! Canonical assembly of hook template variables for switch and merge.+//!+//! Replaces ad-hoc `Vec<(&str, &str)>` reconstructions across `handle_switch`,+//! `worktree::switch`, and `merge`. Owns its strings — no `pr_number_buf`+//! borrow gymnastics — and emits the deprecated `worktree` alias for+//! `worktree_path` once, here, so call sites don't repeat that aliasing.+//!+//! The struct carries operation-context vars (`base` / `target` directional+//! pairs and `pr_*`) plus optional Active overrides (`worktree_path`,+//! `worktree_name`, `commit`, `short_commit`) for sites whose hooks should+//! reference an Active identity that differs from the execution worktree —+//! e.g., post-merge running in the destination but referencing the feature+//! worktree, or pre-switch on an existing destination.++use std::path::Path;++use worktrunk::path::to_posix_path;++use super::worktree::{SwitchBranchInfo, SwitchResult};++#[derive(Default, Debug)]+pub(crate) struct TemplateVars {+ base: Option<String>,+ base_worktree_path: Option<String>,+ target: Option<String>,+ target_worktree_path: Option<String>,+ /// Override the bare `worktree_path` (and the deprecated `worktree` alias).+ active_worktree_path: Option<String>,+ /// Override the bare `worktree_name`.+ active_worktree_name: Option<String>,+ /// Override the bare `commit`.+ active_commit: Option<String>,+ /// Override the bare `short_commit`.+ active_short_commit: Option<String>,+ pr_number: Option<String>,+ pr_url: Option<String>,+}++impl TemplateVars {+ pub fn new() -> Self {+ Self::default()+ }++ /// Set `base` (source branch) and `base_worktree_path` from a path.+ pub fn with_base(mut self, branch: &str, worktree_path: &Path) -> Self {+ self.base = Some(branch.to_string());+ self.base_worktree_path = Some(to_posix_path(&worktree_path.to_string_lossy()));+ self+ }++ /// Set `base` and `base_worktree_path` from already-POSIX strings; either+ /// may be `None`. Mirrors the call sites that pull these straight off a+ /// `SwitchResult::Created`.+ pub fn with_base_strs(mut self, branch: Option<&str>, worktree_path: Option<&str>) -> Self {+ self.base = branch.map(str::to_owned);+ self.base_worktree_path = worktree_path.map(str::to_owned);+ self+ }++ /// Set `target` (destination branch).+ pub fn with_target(mut self, branch: &str) -> Self {+ self.target = Some(branch.to_string());+ self+ }++ /// Set `target_worktree_path` from a path.+ pub fn with_target_worktree_path(mut self, path: &Path) -> Self {+ self.target_worktree_path = Some(to_posix_path(&path.to_string_lossy()));+ self+ }++ /// Override the Active worktree identity. Sets `worktree_path` (and the+ /// deprecated `worktree` alias) plus `worktree_name`. Falls back to+ /// `"unknown"` for `worktree_name` when the path has no file name or the+ /// file name isn't UTF-8 — matches the pre-refactor merge.rs behavior so+ /// templates that reference `{{ worktree_name }}` keep rendering rather+ /// than failing on undefined.+ pub fn with_active_worktree(mut self, path: &Path) -> Self {+ self.active_worktree_path = Some(to_posix_path(&path.to_string_lossy()));+ self.active_worktree_name = Some(+ path.file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("unknown")+ .to_string(),+ );+ self+ }++ /// Override `commit`. Also sets `short_commit` to the first 7 characters+ /// when present (commit SHAs are ASCII hex, so the byte slice is safe).+ pub fn with_active_commit(mut self, commit: &str) -> Self {+ self.active_short_commit = commit.get(..7).map(str::to_owned);+ self.active_commit = Some(commit.to_string());+ self+ }++ /// Set `pr_number` and `pr_url` for `pr:N` / `mr:N` creations. Either may+ /// be `None`; both are emitted independently so partial state survives if+ /// callers ever route one without the other.+ pub fn with_pr(mut self, number: Option<u32>, url: Option<&str>) -> Self {+ self.pr_number = number.map(|n| n.to_string());+ self.pr_url = url.map(str::to_owned);+ self+ }++ /// Materialize as `(name, value)` pairs borrowing from `self`. Emits the+ /// deprecated `worktree` alias for `worktree_path` once, here.+ pub fn as_extra_vars(&self) -> Vec<(&str, &str)> {+ let mut out: Vec<(&str, &str)> = Vec::new();+ if let Some(v) = &self.base {+ out.push(("base", v));+ }+ if let Some(v) = &self.base_worktree_path {+ out.push(("base_worktree_path", v));+ }+ if let Some(v) = &self.target {+ out.push(("target", v));+ }+ if let Some(v) = &self.target_worktree_path {+ out.push(("target_worktree_path", v));+ }+ if let Some(v) = &self.active_worktree_path {+ out.push(("worktree_path", v));+ out.push(("worktree", v));+ }+ if let Some(v) = &self.active_worktree_name {+ out.push(("worktree_name", v));+ }+ if let Some(v) = &self.active_commit {+ out.push(("commit", v));+ }+ if let Some(v) = &self.active_short_commit {+ out.push(("short_commit", v));+ }+ if let Some(v) = &self.pr_number {+ out.push(("pr_number", v));+ }+ if let Some(v) = &self.pr_url {+ out.push(("pr_url", v));+ }+ out+ }++ /// Build the post-switch context (used by foreground execute, background+ /// hooks, and `--execute` template expansion).+ ///+ /// `target` matches the bare vars (the destination); `base` is the source+ /// — the branched-from for creates, the source worktree for existing+ /// switches. PR/MR identity propagates into post-* hooks.+ pub fn for_post_switch(+ result: &SwitchResult,+ branch_info: &SwitchBranchInfo,+ source_branch: &str,+ source_path: &str,+ ) -> Self {+ let mut vars = Self::new().with_target_worktree_path(result.path());+ if let Some(branch) = branch_info.branch.as_deref() {+ vars = vars.with_target(branch);+ }+ match result {+ SwitchResult::Created {+ base_branch,+ base_worktree_path,+ pr_number,+ pr_url,+ ..+ } => vars+ .with_base_strs(base_branch.as_deref(), base_worktree_path.as_deref())+ .with_pr(*pr_number, pr_url.as_deref()),+ SwitchResult::Existing { .. } | SwitchResult::AlreadyAt(_) => {+ let base = (!source_branch.is_empty()).then_some(source_branch);+ let path = (!source_path.is_empty()).then_some(source_path);+ vars.with_base_strs(base, path)+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use std::path::PathBuf;++ use super::*;++ #[test]+ fn empty_vars_produces_empty_slice() {+ let vars = TemplateVars::new();+ assert!(vars.as_extra_vars().is_empty());+ }++ #[test]+ fn directional_pairs_round_trip() {+ let vars = TemplateVars::new()+ .with_base("main", &PathBuf::from("/repo"))+ .with_target("feature")+ .with_target_worktree_path(&PathBuf::from("/repo.feature"));+ let pairs = vars.as_extra_vars();+ assert!(pairs.contains(&("base", "main")));+ assert!(pairs.contains(&("base_worktree_path", "/repo")));+ assert!(pairs.contains(&("target", "feature")));+ assert!(pairs.contains(&("target_worktree_path", "/repo.feature")));+ }++ #[test]+ fn active_worktree_emits_deprecated_alias() {+ let vars = TemplateVars::new().with_active_worktree(&PathBuf::from("/repo.feature"));+ let pairs = vars.as_extra_vars();+ // worktree_path is canonical; worktree is the deprecated alias.+ assert!(pairs.contains(&("worktree_path", "/repo.feature")));+ assert!(pairs.contains(&("worktree", "/repo.feature")));+ assert!(pairs.contains(&("worktree_name", "repo.feature")));+ }++ #[test]+ fn active_worktree_name_falls_back_to_unknown() {+ // Pre-refactor merge.rs used `unwrap_or("unknown")` for the name;+ // preserve that so `{{ worktree_name }}` templates keep rendering.+ let vars = TemplateVars::new().with_active_worktree(&PathBuf::from("/"));+ let pairs = vars.as_extra_vars();+ assert!(pairs.contains(&("worktree_name", "unknown")));+ }++ #[test]+ fn active_commit_derives_short_commit() {+ let vars = TemplateVars::new().with_active_commit("0123456789abcdef");+ let pairs = vars.as_extra_vars();+ assert!(pairs.contains(&("commit", "0123456789abcdef")));+ assert!(pairs.contains(&("short_commit", "0123456")));+ }++ #[test]+ fn active_commit_skips_short_when_too_short() {+ // SHAs are always >= 7 chars in practice, but `.get(..7)` returns None+ // for shorter strings rather than panicking — preserves merge.rs's+ // pre-refactor behavior.+ let vars = TemplateVars::new().with_active_commit("abc");+ let pairs = vars.as_extra_vars();+ assert!(pairs.iter().any(|(k, _)| *k == "commit"));+ assert!(!pairs.iter().any(|(k, _)| *k == "short_commit"));+ }++ #[test]+ fn pr_pair_independent() {+ let vars = TemplateVars::new().with_pr(Some(42), Some("https://example.test/pr/42"));+ let pairs = vars.as_extra_vars();+ assert!(pairs.contains(&("pr_number", "42")));+ assert!(pairs.contains(&("pr_url", "https://example.test/pr/42")));+ }++ #[test]+ fn with_base_strs_skips_none() {+ let vars = TemplateVars::new().with_base_strs(Some("main"), None);+ let pairs = vars.as_extra_vars();+ assert!(pairs.contains(&("base", "main")));+ assert!(!pairs.iter().any(|(k, _)| *k == "base_worktree_path"));+ }++ #[test]+ fn for_post_switch_created_with_pr() {+ let result = SwitchResult::Created {+ path: PathBuf::from("/repo.fork"),+ created_branch: false,+ base_branch: Some("main".to_string()),+ base_worktree_path: Some("/repo".to_string()),+ from_remote: None,+ pr_number: Some(42),+ pr_url: Some("https://example.test/pr/42".to_string()),+ };+ let info = SwitchBranchInfo {+ branch: Some("contributor/feature".to_string()),+ expected_path: None,+ };+ let vars = TemplateVars::for_post_switch(&result, &info, "", "");+ let pairs = vars.as_extra_vars();+ assert!(pairs.contains(&("base", "main")));+ assert!(pairs.contains(&("base_worktree_path", "/repo")));+ assert!(pairs.contains(&("target", "contributor/feature")));+ assert!(pairs.contains(&("target_worktree_path", "/repo.fork")));+ assert!(pairs.contains(&("pr_number", "42")));+ assert!(pairs.contains(&("pr_url", "https://example.test/pr/42")));+ }++ #[test]+ fn for_post_switch_existing_uses_source() {+ let result = SwitchResult::Existing {+ path: PathBuf::from("/repo.feature"),+ };+ let info = SwitchBranchInfo {+ branch: Some("feature".to_string()),+ expected_path: None,+ };+ let vars = TemplateVars::for_post_switch(&result, &info, "main", "/repo");+ let pairs = vars.as_extra_vars();+ assert!(pairs.contains(&("base", "main")));+ assert!(pairs.contains(&("base_worktree_path", "/repo")));+ assert!(pairs.contains(&("target", "feature")));+ assert!(pairs.contains(&("target_worktree_path", "/repo.feature")));+ assert!(!pairs.iter().any(|(k, _)| *k == "pr_number"));+ }++ #[test]+ fn for_post_switch_existing_skips_empty_source() {+ let result = SwitchResult::AlreadyAt(PathBuf::from("/repo.feature"));+ let info = SwitchBranchInfo {+ branch: Some("feature".to_string()),+ expected_path: None,+ };+ let vars = TemplateVars::for_post_switch(&result, &info, "", "");+ let pairs = vars.as_extra_vars();+ assert!(!pairs.iter().any(|(k, _)| *k == "base"));+ assert!(!pairs.iter().any(|(k, _)| *k == "base_worktree_path"));+ assert!(pairs.contains(&("target", "feature")));+ }++ #[test]+ fn for_post_switch_detached_omits_target_branch() {+ let result = SwitchResult::Existing {+ path: PathBuf::from("/repo.detached"),+ };+ let info = SwitchBranchInfo {+ branch: None,+ expected_path: None,+ };+ let vars = TemplateVars::for_post_switch(&result, &info, "", "");+ let pairs = vars.as_extra_vars();+ assert!(!pairs.iter().any(|(k, _)| *k == "target"));+ assert!(pairs.contains(&("target_worktree_path", "/repo.detached")));+ }+}diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex f06220529..1c1efa0d2 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -21,6 +21,7 @@ use worktrunk::styling::{use super::resolve::{compute_clobber_backup, compute_worktree_path};use super::types::{CreationMethod, SwitchBranchInfo, SwitchPlan, SwitchResult};use crate::commands::command_executor::CommandContext;+use crate::commands::template_vars::TemplateVars;/// Result of resolving the switch target.struct ResolvedTarget {@@ -909,8 +910,8 @@ pub fn execute_switch(.map(|p| worktrunk::path::to_posix_path(&p.to_string_lossy()));// PR/MR identity travels into both the pre-start hook below and the- // SwitchResult — switch_extra_vars then forwards it to background- // post-switch / post-start hooks.+ // SwitchResult — TemplateVars::for_post_switch then forwards it to+ // background post-switch / post-start hooks.let (pr_number, pr_url) = match &method {CreationMethod::ForkRef {number, ref_url, ..@@ -921,37 +922,21 @@ pub fn execute_switch(// Execute post-create commandsif run_hooks {let ctx = CommandContext::new(repo, config, Some(&branch), &worktree_path, force);- let target_wt_posix =- worktrunk::path::to_posix_path(&worktree_path.to_string_lossy());-+ let mut vars = TemplateVars::new()+ .with_target(&branch)+ .with_target_worktree_path(&worktree_path);match &method {CreationMethod::Regular { base_branch, .. } => {- let extra_vars: Vec<(&str, &str)> = [- base_branch.as_ref().map(|b| ("base", b.as_str())),- base_worktree_path- .as_ref()- .map(|p| ("base_worktree_path", p.as_str())),- Some(("target", branch.as_str())),- Some(("target_worktree_path", target_wt_posix.as_str())),- ]- .into_iter()- .flatten()- .collect();- ctx.execute_pre_start_commands(&extra_vars)?;+ vars = vars+ .with_base_strs(base_branch.as_deref(), base_worktree_path.as_deref());}CreationMethod::ForkRef {number, ref_url, ..} => {- let num_str = number.to_string();- let extra_vars: Vec<(&str, &str)> = vec![- ("pr_number", &num_str),- ("pr_url", ref_url),- ("target", &branch),- ("target_worktree_path", &target_wt_posix),- ];- ctx.execute_pre_start_commands(&extra_vars)?;+ vars = vars.with_pr(Some(*number), Some(ref_url));}}+ ctx.execute_pre_start_commands(&vars.as_extra_vars())?;}// Record successful switch in history