Skip to content

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

fix(hooks): resolve `wt switch`'s post-switch hooks from the new worktree (#2703)

Maximilian Roos5384f62bd63f
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rs
index 5629947f7..b994ec5cc 100644
--- a/src/commands/command_approval.rs
+++ b/src/commands/command_approval.rs
@@ -276,3 +276,35 @@ pub fn approve_or_skip(
}
Ok(approved)
}
+
+/// Like [`approve_or_skip`] but approves against an already-resolved
+/// `ProjectConfig` rather than `ctx.repo.load_project_config()`.
+///
+/// `wt switch`'s post-switch hooks (`pre-start` / `post-start` / `post-switch`)
+/// resolve their config from the new/destination worktree, which for
+/// `--create` doesn't exist yet at approval time — the config is read from the
+/// base ref via `git show` and passed in here so the prompt lists the exact
+/// commands the hooks will execute. `project_id` (the approvals namespace) is
+/// still taken from `ctx.repo`: it's repo-wide and independent of which
+/// worktree the commands come from.
+pub fn approve_or_skip_with_config(
+ ctx: &super::command_executor::CommandContext<'_>,
+ project_config: Option<&worktrunk::config::ProjectConfig>,
+ hook_types: &[HookType],
+ on_decline: &str,
+) -> anyhow::Result<bool> {
+ let Some(project_config) = project_config else {
+ return Ok(true); // no project config = no commands to approve
+ };
+ let commands = collect_commands_for_hooks(project_config, hook_types);
+ if commands.is_empty() {
+ return Ok(true);
+ }
+ let project_id = ctx.repo.project_identifier()?;
+ let approvals = Approvals::load().context("Failed to load approvals")?;
+ let approved = approve_command_batch(&commands, &project_id, &approvals, ctx.yes, false)?;
+ if !approved {
+ worktrunk::styling::eprintln!("{}", worktrunk::styling::info_message(on_decline));
+ }
+ Ok(approved)
+}
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index b2c2eb4dd..5ec100b48 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -7,7 +7,7 @@
//!
//! A hook resolves its project config from `ctx.repo.load_project_config()` —
//! [`execute_hook`], [`prepare_background_pipelines`], and
-//! [`super::command_approval::approve_hooks`] all do this — and
+//! [`super::command_approval::approve_hooks`] do this — and
//! `Repository::project_config_path` keys that off whichever worktree
//! `ctx.repo` was rooted at. So the rule reduces to **`ctx.repo` is rooted at
//! the worktree the hook acts on** (not, in general, where `wt` was invoked),
@@ -18,17 +18,20 @@
//! | `pre-remove` | the worktree being removed (still on disk at hook time); if it has no `.config/wt.toml`, the post-removal working directory (`RemoveResult.main_path`) — the **primary worktree** for `wt remove` / `wt step prune`, the merge destination for `wt merge` | `output::handlers::execute_pre_remove_hooks_if_needed`; approval mirrors it in `main.rs`'s `approve_remove` (`wt remove`), `merge::collect_merge_commands` (`wt merge`), and `step::prune::approve_prune_hooks` (`wt step prune` — over every worktree it might prune, since the integrated set isn't known until the checks run) |
//! | `post-merge`, `post-remove`, `post-switch` after a removal | the destination — for `wt merge`, the target branch's worktree (else the primary); for `wt remove` / `wt step prune`, the primary worktree — the removed/feature worktree is gone by then | `worktree::finish::finish_after_merge`, `output::handlers::spawn_hooks_after_remove` (approval mirrored in `merge::collect_merge_commands`, `main.rs`'s `approve_remove`, and `step::prune::approve_prune_hooks`) |
//! | `pre-commit` / `post-commit` | the worktree being committed — the cwd worktree, or `<b>`'s worktree for `wt step commit --branch <b>` | `commands::commit`, `step::commit` (via `CommandEnv::for_branch`) |
-//! | `wt switch`'s `pre-start` / `post-start` / `post-switch` | the worktree `wt switch` ran in — the new worktree doesn't exist yet when these are approved, and for `wt switch --create` it's a fresh checkout of that worktree's HEAD anyway | `worktree::switch` |
+//! | `wt switch`'s `pre-start` / `post-start` / `post-switch` | the new (`--create`) or destination (`wt switch <existing>`) worktree, where these run; if it has no `.config/wt.toml`, the primary worktree's. For `--create` the target doesn't exist yet at approval time, so the approval prompt and template pre-flight read its base ref's committed `.config/wt.toml` via `git show` (`git fetch`ing a `pr:`/`mr:` fork head first) — the new worktree, once created, is a checkout of that ref | `worktree::switch` — `hook_repo_for_worktree` (execution), `switch_hook_project_config` (approval / pre-flight) |
//! | `pre-switch`, `pre-merge`, `wt hook <type>`, aliases | the worktree `wt` was invoked in (= where they run) | the respective command entry points |
//!
//! `WORKTRUNK_PROJECT_CONFIG_PATH` overrides the path regardless of the root
//! (test isolation). User config (`~/.config/worktrunk/config.toml`) is global
-//! and unaffected. When a hook's worktree and its approval-time stand-in differ
-//! (the `wt switch --create` row), the approval prompt may list slightly
-//! different commands than execute — see that row's note for why it's harmless
-//! in practice. `pre-remove` and the merge/remove `post-*` hooks are otherwise
-//! approved against the exact config they execute against — the one exception
-//! being `wt step prune`, which over-approves `pre-remove` across every worktree
+//! and unaffected. Every hook is approved against the same `.config/wt.toml`
+//! it executes against — most paths mirror the execution root in their
+//! approval `ctx.repo` (so `approve_hooks` reads the same file); `wt switch`'s
+//! post-switch hooks instead resolve the config out of band
+//! (`worktree::switch::switch_hook_project_config`) — for `--create`, from the
+//! base ref's committed copy via `git show`, since the target worktree
+//! doesn't exist yet — and pass it to
+//! [`super::command_approval::approve_or_skip_with_config`]. The one exception
+//! is `wt step prune`, which over-approves `pre-remove` across every worktree
//! it might prune (the integrated set isn't known until the checks run), a
//! superset of what executes.
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index c99fd8f59..fb745195b 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -111,7 +111,7 @@ use super::worktree::hooks::PostRemoveContext;
use super::worktree::{
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,
+ spawn_switch_background_hooks, switch_hook_project_config,
};
use crate::commands::command_executor::CommandContext;
use crate::output::handle_switch_output;
@@ -782,7 +782,18 @@ pub fn handle_picker(
// Switch to existing worktree or create new one
let plan = plan_switch(&repo, &identifier, should_create, None, false, &config)?;
- let hooks_approved = approve_switch_hooks(&repo, &config, &plan, false, true)?;
+ // 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 = approve_switch_hooks(
+ &repo,
+ &config,
+ &plan,
+ false,
+ true,
+ hook_project_config.as_ref(),
+ )?;
let (result, branch_info) = execute_switch(&repo, plan, &config, false, hooks_approved)?;
// Compute path mismatch lazily (deferred from plan_switch for existing worktrees).
diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rs
index 64f3586fe..179191ac1 100644
--- a/src/commands/worktree/mod.rs
+++ b/src/commands/worktree/mod.rs
@@ -101,6 +101,7 @@ pub use switch::{SwitchOptions, run_switch};
#[cfg(unix)]
pub(crate) use switch::{
approve_switch_hooks, run_pre_switch_hooks, spawn_switch_background_hooks,
+ switch_hook_project_config,
};
#[cfg(unix)]
pub use switch::{execute_switch, plan_switch};
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index e1f775bad..8bfa65e67 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -13,7 +13,8 @@ use dunce::canonicalize;
use serde::Serialize;
use worktrunk::HookType;
use worktrunk::config::{
- UserConfig, ValidationScope, expand_template, template_references_var, validate_template,
+ ProjectConfig, UserConfig, ValidationScope, expand_template, template_references_var,
+ validate_template,
};
use worktrunk::git::remote_ref::{
self, AzureDevOpsProvider, GitHubProvider, GitLabProvider, GiteaProvider, RemoteRefInfo,
@@ -33,7 +34,7 @@ use super::resolve::{
};
use super::types::{CreationMethod, SwitchBranchInfo, SwitchPlan, SwitchResult};
use crate::cli::SwitchFormat;
-use crate::commands::command_approval::{approve_hooks, approve_or_skip};
+use crate::commands::command_approval::{approve_hooks, approve_or_skip_with_config};
use crate::commands::command_executor::FailureStrategy;
use crate::commands::command_executor::{CommandContext, build_hook_context};
use crate::commands::hooks::{HookAnnouncer, execute_hook};
@@ -1093,9 +1094,13 @@ pub fn execute_switch(
CreationMethod::Regular { .. } => (None, None),
};
- // Execute post-create commands
+ // Execute pre-start commands. The hook resolves its `.config/wt.toml`
+ // from the new worktree (created just above), falling back to the
+ // primary worktree's — see `hook_repo_for_worktree`.
if run_hooks {
- let ctx = CommandContext::new(repo, config, Some(&branch), &worktree_path, force);
+ let hook_repo = hook_repo_for_worktree(repo, &worktree_path);
+ let ctx =
+ CommandContext::new(&hook_repo, config, Some(&branch), &worktree_path, force);
let mut vars = TemplateVars::new()
.with_target(&branch)
.with_target_worktree_path(&worktree_path);
@@ -1298,8 +1303,127 @@ fn switch_post_hook_types(is_create: bool) -> &'static [HookType] {
}
}
+/// The git ref a `wt switch --create` (or a branchless `wt switch <branch>`
+/// that has to create a worktree) checks out into the new worktree — covers
+/// [`CreationMethod::Regular`] only; [`CreationMethod::ForkRef`] needs a
+/// `git fetch` first and is handled by [`switch_hook_project_config`].
+///
+/// Used to read that ref's committed `.config/wt.toml` before the worktree
+/// exists. Mirrors how [`execute_switch`] picks the `git worktree add`
+/// argument: an explicit `--create` base if one was resolved, else the
+/// existing local branch, else its single remote's tracking ref, else `HEAD`
+/// (the current worktree's tip — git's fallback for `git worktree add -b
+/// <new>` with no base, and the only thing left for a stale default branch).
+fn base_ref_for_create(
+ repo: &Repository,
+ create_branch: bool,
+ base_branch: Option<&str>,
+ branch: &str,
+) -> String {
+ if create_branch {
+ return base_branch.unwrap_or("HEAD").to_string();
+ }
+ if repo.branch(branch).exists_locally().unwrap_or(false) {
+ return branch.to_string();
+ }
+ let remotes = repo.branch(branch).remotes().unwrap_or_default();
+ if remotes.len() == 1 {
+ return format!("{}/{}", remotes[0], branch);
+ }
+ // Multiple remotes: replicate `git worktree add <branch>`'s DWIM — when
+ // `checkout.defaultRemote` names one of these remotes, that's the ref the
+ // new worktree will check out, so the hook preview must match. Without
+ // this, a `pre-start` on `<defaultRemote>/<branch>` could run unapproved
+ // because the preview defaulted to `HEAD`.
+ if remotes.len() > 1
+ && let Ok(Some(default)) = repo.config_value("checkout.defaultRemote")
+ && remotes.iter().any(|r| r == &default)
+ {
+ return format!("{default}/{branch}");
+ }
+ "HEAD".to_string()
+}
+
+/// The `.config/wt.toml` that `wt switch`'s post-switch hooks (`pre-start` /
+/// `post-start` / `post-switch`) will resolve against, viewed from *before*
+/// the worktree is created — so the approval prompt and the pre-flight
+/// template validation see the exact config `execute_switch` /
+/// [`spawn_switch_background_hooks`] (via [`hook_repo_for_worktree`]) read at
+/// run time.
+///
+/// For an existing destination the worktree is on disk, so its config is read
+/// directly. For `--create` the new worktree is a checkout of the resolved
+/// base ref (or, for `pr:`/`mr:` fork refs, the fetched PR/MR head), so the
+/// committed `.config/wt.toml` at that ref is read via `git show`. In both
+/// cases, if there's no `.config/wt.toml` there, fall back to the primary
+/// worktree's — a project-wide hook on the default branch still applies to a
+/// worktree branched before that hook was added (matching `pre-remove`).
+///
+/// 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(
+ repo: &Repository,
+ plan: &SwitchPlan,
+) -> anyhow::Result<Option<ProjectConfig>> {
+ let direct = match plan {
+ SwitchPlan::Existing { path, .. } => Repository::at(path)
+ .ok()
+ .and_then(|r| r.load_project_config().ok().flatten()),
+ SwitchPlan::Create { method, branch, .. } => {
+ let base_ref = match method {
+ CreationMethod::ForkRef {
+ remote, ref_path, ..
+ } => {
+ repo.run_command(&["fetch", "--", remote, ref_path])
+ .with_context(|| format!("Failed to fetch {ref_path} from {remote}"))?;
+ "FETCH_HEAD".to_string()
+ }
+ CreationMethod::Regular {
+ create_branch,
+ base_branch,
+ ..
+ } => base_ref_for_create(repo, *create_branch, base_branch.as_deref(), branch),
+ };
+ repo.project_config_at_ref(&base_ref)
+ }
+ };
+ if direct.is_some() {
+ return Ok(direct);
+ }
+
+ // No `.config/wt.toml` at the new/destination worktree (or its base ref) →
+ // fall back to the primary worktree's, so a project-wide hook on the
+ // default branch still applies (matching `pre-remove`).
+ Repository::at(repo.home_path()?)?.load_project_config()
+}
+
+/// The `Repository` whose `.config/wt.toml` a post-switch hook running in
+/// `worktree_path` should read: the new/destination worktree itself when it
+/// carries a `.config/wt.toml`, otherwise the primary worktree (so a
+/// project-wide hook on the default branch still applies). Mirrors
+/// `execute_pre_remove_hooks_if_needed`; the `repo.clone()` arm only triggers
+/// if even the primary worktree can't be opened.
+fn hook_repo_for_worktree(repo: &Repository, worktree_path: &Path) -> Repository {
+ if let Ok(wt_repo) = Repository::at(worktree_path)
+ && wt_repo.load_project_config().ok().flatten().is_some()
+ {
+ return wt_repo;
+ }
+ repo.home_path()
+ .and_then(Repository::at)
+ .unwrap_or_else(|_| repo.clone())
+}
+
/// Approve switch hooks upfront and show "Commands declined" if needed.
///
+/// `project_config` is the `.config/wt.toml` the post-switch hooks will run
+/// against — the new/destination worktree's (or, for `--create`, the base
+/// ref's), resolved by [`switch_hook_project_config`]. Passing it in (rather
+/// than letting the approval read `ctx.repo`'s config) is what keeps the
+/// prompt listing the exact commands `execute_switch` will run, including for
+/// `wt switch pr:N` against a fork's hooks.
+///
/// 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(
@@ -1308,6 +1432,7 @@ pub(crate) fn approve_switch_hooks(
plan: &SwitchPlan,
yes: bool,
verify: bool,
+ project_config: Option<&ProjectConfig>,
) -> anyhow::Result<bool> {
if !verify {
return Ok(false);
@@ -1319,7 +1444,12 @@ pub(crate) fn approve_switch_hooks(
} else {
"Commands declined"
};
- approve_or_skip(&ctx, switch_post_hook_types(plan.is_create()), on_decline)
+ approve_or_skip_with_config(
+ &ctx,
+ project_config,
+ switch_post_hook_types(plan.is_create()),
+ on_decline,
+ )
}
/// Spawn post-switch (and post-start for creates) background hooks.
@@ -1332,9 +1462,12 @@ pub(crate) fn spawn_switch_background_hooks(
extra_vars: &[(&str, &str)],
hooks_display_path: Option<&Path>,
) -> anyhow::Result<()> {
- let ctx = CommandContext::new(repo, config, branch, result.path(), yes);
+ // Background hooks run in the new/destination worktree and resolve their
+ // `.config/wt.toml` from there (fallback: the primary worktree's).
+ let hook_repo = hook_repo_for_worktree(repo, result.path());
+ let ctx = CommandContext::new(&hook_repo, config, branch, result.path(), yes);
- let mut announcer = HookAnnouncer::new(repo, config, false);
+ let mut announcer = HookAnnouncer::new(&hook_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)?;
@@ -1431,15 +1564,47 @@ pub fn run_switch(
}
})?;
+ // 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 = approve_switch_hooks(&repo, config, &plan, yes, verify)?;
+ let hooks_approved = 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)?;
+ validate_switch_templates(
+ &repo,
+ config,
+ &plan,
+ 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 }}.
@@ -1592,10 +1757,15 @@ pub fn run_switch(
/// completed successfully — template failure is a missed notification, not a
/// blocking state. The user can fix the template and run `wt hook` manually.
///
+/// `project_config` is the `.config/wt.toml` the post-switch hooks will run
+/// against — the new/destination worktree's (for `--create`, the base ref's),
+/// resolved by [`switch_hook_project_config`] — so the templates checked here
+/// are the ones that will actually be expanded, not the invoking worktree's.
+///
/// 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
+/// - Hook templates (pre-start, post-start, post-switch) from user and project config
fn validate_switch_templates(
repo: &Repository,
config: &UserConfig,
@@ -1603,6 +1773,7 @@ fn validate_switch_templates(
execute: Option<&str>,
execute_args: &[String],
hooks_approved: bool,
+ project_config: Option<&ProjectConfig>,
) -> anyhow::Result<()> {
// Validate --execute template and trailing args
if let Some(cmd) = execute {
@@ -1627,15 +1798,11 @@ fn validate_switch_templates(
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,
- );
+ let (user_cfg, proj_cfg) =
+ crate::commands::hooks::lookup_hook_configs(&user_hooks, project_config, hook_type);
for (source, cfg) in [("user", user_cfg), ("project", proj_cfg)] {
if let Some(cfg) = cfg {
for cmd in cfg.commands() {
@@ -1779,4 +1946,75 @@ mod tests {
PrProviderChoice::GitHub
);
}
+
+ /// `base_ref_for_create` names the ref the new worktree checks out, so the
+ /// pre-creation hook-config preview reads the same `.config/wt.toml` the
+ /// hooks will run against — mirroring `execute_switch`'s `git worktree add`
+ /// argument choice for `CreationMethod::Regular`.
+ #[test]
+ fn base_ref_for_create_picks_the_checkout_ref() {
+ let mut test = TestRepo::with_initial_commit();
+ test.setup_remote("main");
+ test.run_git(&["branch", "local-feature"]);
+ // A branch that lives only on the remote: push it, then drop the local ref.
+ test.run_git(&["branch", "remote-feature"]);
+ test.run_git(&["push", "origin", "remote-feature"]);
+ test.run_git(&["branch", "-D", "remote-feature"]);
+
+ // `--create` with an explicit base → that base.
+ assert_eq!(
+ base_ref_for_create(&test.repo, true, Some("dev"), "feature"),
+ "dev"
+ );
+ // `--create` with no resolvable default branch → `HEAD` (git's own
+ // fallback for `git worktree add -b <new>` with no base).
+ assert_eq!(
+ base_ref_for_create(&test.repo, true, None, "feature"),
+ "HEAD"
+ );
+ // An existing local branch (no worktree yet) → that branch.
+ assert_eq!(
+ base_ref_for_create(&test.repo, false, None, "local-feature"),
+ "local-feature"
+ );
+ // A branch that exists only on a single remote → its tracking ref.
+ assert_eq!(
+ base_ref_for_create(&test.repo, false, None, "remote-feature"),
+ "origin/remote-feature"
+ );
+ // No local ref, no remote → `HEAD`.
+ assert_eq!(
+ base_ref_for_create(&test.repo, false, None, "nowhere"),
+ "HEAD"
+ );
+
+ // A branch on multiple remotes: with `checkout.defaultRemote` set,
+ // matches what `git worktree add <branch>` would DWIM to; without it,
+ // git would refuse to pick — preview safely defaults to `HEAD`.
+ test.setup_custom_remote("upstream", "main");
+ test.run_git(&["branch", "shared-feature"]);
+ test.run_git(&["push", "origin", "shared-feature"]);
+ test.run_git(&["push", "upstream", "shared-feature"]);
+ test.run_git(&["branch", "-D", "shared-feature"]);
+ // `checkout.defaultRemote` may be set in the user's global config —
+ // override locally so the test isn't sensitive to it.
+ test.repo
+ .set_config("checkout.defaultRemote", "no-such-remote")
+ .unwrap();
+ let repo = Repository::at(test.root_path()).unwrap();
+ // Default doesn't match any remote on the branch → fall back to HEAD.
+ assert_eq!(
+ base_ref_for_create(&repo, false, None, "shared-feature"),
+ "HEAD"
+ );
+ // With `checkout.defaultRemote = upstream`, that remote's ref wins —
+ // matching what `git worktree add shared-feature` would DWIM to.
+ repo.set_config("checkout.defaultRemote", "upstream")
+ .unwrap();
+ let repo = Repository::at(test.root_path()).unwrap();
+ assert_eq!(
+ base_ref_for_create(&repo, false, None, "shared-feature"),
+ "upstream/shared-feature"
+ );
+ }
}
diff --git a/src/git/repository/config.rs b/src/git/repository/config.rs
index b00e5a347..37a75ba8a 100644
--- a/src/git/repository/config.rs
+++ b/src/git/repository/config.rs
@@ -613,6 +613,35 @@ impl Repository {
})
.map(Option::as_ref)
}
+
+ /// Parse `.config/wt.toml` as committed at `gitref` (a branch name,
+ /// `FETCH_HEAD`, a SHA, …), applying the structural TOML migration so
+ /// deprecated patterns still parse.
+ ///
+ /// Used to preview the project config a not-yet-created worktree will
+ /// check out: `wt switch --create`'s hook-approval prompt and template
+ /// pre-flight read the base ref this way so they match what the
+ /// post-switch hooks execute against once the worktree exists (a checkout
+ /// of that ref). `WORKTRUNK_PROJECT_CONFIG_PATH` overrides the path
+ /// regardless of the ref, the same as [`project_config_path`].
+ ///
+ /// Unlike [`load_project_config`](Self::load_project_config) this never
+ /// touches the working tree and never writes a `.new` migration file —
+ /// it must not, since the content comes from an arbitrary ref rather than
+ /// the user's working copy. Returns `None` when the ref has no
+ /// `.config/wt.toml` (git exits non-zero) or the content fails to parse.
+ ///
+ /// [`project_config_path`]: Self::project_config_path
+ pub fn project_config_at_ref(&self, gitref: &str) -> Option<ProjectConfig> {
+ if std::env::var_os("WORKTRUNK_PROJECT_CONFIG_PATH").is_some() {
+ return self.load_project_config().ok().flatten();
+ }
+ let content = self
+ .run_command(&["show", &format!("{gitref}:.config/wt.toml")])
+ .ok()?;
+ let migrated = crate::config::migrate_content(&content);
+ toml::from_str::<ProjectConfig>(&migrated).ok()
+ }
}
#[cfg(test)]
@@ -620,6 +649,31 @@ mod tests {
use super::*;
use crate::testing::TestRepo;
+ #[test]
+ fn project_config_at_ref_reads_committed_config() {
+ let test = TestRepo::with_initial_commit();
+ let repo = Repository::at(test.root_path()).unwrap();
+
+ // No `.config/wt.toml` committed yet, and a nonexistent ref → None.
+ assert!(repo.project_config_at_ref("HEAD").is_none());
+ assert!(repo.project_config_at_ref("no-such-ref").is_none());
+
+ // Commit one and read it back at that branch.
+ test.write_project_config(r#"post-start = "echo hi""#);
+ test.run_git(&["add", ".config/wt.toml"]);
+ test.run_git(&["commit", "-m", "Add config"]);
+ let cfg = repo
+ .project_config_at_ref("HEAD")
+ .expect("config committed at HEAD");
+ assert!(cfg.hooks.post_start.is_some());
+
+ // A committed file that doesn't parse → None (rather than erroring).
+ test.write_project_config("this is not [ valid toml");
+ test.run_git(&["add", ".config/wt.toml"]);
+ test.run_git(&["commit", "-m", "Break config"]);
+ assert!(repo.project_config_at_ref("HEAD").is_none());
+ }
+
#[test]
fn test_get_config_regexp_no_match_returns_empty() {
// Exit 1 from git config --get-regexp means "no keys matched" — must
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 65ca4f2ad..20b9739f9 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -889,6 +889,149 @@ fn test_switch_no_config_commands_with_yes(repo: TestRepo) {
);
}
+/// `wt switch --create <new> --base <other>` resolves `pre-start` / `post-start`
+/// from the base branch's committed `.config/wt.toml` — the worktree these hooks
+/// run in is a checkout of that branch. The primary worktree (cwd) has no
+/// project config at all; only `other-base` does, so a regression that read the
+/// invoking worktree's config would run nothing.
+#[rstest]
+fn test_switch_create_reads_base_branch_config(mut repo: TestRepo) {
+ // Commit a `.config/wt.toml` on `other-base` only (not on `main`).
+ let other_wt = repo.add_worktree("other-base");
+ fs::create_dir_all(other_wt.join(".config")).unwrap();
+ fs::write(
+ other_wt.join(".config/wt.toml"),
+ // `{{ repo_path }}` is the main worktree root regardless of which
+ // worktree the hook runs in, so the markers land where the test reads.
+ r#"pre-start = "echo pre-start-from-base > {{ repo_path }}/pre-start-marker.txt"
+post-start = "echo post-start-from-base > {{ repo_path }}/post-start-marker.txt"
+"#,
+ )
+ .unwrap();
+ repo.run_git_in(&other_wt, &["add", ".config/wt.toml"]);
+ repo.run_git_in(&other_wt, &["commit", "-m", "Add hooks on other-base"]);
+
+ let output = repo
+ .wt_command()
+ .args([
+ "switch",
+ "--create",
+ "new-feature",
+ "--base",
+ "other-base",
+ "--yes",
+ ])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "wt switch --create failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let pre_marker = repo.root_path().join("pre-start-marker.txt");
+ wait_for_file_content(&pre_marker);
+ assert_eq!(
+ fs::read_to_string(&pre_marker).unwrap().trim(),
+ "pre-start-from-base",
+ "pre-start should run with the base branch's config"
+ );
+ let post_marker = repo.root_path().join("post-start-marker.txt");
+ wait_for_file_content(&post_marker);
+ assert_eq!(
+ fs::read_to_string(&post_marker).unwrap().trim(),
+ "post-start-from-base",
+ "post-start should run with the base branch's config"
+ );
+}
+
+/// `wt switch <existing>` resolves `post-switch` from the destination worktree's
+/// `.config/wt.toml`, not the worktree `wt switch` ran in. Only the destination
+/// has a project config here.
+#[rstest]
+fn test_switch_existing_reads_destination_worktree_config(mut repo: TestRepo) {
+ let dest = repo.add_worktree("dest");
+ fs::create_dir_all(dest.join(".config")).unwrap();
+ fs::write(
+ dest.join(".config/wt.toml"),
+ r#"post-switch = "echo post-switch-from-dest > {{ repo_path }}/post-switch-marker.txt""#,
+ )
+ .unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["switch", "dest", "--yes"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "wt switch dest failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let marker = repo.root_path().join("post-switch-marker.txt");
+ wait_for_file_content(&marker);
+ assert_eq!(
+ fs::read_to_string(&marker).unwrap().trim(),
+ "post-switch-from-dest",
+ "post-switch should run with the destination worktree's config"
+ );
+}
+
+/// `WORKTRUNK_PROJECT_CONFIG_PATH` overrides the path for *every* config read —
+/// including `wt switch --create`'s base-ref preview — so the override file's
+/// hooks run, not the base branch's committed `.config/wt.toml`.
+#[rstest]
+fn test_switch_create_honors_project_config_path_override(mut repo: TestRepo) {
+ // The base branch carries a committed hook that must be ignored.
+ let other_wt = repo.add_worktree("other-base");
+ fs::create_dir_all(other_wt.join(".config")).unwrap();
+ fs::write(
+ other_wt.join(".config/wt.toml"),
+ r#"post-start = "echo IGNORED-COMMITTED-HOOK > {{ repo_path }}/wrong-marker.txt""#,
+ )
+ .unwrap();
+ repo.run_git_in(&other_wt, &["add", ".config/wt.toml"]);
+ repo.run_git_in(&other_wt, &["commit", "-m", "Committed hook on other-base"]);
+
+ // The override file (outside any worktree) is what should win.
+ let override_path = repo.root_path().parent().unwrap().join("override-wt.toml");
+ fs::write(
+ &override_path,
+ r#"post-start = "echo OVERRIDE-HOOK > {{ repo_path }}/right-marker.txt""#,
+ )
+ .unwrap();
+
+ let output = repo
+ .wt_command()
+ .env("WORKTRUNK_PROJECT_CONFIG_PATH", &override_path)
+ .args([
+ "switch",
+ "--create",
+ "new-feature",
+ "--base",
+ "other-base",
+ "--yes",
+ ])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "wt switch --create failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let right = repo.root_path().join("right-marker.txt");
+ wait_for_file_content(&right);
+ assert_eq!(fs::read_to_string(&right).unwrap().trim(), "OVERRIDE-HOOK");
+ // The base ref's committed hook must never have run.
+ std::thread::sleep(std::time::Duration::from_millis(500));
+ assert!(
+ !repo.root_path().join("wrong-marker.txt").exists(),
+ "the base ref's committed hook must not run when the config path is overridden"
+ );
+}
+
// --no-verify backward compatibility
#[rstest]
fn test_switch_no_verify_deprecated_still_works(repo: TestRepo) {
@@ -2247,6 +2390,123 @@ post-switch = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_pa
}
}
+/// `wt switch pr:N` resolves `post-start` etc. from the PR's tree — the fetched
+/// head ref, potentially from a fork — and the approval prompt reads that same
+/// PR config, so what the prompt lists can't diverge from what runs. The local
+/// repo has no project config; only the PR commit does. Without `--yes` the
+/// prompt lists the PR's hook and bails (non-interactive); with `--yes` the
+/// hook executes against the new worktree (a checkout of the PR head).
+#[rstest]
+fn test_switch_pr_reads_pr_ref_config(#[from(repo_with_remote)] repo: TestRepo) {
+ // Fork-PR scenario (mirrors `test_switch_pr_hooks_see_pr_vars`): a
+ // refs/pull/42/head on the bare remote, origin redirected to a GitHub URL,
+ // `gh api` mocked — but the PR commit carries a `.config/wt.toml`.
+ repo.run_git(&["checkout", "-b", "pr-source"]);
+ fs::write(repo.root_path().join("pr-file.txt"), "PR content").unwrap();
+ fs::create_dir_all(repo.root_path().join(".config")).unwrap();
+ fs::write(
+ repo.root_path().join(".config/wt.toml"),
+ r#"post-start = "echo PR-CONFIG-HOOK-RAN > {{ repo_path }}/pr-hook-marker.txt""#,
+ )
+ .unwrap();
+ repo.run_git(&["add", "pr-file.txt", ".config/wt.toml"]);
+ repo.run_git(&["commit", "-m", "PR commit with hook config"]);
+
+ let sha = String::from_utf8_lossy(
+ &repo
+ .git_command()
+ .args(["rev-parse", "HEAD"])
+ .run()
+ .unwrap()
+ .stdout,
+ )
+ .trim()
+ .to_string();
+ repo.run_git(&["push", "origin", &format!("{sha}:refs/pull/42/head")]);
+ // Back on `main`, which never had `.config/wt.toml` committed — `pr-source`
+ // branched off before that commit, so `git checkout main` drops it from the
+ // working tree, leaving the local repo with no project config.
+ repo.run_git(&["checkout", "main"]);
+
+ let bare_url = String::from_utf8_lossy(
+ &repo
+ .git_command()
+ .args(["config", "remote.origin.url"])
+ .run()
+ .unwrap()
+ .stdout,
+ )
+ .trim()
+ .to_string();
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "https://github.com/owner/test-repo.git",
+ ]);
+ repo.run_git(&[
+ "config",
+ &format!("url.{bare_url}.insteadOf"),
+ "https://github.com/owner/test-repo.git",
+ ]);
+
+ let gh_response = r#"{
+ "title": "Add feature fix for edge case",
+ "user": {"login": "contributor"},
+ "state": "open",
+ "draft": false,
+ "head": {
+ "ref": "feature-fix",
+ "repo": {"name": "test-repo", "owner": {"login": "contributor"}}
+ },
+ "base": {
+ "ref": "main",
+ "repo": {"name": "test-repo", "owner": {"login": "owner"}}
+ },
+ "html_url": "https://github.com/owner/test-repo/pull/42"
+ }"#;
+ let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));
+
+ // (a) Without `--yes`: the approval prompt prints the PR's command template
+ // to stderr, then bails (stdin is not a TTY in tests). No worktree, no hook.
+ let mut cmd = repo.wt_command();
+ cmd.args(["switch", "pr:42"]);
+ configure_mock_cli_env(&mut cmd, &mock_bin);
+ let output = cmd.output().expect("wt switch pr:42 should run");
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("PR-CONFIG-HOOK-RAN"),
+ "approval prompt should list the PR ref's post-start hook; stderr:\n{stderr}"
+ );
+ assert!(
+ !output.status.success(),
+ "non-interactive approval should bail without running the hook"
+ );
+ assert!(
+ !repo.root_path().join("pr-hook-marker.txt").exists(),
+ "a declined approval must not run the hook"
+ );
+
+ // (b) With `--yes`: the PR's `post-start` runs against the new worktree.
+ let mut cmd = repo.wt_command();
+ cmd.args(["switch", "pr:42", "--yes"]);
+ configure_mock_cli_env(&mut cmd, &mock_bin);
+ let output = cmd.output().expect("wt switch pr:42 --yes should run");
+ assert!(
+ output.status.success(),
+ "wt switch pr:42 --yes failed: stdout={}\nstderr={}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr),
+ );
+ let marker = repo.root_path().join("pr-hook-marker.txt");
+ wait_for_file_content(&marker);
+ assert_eq!(
+ fs::read_to_string(&marker).unwrap().trim(),
+ "PR-CONFIG-HOOK-RAN",
+ "post-start should run with the PR ref's config"
+ );
+}
+
/// Test fork PR when origin points to fork (no remote for base repo)
///
/// User scenario: