Skip to content

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

feat(hooks): `post-remove` reads the removed worktree's config (snapshot before removal) (#2736)

Maximilian Roos23d655247120
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 58d6eede6..5280b8ed6 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -5,36 +5,56 @@
//!
//! # Which `.config/wt.toml` a hook reads
//!
-//! A hook resolves its project config from `ctx.repo.load_project_config()` —
-//! [`execute_hook`], [`prepare_background_pipelines`], 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),
-//! and the construction sites enforce it. Each worktree's `.config/wt.toml`
-//! stands alone — there is no fallback to the primary worktree's config when
-//! the acting worktree has none, and a present-but-malformed config aborts the
-//! operation rather than silently using a different one.
+//! **Every hook is anchored to one worktree — the worktree it's *about*.** It
+//! reads that worktree's `.config/wt.toml`. When the worktree isn't on disk at
+//! the moment we need to read it, read a snapshot.
//!
-//! | Hook | `ctx.repo` rooted at → config from | Set in |
+//! Most hooks resolve their project config from `ctx.repo.load_project_config()`
+//! — [`execute_hook`], [`prepare_background_pipelines`], and
+//! [`super::command_approval::approve_hooks`] all do this — so the construction
+//! sites just have to root `ctx.repo` at the anchor worktree. Two hooks resolve
+//! the config from a snapshot instead, because the anchor isn't on disk at
+//! preparation time: see "Snapshot paths" below.
+//!
+//! Each worktree's `.config/wt.toml` stands alone — there is no fallback to
+//! the primary worktree's config when the anchor has none, and a
+//! present-but-malformed config aborts the operation rather than silently
+//! using a different one.
+//!
+//! | Hook | Anchor worktree | Set in |
//! |---|---|---|
-//! | `pre-remove` | the worktree being removed (still on disk at hook time) | `output::handlers::execute_pre_remove_hooks_if_needed`; the three approval call sites (`main.rs`'s `approve_remove` for `wt remove`, `merge::collect_merge_commands` for `wt merge`, `step::prune::approve_prune_hooks` for `wt step prune`) all delegate to [`super::project_config::collect_remove_hook_commands`] |
-//! | `post-merge`, `post-remove`, `post-switch` after a removal | the post-removal working directory — for `wt remove` / `wt step prune` always the primary worktree; for `wt merge` the target branch's worktree if one exists, otherwise the primary (path choice for the destination, not a config fallback). The removed/feature worktree is gone by then. | `worktree::finish::finish_after_merge`, `output::handlers::spawn_hooks_after_remove` (approval of `post-remove`/`post-switch` for the three remove flows runs through [`super::project_config::collect_remove_hook_commands`]; `post-merge` is added by `merge::collect_merge_commands` directly) |
+//! | `pre-remove`, `post-remove` | the worktree being removed (`pre-remove` reads it on disk; `post-remove` reads a snapshot taken before removal, stashed on [`super::worktree::RemoveResult::RemovedWorktree::removed_project_config`]) | `output::handlers::execute_pre_remove_hooks_if_needed` and `output::handlers::spawn_hooks_after_remove`; the three approval call sites (`main.rs`'s `approve_remove` for `wt remove`, `merge::collect_merge_commands` for `wt merge`, `step::prune::approve_prune_hooks` for `wt step prune`) all delegate to [`super::project_config::collect_remove_hook_commands`] |
+//! | `post-merge` | the merge destination (target branch's worktree if it has one, otherwise the primary) | `worktree::finish::finish_after_merge`; approval in `merge::collect_merge_commands` |
+//! | `post-switch` after a removal | the post-removal working directory (where the user landed) — for `wt remove` / `wt step prune` the primary worktree, for `wt merge` the merge destination | `output::handlers::spawn_hooks_after_remove`; approval through `collect_remove_hook_commands` |
//! | `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 new (`--create`) or destination (`wt switch <existing>`) worktree, where these run. 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 |
+//! | `wt switch`'s `pre-start` / `post-start` / `post-switch` | the new (`--create`) or destination (`wt switch <existing>`) worktree | `worktree::switch` — `hook_repo_for_worktree` (execution); `switch_hook_project_config` (approval / pre-flight, see Snapshot paths below) |
+//! | `pre-switch`, `pre-merge`, `wt hook <type>`, aliases | the worktree `wt` was invoked in | the respective command entry points |
+//!
+//! ## Snapshot paths
+//!
+//! Two hooks need the anchor's config when the anchor itself isn't on disk:
+//!
+//! - **`post-remove`** runs after the anchor worktree was just deleted. The
+//! removed worktree's `ProjectConfig` is loaded by `prepare_worktree_removal`
+//! (or `finish_after_merge` for `wt merge`) *before* the deletion and stashed
+//! on `RemoveResult::RemovedWorktree::removed_project_config`. The executor
+//! reads it via [`HookAnnouncer::register_with_project_config`].
+//! - **`wt switch --create`'s post-switch hooks** (approval-time only) anchor at
+//! a worktree that doesn't exist yet — `git worktree add` runs after the
+//! approval gate. The approval prompt and template pre-flight read the base
+//! ref's committed `.config/wt.toml` via `git show` (`git fetch`ing a
+//! `pr:`/`mr:` fork head first), assembled by `switch_hook_project_config` and
+//! passed to [`super::command_approval::approve_or_skip_with_config`]. By
+//! execution time the worktree exists and the executor reads its on-disk
+//! config the normal way.
+//!
+//! Different physical sources, same role: produce the anchor's config when the
+//! anchor isn't on disk.
//!
//! `WORKTRUNK_PROJECT_CONFIG_PATH` overrides the path regardless of the root
//! (test isolation). User config (`~/.config/worktrunk/config.toml`) is global
//! 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 calls
+//! it executes against. The one exception is `wt step prune`, which calls
//! [`super::project_config::collect_remove_hook_commands`] over every linked
//! worktree it might prune (the integrated set isn't known until the checks
//! run), a superset of what executes.
@@ -258,7 +278,13 @@ impl<'a> HookAnnouncer<'a> {
}
}
- /// Prepare and add user+project pipelines for a single hook type.
+ /// Prepare and add user+project pipelines for a single hook type, reading
+ /// the project config from `ctx.repo.load_project_config()` — the worktree
+ /// this hook acts on, per the spec. Use [`Self::register_with_project_config`]
+ /// when the anchor worktree isn't on disk and the config came from a
+ /// snapshot or git ref (`post-remove` after the worktree is gone; `wt
+ /// switch`'s post-switch hooks before `--create` materializes the new
+ /// worktree).
pub fn register(
&mut self,
ctx: &CommandContext<'_>,
@@ -266,7 +292,28 @@ impl<'a> HookAnnouncer<'a> {
extra_vars: &[(&str, &str)],
display_path: Option<&Path>,
) -> anyhow::Result<()> {
- let pipelines = prepare_background_pipelines(ctx, hook_type, extra_vars, display_path)?;
+ let project_config = ctx.repo.load_project_config()?;
+ self.register_with_project_config(
+ ctx,
+ project_config.as_ref(),
+ hook_type,
+ extra_vars,
+ display_path,
+ )
+ }
+
+ /// Like [`Self::register`], but reads the project config from an explicit
+ /// snapshot instead of `ctx.repo.load_project_config()`.
+ pub fn register_with_project_config(
+ &mut self,
+ ctx: &CommandContext<'_>,
+ project_config: Option<&worktrunk::config::ProjectConfig>,
+ hook_type: HookType,
+ extra_vars: &[(&str, &str)],
+ display_path: Option<&Path>,
+ ) -> anyhow::Result<()> {
+ let pipelines =
+ prepare_background_pipelines(ctx, project_config, hook_type, extra_vars, display_path)?;
self.extend(pipelines);
Ok(())
}
@@ -432,19 +479,23 @@ pub(crate) fn into_source_groups(flat: Vec<SourcedStep>) -> Vec<Vec<SourcedStep>
/// them by source so each source spawns as an independent pipeline. Each
/// group is returned with its `(hook_type, display_path)` metadata.
///
-/// Project config comes from `ctx.repo.load_project_config()` — see the
-/// module-level "Which `.config/wt.toml` a hook reads" docs for which worktree
-/// `ctx.repo` is rooted at per hook type.
+/// `project_config` is the resolved `.config/wt.toml` for this hook's anchor
+/// worktree — normally `ctx.repo.load_project_config()` (what
+/// [`HookAnnouncer::register`] passes), or a snapshot / git-ref-derived config
+/// when the anchor isn't on disk at preparation time: `post-remove` (worktree
+/// just removed; config snapshotted on [`super::worktree::RemoveResult::RemovedWorktree`])
+/// and `wt switch`'s post-switch hooks before `--create` materializes the new
+/// worktree (config from the base ref via `git show`). See the module-level
+/// "Which `.config/wt.toml` a hook reads" docs.
pub(crate) fn prepare_background_pipelines<'c>(
ctx: &CommandContext<'c>,
+ project_config: Option<&worktrunk::config::ProjectConfig>,
hook_type: HookType,
extra_vars: &[(&str, &str)],
display_path: Option<&Path>,
) -> anyhow::Result<Vec<BackgroundPipeline<'c>>> {
- let project_config = ctx.repo.load_project_config()?;
let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());
- let (user_config, proj_config) =
- lookup_hook_configs(&user_hooks, project_config.as_ref(), hook_type);
+ let (user_config, proj_config) = lookup_hook_configs(&user_hooks, project_config, hook_type);
let flat = prepare_and_check(
ctx,
HookCommandSpec {
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index f0e11da5c..dc2505df8 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -188,15 +188,19 @@ impl PickerCollector {
target_branch,
force_worktree,
removed_commit,
+ removed_project_config,
..
} => {
- let repo = Repository::at(main_path)?;
- let config = repo.user_config();
+ let main_repo = Repository::at(main_path)?;
+ let config = main_repo.user_config();
let hook_branch = branch_name.as_deref().unwrap_or("HEAD");
// Run pre-remove hooks (synchronously in this background thread).
- // Non-zero exit aborts the removal, matching `wt remove` semantics.
- let target_ref = repo
+ // Rooted at the removed worktree so its `.config/wt.toml` is the
+ // one that fires — same rule as `wt remove`'s
+ // `execute_pre_remove_hooks_if_needed`. Non-zero exit aborts the
+ // removal, matching `wt remove` semantics.
+ let target_ref = main_repo
.worktree_at(main_path)
.branch()
.ok()
@@ -205,8 +209,14 @@ impl PickerCollector {
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);
+ let removed_repo = Repository::at(worktree_path)?;
+ let pre_ctx = CommandContext::new(
+ &removed_repo,
+ config,
+ Some(hook_branch),
+ worktree_path,
+ false,
+ );
execute_hook(
&pre_ctx,
worktrunk::HookType::PreRemove,
@@ -215,9 +225,9 @@ impl PickerCollector {
None, // no display path in TUI context
)?;
- let snapshot = repo.capture_refs()?;
+ let snapshot = main_repo.capture_refs()?;
let output = remove_worktree_with_cleanup(
- &repo,
+ &main_repo,
&snapshot,
worktree_path,
RemoveOptions {
@@ -231,19 +241,22 @@ impl PickerCollector {
let _ = std::fs::remove_dir_all(&staged);
}
- // Spawn post-remove hooks in background (log to files, no terminal output).
+ // Spawn post-remove hooks in background. The removed worktree
+ // is gone, so its `.config/wt.toml` comes from the snapshot —
+ // same source the `wt remove` / `wt merge` teardown paths use.
let post_ctx =
- CommandContext::new(&repo, config, Some(hook_branch), main_path, false);
+ CommandContext::new(&main_repo, config, Some(hook_branch), main_path, false);
let remove_vars = PostRemoveContext::new(
worktree_path,
removed_commit.as_deref(),
main_path,
- &repo,
+ &main_repo,
);
let extra_vars = remove_vars.extra_vars(hook_branch);
- let mut announcer = HookAnnouncer::new(&repo, config, false);
- announcer.register(
+ let mut announcer = HookAnnouncer::new(&main_repo, config, false);
+ announcer.register_with_project_config(
&post_ctx,
+ removed_project_config.as_deref(),
worktrunk::HookType::PostRemove,
&extra_vars,
None, // no display path in TUI context
@@ -1027,6 +1040,7 @@ pub mod tests {
force_worktree: false,
expected_path: None,
removed_commit: None,
+ removed_project_config: None,
};
PickerCollector::do_removal(&repo, &result).unwrap();
@@ -1123,6 +1137,7 @@ pub mod tests {
force_worktree: false,
expected_path: None,
removed_commit: None,
+ removed_project_config: None,
};
PickerCollector::do_removal(&repo, &result).unwrap();
diff --git a/src/commands/project_config.rs b/src/commands/project_config.rs
index 19590e685..1f2ebc846 100644
--- a/src/commands/project_config.rs
+++ b/src/commands/project_config.rs
@@ -47,19 +47,19 @@ pub fn collect_commands_for_hooks(
/// Collect the project commands that run as part of removing a set of worktrees.
///
-/// Each `pre-remove` reads the removed worktree's own `.config/wt.toml` — no
-/// fallback to `primary_repo`'s config, mirroring
-/// `output::handlers::execute_pre_remove_hooks_if_needed`, the executor that
-/// runs the hook. `post-remove` and `post-switch` always read `primary_repo`'s
-/// config (the removed worktree is gone by the time they fire). For `wt merge`,
+/// Each `pre-remove` and `post-remove` reads the removed worktree's own
+/// `.config/wt.toml` — both hooks are *about* that worktree, and at approval
+/// time it's still on disk. `post-switch` reads `primary_repo`'s config (the
+/// post-removal working directory, where the user lands). For `wt merge`,
/// `primary_repo` is the merge destination — same rule, different "primary".
///
-/// A present-but-malformed worktree config surfaces as an error so the user
+/// No fallback to another worktree's config, mirroring the executors
+/// (`output::handlers::execute_pre_remove_hooks_if_needed` and the
+/// `post-remove` snapshot path in `spawn_hooks_after_remove`). A
+/// present-but-malformed worktree config surfaces as an error so the user
/// fixes it rather than silently running a different one.
///
-/// Templates are deduped: when several removed worktrees define the same
-/// `pre-remove` template, the approval prompt shows it once rather than once
-/// per worktree.
+/// Templates are deduped so the approval prompt shows each command once.
///
/// Callers feed the result into [`super::command_approval::approve_command_batch`].
/// `wt merge` prepends its own `pre-commit` / `post-commit` / `pre-merge` /
@@ -76,15 +76,15 @@ pub fn collect_remove_hook_commands(
// worktree — propagate rather than silently fall back. See #2708.
let wt_repo = Repository::at(wt_path)?;
if let Some(cfg) = wt_repo.load_project_config()? {
- commands.extend(collect_commands_for_hooks(&cfg, &[HookType::PreRemove]));
+ commands.extend(collect_commands_for_hooks(
+ &cfg,
+ &[HookType::PreRemove, HookType::PostRemove],
+ ));
}
}
if let Some(cfg) = primary_repo.load_project_config()? {
- commands.extend(collect_commands_for_hooks(
- &cfg,
- &[HookType::PostRemove, HookType::PostSwitch],
- ));
+ commands.extend(collect_commands_for_hooks(&cfg, &[HookType::PostSwitch]));
}
let mut seen = HashSet::new();
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 6409e1a28..2c4cad500 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -318,6 +318,26 @@ impl RepositoryCliExt for Repository {
.ok()
.map(|s| s.trim().to_string());
+ // Snapshot the removed worktree's `.config/wt.toml` before removal so
+ // `post-remove` can read it after the directory is gone. `pre-remove`
+ // runs against the same config from disk; both hooks are *about* the
+ // removed worktree — see the spec in `commands::hooks`.
+ //
+ // A parse failure here is intentionally not propagated: the executor
+ // (`output::handlers::execute_pre_remove_hooks_if_needed`) re-reads
+ // the config from disk and surfaces the parse error with its full
+ // chain via `print_command_error`. `pre-remove` aborts before
+ // `post-remove` fires, so the snapshot being `None` in the malformed
+ // case is invisible to the user. Routing the parse error through
+ // `prepare_worktree_removal` instead would land it in `main.rs`'s
+ // `record_error`, which renders only the top message — a pre-existing
+ // display gap orthogonal to this work.
+ let removed_project_config = Repository::at(&worktree_path)?
+ .load_project_config()
+ .ok()
+ .flatten()
+ .map(Box::new);
+
Ok(RemoveResult::RemovedWorktree {
main_path,
worktree_path,
@@ -329,6 +349,7 @@ impl RepositoryCliExt for Repository {
force_worktree,
expected_path,
removed_commit,
+ removed_project_config,
})
}
diff --git a/src/commands/worktree/finish.rs b/src/commands/worktree/finish.rs
index b859c530d..8674cbba3 100644
--- a/src/commands/worktree/finish.rs
+++ b/src/commands/worktree/finish.rs
@@ -139,6 +139,16 @@ pub fn finish_after_merge(
);
let expected_path = path_mismatch(repo, current_branch, &worktree_root, config);
+ // Snapshot the feature worktree's `.config/wt.toml` before removal so
+ // `post-remove` can read it after the directory is gone — same
+ // mechanism as `prepare_worktree_removal`. The repo is already rooted
+ // at the feature worktree (`current_wt`), so `load_project_config`
+ // reads from there. Parse errors propagate here because they'd abort
+ // `wt merge` upfront (no removal happens yet, so the executor's
+ // re-read path that handles them on the `wt remove` side isn't
+ // reachable from this call).
+ let removed_project_config = repo.load_project_config()?.map(Box::new);
+
let remove_result = RemoveResult::RemovedWorktree {
main_path: destination_path.clone(),
worktree_path: worktree_root,
@@ -150,6 +160,7 @@ pub fn finish_after_merge(
force_worktree: false,
expected_path,
removed_commit: feature_commit.clone(),
+ removed_project_config,
};
crate::output::handle_remove_output(&remove_result, false, verify, false, announcer)?;
true
diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rs
index 5565da361..b896b8d02 100644
--- a/src/commands/worktree/types.rs
+++ b/src/commands/worktree/types.rs
@@ -4,6 +4,7 @@
use std::path::{Path, PathBuf};
+use worktrunk::config::ProjectConfig;
use worktrunk::git::{BranchDeletionMode, RefType};
/// Flags indicating which merge operations occurred
@@ -182,6 +183,16 @@ pub enum RemoveResult {
/// Used for post-remove hook template variables so they reference the
/// removed worktree's state, not the execution context.
removed_commit: Option<String>,
+ /// The removed worktree's `.config/wt.toml`, snapshotted before
+ /// deletion. `pre-remove` reads it on disk (the worktree is still
+ /// there); `post-remove` reads this snapshot (the worktree is gone by
+ /// then). `None` when the removed worktree had no `.config/wt.toml`.
+ /// Both hooks are *about* the removed worktree — see the spec in
+ /// `commands::hooks` "Which `.config/wt.toml` a hook reads".
+ ///
+ /// Boxed because `ProjectConfig` is ~600 bytes and would otherwise
+ /// dominate the variant size (clippy `large_enum_variant`).
+ removed_project_config: Option<Box<ProjectConfig>>,
},
/// Branch exists but has no worktree - attempt branch deletion only.
///
@@ -357,6 +368,7 @@ mod tests {
force_worktree: false,
expected_path: None,
removed_commit: Some("abc1234567890".to_string()),
+ removed_project_config: None,
};
match result {
RemoveResult::RemovedWorktree {
@@ -370,6 +382,7 @@ mod tests {
force_worktree,
expected_path,
removed_commit,
+ removed_project_config: _,
} => {
assert_eq!(main_path.to_str().unwrap(), "/main");
assert_eq!(worktree_path.to_str().unwrap(), "/worktree");
@@ -455,6 +468,7 @@ mod tests {
force_worktree: true,
expected_path: None,
removed_commit: None, // Detached HEAD may not have meaningful commit
+ removed_project_config: None,
};
match result {
RemoveResult::RemovedWorktree {
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index cc5094d2c..d0a1475a2 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -11,13 +11,13 @@ use worktrunk::styling::{eprint, format_bash_with_gutter, stderr};
use crate::commands::command_executor::CommandContext;
use crate::commands::command_executor::FailureStrategy;
-use crate::commands::hooks::{HookAnnouncer, execute_hook, prepare_background_pipelines};
+use crate::commands::hooks::{HookAnnouncer, execute_hook};
use crate::commands::process::{
HookLog, InternalOp, build_remove_command, build_remove_command_staged, spawn_detached,
};
use crate::commands::worktree::hooks::PostRemoveContext;
use crate::commands::worktree::{RemoveResult, SwitchBranchInfo, SwitchResult};
-use worktrunk::config::UserConfig;
+use worktrunk::config::{ProjectConfig, UserConfig};
use worktrunk::git::ErrorExt;
use worktrunk::git::GitError;
use worktrunk::git::IntegrationReason;
@@ -750,6 +750,7 @@ pub fn handle_remove_output(
force_worktree,
expected_path,
removed_commit,
+ removed_project_config,
} => handle_removed_worktree_output(
RemovedWorktreeOutputContext {
main_path,
@@ -762,6 +763,7 @@ pub fn handle_remove_output(
force_worktree: *force_worktree,
expected_path: expected_path.as_deref(),
removed_commit: removed_commit.as_deref(),
+ removed_project_config: removed_project_config.as_deref(),
foreground,
verify,
},
@@ -920,9 +922,14 @@ fn spawn_hooks_after_remove(
// branch since both post-remove and post-switch are consequences of that removal.
let remove_ctx = CommandContext::new(repo, &config, Some(removed_branch), ctx.main_path, false);
- // Collect post-remove and post-switch hooks for a single combined announcement.
- let mut pipelines = prepare_background_pipelines(
+ // `post-remove` is *about* the removed worktree, so its project config
+ // comes from the snapshot taken before removal — the worktree itself is
+ // gone by now. `post-switch` is *about* the destination worktree (where
+ // the user landed), so its config loads from `remove_ctx` (rooted at
+ // `ctx.main_path`) the normal way.
+ announcer.register_with_project_config(
&remove_ctx,
+ ctx.removed_project_config,
worktrunk::HookType::PostRemove,
&extra_vars,
display_path,
@@ -930,24 +937,18 @@ fn spawn_hooks_after_remove(
// Post-switch: only when the user actually changed directory.
// Uses its own context with the destination branch for template variables.
- // dest_branch hoisted so it outlives the pipelines vec.
- let dest_branch = if ctx.changed_directory {
- Some(repo.worktree_at(ctx.main_path).branch()?)
- } else {
- None
- };
- if let Some(ref dest_branch) = dest_branch {
+ if ctx.changed_directory {
+ let dest_branch = repo.worktree_at(ctx.main_path).branch()?;
let switch_ctx =
CommandContext::new(repo, &config, dest_branch.as_deref(), ctx.main_path, false);
- pipelines.extend(prepare_background_pipelines(
+ announcer.register(
&switch_ctx,
worktrunk::HookType::PostSwitch,
&[],
display_path,
- )?);
+ )?;
}
- announcer.extend(pipelines);
Ok(())
}
@@ -1173,6 +1174,10 @@ struct RemovedWorktreeOutputContext<'a> {
force_worktree: bool,
expected_path: Option<&'a Path>,
removed_commit: Option<&'a str>,
+ /// The removed worktree's `.config/wt.toml`, snapshotted before removal.
+ /// Used by `post-remove` (the worktree is gone by the time it runs);
+ /// `pre-remove` reads the same file on disk via `Repository::at`.
+ removed_project_config: Option<&'a ProjectConfig>,
foreground: bool,
verify: bool,
}
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index d0bbf1d1f..d0082141d 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -1758,6 +1758,59 @@ fn test_pre_remove_hook_reads_removed_worktree_config(mut repo: TestRepo) {
);
}
+/// `post-remove` reads the *removed* worktree's `.config/wt.toml`, even though
+/// the worktree is gone by the time the hook runs. The config is snapshotted
+/// before removal and threaded through `RemoveResult` to the executor —
+/// symmetric with `pre-remove`, which reads the same file from disk while it's
+/// still there. Both hooks are *about* the removed worktree.
+#[rstest]
+fn test_post_remove_hook_reads_removed_worktree_config(mut repo: TestRepo) {
+ use crate::common::wait_for_file_content;
+
+ let worktree_path = repo.add_worktree("feature-local-hook");
+ let marker_file = repo.root_path().join("post-remove-ran.txt");
+ std::fs::create_dir_all(worktree_path.join(".config")).unwrap();
+ std::fs::write(
+ worktree_path.join(".config/wt.toml"),
+ // `{{ branch }}` proves the hook ran with the removed worktree's
+ // template context; the marker living outside the removed worktree
+ // (in the primary) lets us assert it after the worktree is gone.
+ format!(
+ r#"post-remove = "echo 'post-remove of {{{{ branch }}}}' > {}""#,
+ marker_file.to_slash_lossy()
+ ),
+ )
+ .unwrap();
+
+ let output = repo
+ .wt_command()
+ .args([
+ "remove",
+ "--foreground",
+ "--force",
+ "--yes",
+ "feature-local-hook",
+ ])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "wt remove failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ wait_for_file_content(&marker_file);
+ assert_eq!(
+ std::fs::read_to_string(&marker_file).unwrap().trim(),
+ "post-remove of feature-local-hook",
+ "post-remove should run with the removed worktree's config, snapshotted before removal"
+ );
+ assert!(
+ !worktree_path.exists(),
+ "feature worktree should be removed"
+ );
+}
+
/// A worktree with a malformed `.config/wt.toml` makes `wt remove` abort with
/// the parse error in stderr — no silent fall-through to a different config,
/// and the worktree stays on disk so the user can fix it.