Skip to content

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

refactor(hooks): adopt TemplateVars in remaining call sites (#2481)

Maximilian Roos6701cc86803d
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index 36bebed90..fd090a108 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -10,6 +10,7 @@ use super::command_executor::CommandContext;
use super::command_executor::FailureStrategy;
use super::hooks::{execute_hook, spawn_background_hooks};
use super::repository_ext::warn_about_untracked_files;
+use super::template_vars::TemplateVars;
// Re-export StageMode from config for use by CLI
pub use worktrunk::config::StageMode;
@@ -170,18 +171,16 @@ impl CommitOptions<'_> {
eprintln!("{}", info_message("Skipping pre-commit hooks (--no-hooks)"));
}
- if self.verify {
- let extra_vars: Vec<(&str, &str)> = self
- .target_branch
- .into_iter()
- .map(|target| ("target", target))
- .collect();
+ let template_vars = self
+ .target_branch
+ .map_or_else(TemplateVars::new, |t| TemplateVars::new().with_target(t));
+ if self.verify {
// Run pre-commit hooks (user first, then project).
execute_hook(
self.ctx,
HookType::PreCommit,
- &extra_vars,
+ &template_vars.as_extra_vars(),
FailureStrategy::FailFast,
crate::output::pre_hook_display_path(self.ctx.worktree_path),
)?;
@@ -225,11 +224,7 @@ impl CommitOptions<'_> {
// Spawn post-commit hooks in background (respects --no-hooks)
if self.verify {
- let extra_vars: Vec<(&str, &str)> = self
- .target_branch
- .into_iter()
- .map(|target| ("target", target))
- .collect();
+ let extra_vars = template_vars.as_extra_vars();
spawn_background_hooks(self.ctx, HookType::PostCommit, &extra_vars, None)?;
}
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index f17107ba4..2e31a944d 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -31,6 +31,7 @@ use super::hooks::{
HookCommandSpec, lookup_hook_configs, prepare_and_check, prepare_background_pipelines,
run_hooks_background, run_hooks_foreground,
};
+use super::template_vars::TemplateVars;
fn run_filtered_hook(
ctx: &CommandContext,
@@ -105,52 +106,42 @@ fn run_post_hook(
/// Build best-effort directional vars for manual `wt hook` invocation.
///
/// When hooks run during real operations (switch, merge, remove), each call site
-/// builds precise extra_vars from the actual source/destination context. When
-/// invoked manually via `wt hook <type>`, we only have the current worktree —
-/// so we provide reasonable defaults: the current branch as both base and target,
-/// and the current worktree path for directional path vars.
+/// builds precise vars from the actual source/destination context. When invoked
+/// manually via `wt hook <type>`, we only have the current worktree — so we
+/// provide reasonable defaults: the current branch as both base and target, and
+/// the current worktree path for directional path vars.
///
/// This is the single source of truth for manual hook context — both `run_hook`
/// (execution + dry-run) and `expand_command_template` (hook show --expanded)
-/// use this function.
-fn build_manual_hook_extra_vars<'a>(
- ctx: &'a CommandContext,
+/// use this function. Returns a `TemplateVars` so callers can extend with
+/// additional bindings (e.g. CLI shorthand) before materializing.
+fn build_manual_hook_template_vars(
+ ctx: &CommandContext,
hook_type: HookType,
- custom_vars: &'a [(&'a str, &'a str)],
- default_branch: Option<&'a str>,
- worktree_path_str: &'a str,
-) -> Vec<(&'a str, &'a str)> {
+ default_branch: Option<&str>,
+) -> TemplateVars {
let branch = ctx.branch_or_head();
- let mut vars: Vec<(&str, &str)> = match hook_type {
+ let worktree_path = ctx.worktree_path;
+ match hook_type {
// Merge/commit hooks: target = merge target (default branch for commit, current for merge)
HookType::PreCommit | HookType::PostCommit => {
- default_branch.into_iter().map(|t| ("target", t)).collect()
- }
- HookType::PreMerge | HookType::PostMerge => {
- vec![
- ("target", branch),
- ("target_worktree_path", worktree_path_str),
- ]
+ default_branch.map_or_else(TemplateVars::new, |t| TemplateVars::new().with_target(t))
}
+ HookType::PreMerge | HookType::PostMerge => TemplateVars::new()
+ .with_target(branch)
+ .with_target_worktree_path(worktree_path),
// Switch hooks: base = current (we're "switching from" here)
HookType::PreSwitch | HookType::PreStart | HookType::PostStart | HookType::PostSwitch => {
- vec![
- ("base", branch),
- ("base_worktree_path", worktree_path_str),
- ("target", branch),
- ("target_worktree_path", worktree_path_str),
- ]
+ TemplateVars::new()
+ .with_base(branch, worktree_path)
+ .with_target(branch)
+ .with_target_worktree_path(worktree_path)
}
// Remove hooks: target = where user ends up (current worktree is the best guess)
- HookType::PreRemove | HookType::PostRemove => {
- vec![
- ("target", branch),
- ("target_worktree_path", worktree_path_str),
- ]
- }
- };
- vars.extend(custom_vars.iter().copied());
- vars
+ HookType::PreRemove | HookType::PostRemove => TemplateVars::new()
+ .with_target(branch)
+ .with_target_worktree_path(worktree_path),
+ }
}
/// Parse a raw `KEY=VALUE` shorthand token into a canonicalized
@@ -304,20 +295,15 @@ pub fn run_hook(
// Build extra vars per hook type (shared by dry-run and execution paths)
let default_branch = repo.default_branch();
- let worktree_path_str = worktrunk::path::to_posix_path(&ctx.worktree_path.to_string_lossy());
// Splice `args` into the template context as a JSON-encoded sequence.
// `expand_template` rehydrates it as `ShellArgs` so bare `{{ args }}`
// renders space-joined with per-element shell escaping. Mirrors
// `run_alias` at `src/commands/alias.rs`.
let args_json =
serde_json::to_string(&args).expect("Vec<String> serialization should never fail");
- let mut extra_vars = build_manual_hook_extra_vars(
- &ctx,
- hook_type,
- &custom_vars_refs,
- default_branch.as_deref(),
- &worktree_path_str,
- );
+ let template_vars = build_manual_hook_template_vars(&ctx, hook_type, default_branch.as_deref());
+ let mut extra_vars = template_vars.as_extra_vars();
+ extra_vars.extend(custom_vars_refs.iter().copied());
// Forward positional CLI args as `{{ args }}` (empty sequence when
// nothing was forwarded). `expand_template` rehydrates this JSON into a
// `ShellArgs` sequence that renders space-joined, per-element escaped.
@@ -602,14 +588,8 @@ fn expand_command_template(
hook_name: Option<&str>,
) -> anyhow::Result<String> {
let default_branch = ctx.repo.default_branch();
- let worktree_path_str = worktrunk::path::to_posix_path(&ctx.worktree_path.to_string_lossy());
- let extra_vars = build_manual_hook_extra_vars(
- ctx,
- hook_type,
- &[],
- default_branch.as_deref(),
- &worktree_path_str,
- );
+ let template_vars = build_manual_hook_template_vars(ctx, hook_type, default_branch.as_deref());
+ let extra_vars = template_vars.as_extra_vars();
let mut template_ctx = build_hook_context(ctx, &extra_vars)?;
template_ctx.insert("hook_type".into(), hook_type.to_string());
if let Some(name) = hook_name {
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index 5583f709b..4e6b1ed5e 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -194,17 +194,15 @@ impl PickerCollector {
.ok()
.flatten()
.unwrap_or_default();
- let target_path_str = worktrunk::path::to_posix_path(&main_path.to_string_lossy());
- let extra_vars: Vec<(&str, &str)> = vec![
- ("target", &target_ref),
- ("target_worktree_path", &target_path_str),
- ];
+ let template_vars = TemplateVars::new()
+ .with_target(&target_ref)
+ .with_target_worktree_path(main_path);
let pre_ctx =
CommandContext::new(&repo, config, Some(hook_branch), worktree_path, false);
execute_hook(
&pre_ctx,
worktrunk::HookType::PreRemove,
- &extra_vars,
+ &template_vars.as_extra_vars(),
FailureStrategy::FailFast,
None, // no display path in TUI context
)?;
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index 55673dd94..f86cd54d5 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -41,6 +41,7 @@ use super::commit::{CommitGenerator, CommitOptions, StageMode};
use super::context::CommandEnv;
use super::hooks::{execute_hook, spawn_background_hooks};
use super::repository_ext::{RemoveTarget, RepositoryCliExt};
+use super::template_vars::TemplateVars;
use crate::output::handle_remove_output;
use worktrunk::git::BranchDeletionMode;
@@ -166,6 +167,7 @@ pub fn handle_squash(
// Get and validate target ref (any commit-ish for merge-base calculation)
let integration_target = repo.require_target_ref(target)?;
+ let template_vars = TemplateVars::new().with_target(&integration_target);
// Auto-stage changes before running pre-commit hooks so both beta and merge paths behave identically
match stage_mode {
@@ -185,11 +187,10 @@ pub fn handle_squash(
// Run pre-commit hooks (user first, then project).
if verify {
- let extra_vars = [("target", integration_target.as_str())];
execute_hook(
&ctx,
HookType::PreCommit,
- &extra_vars,
+ &template_vars.as_extra_vars(),
FailureStrategy::FailFast,
crate::output::pre_hook_display_path(ctx.worktree_path),
)?;
@@ -342,7 +343,7 @@ pub fn handle_squash(
// Spawn post-commit hooks in background (respects --no-hooks)
if verify {
- let extra_vars: Vec<(&str, &str)> = vec![("target", integration_target.as_str())];
+ let extra_vars = template_vars.as_extra_vars();
spawn_background_hooks(&ctx, HookType::PostCommit, &extra_vars, None)?;
}
diff --git a/src/commands/template_vars.rs b/src/commands/template_vars.rs
index 6af7f653b..e41367ed0 100644
--- a/src/commands/template_vars.rs
+++ b/src/commands/template_vars.rs
@@ -1,9 +1,10 @@
-//! Canonical assembly of hook template variables for switch and merge.
+//! Canonical assembly of hook template variables.
//!
-//! 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.
+//! Replaces ad-hoc `Vec<(&str, &str)>` reconstructions across the hook call
+//! sites (switch, merge, commit, squash, manual `wt hook`, picker remove).
+//! 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`,