Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(approval): share the remove-hook approval helper across remove/merge/prune (#2709)
Maximilian Roos06285edf9075
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 5ec100b48..39b1eba0b 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -15,8 +15,8 @@//!//! | Hook | `ctx.repo` rooted at → config from | Set in |//! |---|---|---|-//! | `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-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`; 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`], which mirrors the executor's fallback |+//! | `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 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-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; 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 |@@ -31,9 +31,10 @@//! 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.+//! 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.use std::collections::HashMap;use std::path::{Path, PathBuf};diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 61a4f4a3a..6d1b61887 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -2,7 +2,7 @@ use std::path::Path;use anyhow::Context;use worktrunk::HookType;-use worktrunk::config::{Approvals, MergeConfig, ProjectConfig, UserConfig};+use worktrunk::config::{Approvals, MergeConfig, UserConfig};use worktrunk::git::Repository;use worktrunk::styling::{eprintln, info_message};@@ -11,7 +11,9 @@ use super::command_executor::FailureStrategy;use super::commit::{CommitOptions, HookGate};use super::context::CommandEnv;use super::hooks::{HookAnnouncer, execute_hook};-use super::project_config::{ApprovableCommand, collect_commands_for_hooks};+use super::project_config::{+ ApprovableCommand, collect_commands_for_hooks, collect_remove_hook_commands,+};use super::repository_ext::RepositoryCliExt;use super::template_vars::TemplateVars;use super::worktree::{@@ -81,12 +83,13 @@ pub struct MergeOptions<'a> {////// - `pre-commit` / `post-commit` / `pre-merge` → the feature worktree/// (= `repo`'s cwd).-/// - `post-merge` / `post-remove` / `post-switch` → the merge destination-/// (`destination_path`); these run after the feature worktree is removed.-/// - `pre-remove` → the feature worktree if it has a `.config/wt.toml` (it's-/// still on disk when the hook runs), else the destination — mirroring-/// `output::handlers::execute_pre_remove_hooks_if_needed`, the executor for-/// both `wt remove` and `wt merge`'s teardown.+/// - `post-merge` → the merge destination (`destination_path`).+/// - `pre-remove` / `post-remove` / `post-switch` (when the feature worktree+/// is being removed) → resolved by [`collect_remove_hook_commands`], which+/// reads `pre-remove` from the feature worktree's own `.config/wt.toml`+/// (falling back to the destination's) and `post-remove` / `post-switch`+/// from the destination — mirroring+/// `output::handlers::execute_pre_remove_hooks_if_needed`.fn collect_merge_commands(repo: &Repository,destination_path: &Path,@@ -97,7 +100,6 @@ fn collect_merge_commands() -> anyhow::Result<(Vec<ApprovableCommand>, String)> {let mut feature_hooks = Vec::new();let mut destination_hooks = Vec::new();- let mut needs_pre_remove = false;// Pre-commit hooks run when a commit will actually be createdlet will_create_commit = repo.current_worktree().is_dirty()? || squash_enabled;@@ -109,34 +111,27 @@ fn collect_merge_commands(if verify {feature_hooks.push(HookType::PreMerge);destination_hooks.push(HookType::PostMerge);- if will_remove {- needs_pre_remove = true;- destination_hooks.push(HookType::PostRemove);- destination_hooks.push(HookType::PostSwitch);- }}- let feature_config = repo.load_project_config()?;- // Load the destination's config if a destination-bucket hook needs it, or- // if `pre-remove` has to fall back to it (the feature worktree has no- // `.config/wt.toml` — same fallback the executor takes).- let destination_config =- if !destination_hooks.is_empty() || (needs_pre_remove && feature_config.is_none()) {- ProjectConfig::load(&Repository::at(destination_path)?, true)- .context("Failed to load project config")?- } else {- None- };-let mut all_commands = Vec::new();- if let Some(cfg) = feature_config.as_ref() {- all_commands.extend(collect_commands_for_hooks(cfg, &feature_hooks));+ if let Some(cfg) = repo.load_project_config()? {+ all_commands.extend(collect_commands_for_hooks(&cfg, &feature_hooks));}- if let Some(cfg) = destination_config.as_ref() {- all_commands.extend(collect_commands_for_hooks(cfg, &destination_hooks));- }- if needs_pre_remove && let Some(cfg) = feature_config.as_ref().or(destination_config.as_ref()) {- all_commands.extend(collect_commands_for_hooks(cfg, &[HookType::PreRemove]));+ if !destination_hooks.is_empty() || (verify && will_remove) {+ let destination_repo = Repository::at(destination_path)?;+ if !destination_hooks.is_empty()+ && let Some(cfg) = destination_repo.load_project_config()?+ {+ all_commands.extend(collect_commands_for_hooks(&cfg, &destination_hooks));+ }+ if verify && will_remove {+ let current_wt = repo.current_worktree();+ let feature_path = current_wt.path();+ all_commands.extend(collect_remove_hook_commands(+ &destination_repo,+ &[feature_path],+ )?);+ }}Ok((all_commands, repo.project_identifier()?))diff --git a/src/commands/project_config.rs b/src/commands/project_config.rsindex 6a9b9c925..8b5f5a020 100644--- a/src/commands/project_config.rs+++ b/src/commands/project_config.rs@@ -1,7 +1,9 @@+use std::collections::HashSet;use std::fmt;+use std::path::Path;use worktrunk::config::{Command, ProjectConfig};-use worktrunk::git::HookType;+use worktrunk::git::{HookType, Repository};/// What triggered a project command — determines the label in approval prompts.#[derive(Clone)]@@ -43,6 +45,60 @@ pub fn collect_commands_for_hooks(commands}+/// Collect the project commands that run as part of removing a set of worktrees.+///+/// Each `pre-remove` reads the removed worktree's `.config/wt.toml`, falling+/// back to `primary_repo`'s config when the removed worktree carries none —+/// 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`, `primary_repo` is the merge destination — same+/// fallback rule, different "primary".+///+/// Templates are deduped: when several removed worktrees fall back to+/// `primary_repo`'s config, the same `pre-remove` command would otherwise+/// appear in the approval prompt once per worktree.+///+/// Callers feed the result into [`super::command_approval::approve_command_batch`].+/// `wt merge` prepends its own `pre-commit` / `post-commit` / `pre-merge` /+/// `post-merge` commands to the same batch; `wt remove` and `wt step prune`+/// approve the helper's output on its own.+pub fn collect_remove_hook_commands(+ primary_repo: &Repository,+ removed_worktree_paths: &[&Path],+) -> anyhow::Result<Vec<ApprovableCommand>> {+ let mut commands: Vec<ApprovableCommand> = Vec::new();++ for &wt_path in removed_worktree_paths {+ // A `Repository::at` failure means git can't recognize the path as a+ // worktree — propagate rather than silently fall back. The fallback+ // below is for the legitimate "no `.config/wt.toml`" case only, and+ // matches the executor (`execute_pre_remove_hooks_if_needed` in+ // `output::handlers`) — see #2708 for the full rationale.+ let wt_at_path = Repository::at(wt_path)?;+ let wt_repo = if wt_at_path.load_project_config().ok().flatten().is_some() {+ wt_at_path+ } else {+ primary_repo.clone()+ };+ if let Some(cfg) = wt_repo.load_project_config()? {+ commands.extend(collect_commands_for_hooks(&cfg, &[HookType::PreRemove]));+ }+ }++ if let Some(cfg) = primary_repo.load_project_config()? {+ commands.extend(collect_commands_for_hooks(+ &cfg,+ &[HookType::PostRemove, HookType::PostSwitch],+ ));+ }++ let mut seen = HashSet::new();+ commands.retain(|cmd| seen.insert(cmd.command.template.clone()));++ Ok(commands)+}+/// Collect commands for every project-config alias, in `BTreeMap` (alphabetical) order.////// Mirrors `approve_alias_commands` in `command_approval.rs`: unnamed steps withindiff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rsindex 74c617af6..e8bf96c77 100644--- a/src/commands/step/prune.rs+++ b/src/commands/step/prune.rs@@ -2,21 +2,20 @@use std::collections::HashSet;use std::fs;-use std::path::PathBuf;+use std::path::{Path, PathBuf};use std::time::Duration;use anyhow::Context;use color_print::cformat;use crossbeam_channel as chan;use rayon::prelude::*;-use worktrunk::HookType;use worktrunk::config::{Approvals, UserConfig};use worktrunk::git::{BranchDeletionMode, RefSnapshot, Repository, WorktreeInfo};use worktrunk::styling::{eprintln, hint_message, info_message, println, success_message};use super::super::command_approval::approve_command_batch;use super::super::hooks::HookAnnouncer;-use super::super::project_config::{ApprovableCommand, collect_commands_for_hooks};+use super::super::project_config::collect_remove_hook_commands;use super::super::repository_ext::{RemoveTarget, RepositoryCliExt};use crate::output::handle_remove_output;@@ -383,17 +382,15 @@ fn render_dry_run(}/// Approve the project commands `wt step prune` may run, mirroring the-/// executors' `.config/wt.toml` resolution.+/// executors' `.config/wt.toml` resolution via+/// [`collect_remove_hook_commands`].////// `pre-remove` runs only when a *live linked* worktree is removed (stale-/// metadata and orphan-branch removals delete just the branch — no-/// `pre-remove`/`post-remove`/`post-switch`), and each `pre-remove` runs in,-/// and resolves its config from, that worktree — falling back to the primary-/// worktree's config when the removed one carries none, exactly like-/// `output::handlers::execute_pre_remove_hooks_if_needed`. The integration-/// checks haven't run yet, so every linked worktree's `pre-remove` is approved-/// up front — a superset of what executes. `post-remove`/`post-switch` run in-/// the primary worktree afterwards and are approved once against its config.+/// `pre-remove`/`post-remove`/`post-switch`). The integration checks haven't+/// run yet, so every linked worktree is fed to the helper — its `pre-remove`+/// approval is a superset of what executes. `post-remove` / `post-switch`+/// resolve from the primary worktree's config (the same helper input).////// Returns `true` when hooks should run, `false` when the user declined.fn approve_prune_hooks(@@ -405,35 +402,14 @@ fn approve_prune_hooks(let primary_path = repo.home_path()?;let primary_repo = Repository::at(&primary_path)?;- let mut all_commands: Vec<ApprovableCommand> = Vec::new();-- for item in check_items {- let CheckSource::Linked { wt_idx } = &item.source else {- continue;- };- let wt = &worktrees[*wt_idx];- let wt_at_path = Repository::at(&wt.path)?;- let wt_repo = if wt_at_path.load_project_config().ok().flatten().is_some() {- wt_at_path- } else {- primary_repo.clone()- };- if let Some(cfg) = wt_repo.load_project_config()? {- all_commands.extend(collect_commands_for_hooks(&cfg, &[HookType::PreRemove]));- }- }-- if let Some(cfg) = primary_repo.load_project_config()? {- all_commands.extend(collect_commands_for_hooks(- &cfg,- &[HookType::PostRemove, HookType::PostSwitch],- ));- }-- // The same template can be reached through several worktrees (most often- // via the primary fallback) — show, and remember, each command once.- let mut seen = HashSet::new();- all_commands.retain(|cmd| seen.insert(cmd.command.template.clone()));+ let removed_worktree_paths: Vec<&Path> = check_items+ .iter()+ .filter_map(|item| match &item.source {+ CheckSource::Linked { wt_idx } => Some(worktrees[*wt_idx].path.as_path()),+ _ => None,+ })+ .collect();+ let all_commands = collect_remove_hook_commands(&primary_repo, &removed_worktree_paths)?;if all_commands.is_empty() {return Ok(true);diff --git a/src/main.rs b/src/main.rsindex b1c63421e..be727994c 100644--- a/src/main.rs+++ b/src/main.rs@@ -7,7 +7,7 @@ use clap::FromArgMatches;use clap::error::ErrorKind as ClapErrorKind;use color_print::{ceprintln, cformat};use std::process;-use worktrunk::config::{UserConfig, set_config_path};+use worktrunk::config::{Approvals, UserConfig, set_config_path};use worktrunk::git::{ErrorExt, Repository, ResolvedWorktree, WorktrunkError, current_or_recover, cwd_removed_hint,set_base_path,@@ -16,9 +16,9 @@ use worktrunk::styling::{eprintln, error_message, format_with_gutter, hint_message, info_message, warning_message,};-use commands::command_approval::approve_or_skip;-use commands::command_executor::CommandContext;+use commands::command_approval::approve_command_batch;use commands::hooks::HookAnnouncer;+use commands::project_config::collect_remove_hook_commands;use commands::worktree::RemoveResult;mod cli;@@ -71,7 +71,6 @@ use cli::{ListSubcommand, LogsAction, MarkerAction, MergeArgs, PreviousBranchAction, RemoveArgs,StateCommand, StepCommand, SwitchArgs, SwitchFormat, VarsAction,};-use worktrunk::HookType;/// Render a clap error to stderr, appending a wt-specific nested-subcommand/// tip when the unknown name matches something under `wt step` / `wt hook`@@ -894,58 +893,32 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {.into());}- // Branch context for the approval prompt. Templates are shown- // unexpanded, so the exact branch is immaterial — `project_id`- // (which selects the approvals namespace) doesn't depend on it.- let approve_branch = repo- .current_worktree()- .branch()- .context("Failed to determine current branch")?;-- // Helper: approve remove hooks. `pre-remove` runs in each worktree- // being removed and resolves *that* worktree's `.config/wt.toml`- // (falling back to the primary worktree's when the removed one has- // none — same rule as `execute_pre_remove_hooks_if_needed`), so- // it's approved per worktree against that config; `post-remove` and- // `post-switch` run in the primary worktree afterwards (the removed- // worktree is gone) and are approved once against its config. The- // `Repository` rooted at each path is what selects the config — see- // [`Repository::project_config_path`]. Returns true if every prompt- // was accepted (or there was nothing to approve).+ // Helper: approve every command the removal will run, in one batch.+ // `pre-remove` runs in — and resolves its `.config/wt.toml` from —+ // each worktree being removed (falling back to the primary+ // worktree's config when the removed one carries none, same rule+ // as `execute_pre_remove_hooks_if_needed`); `post-remove` and+ // `post-switch` run in the primary worktree afterwards and resolve+ // their config from there. The shared helper assembles both,+ // dedup'd by template (multiple worktrees often fall back to the+ // same primary config). Returns `true` when the prompt was+ // accepted or there was nothing to approve.let approve_remove = |removed_worktree_paths: &[&Path], yes: bool| -> anyhow::Result<bool> {- let decline_msg = "Commands declined, continuing removal";let primary_path = repo.home_path()?;let primary_repo = Repository::at(&primary_path)?;- for &wt_path in removed_worktree_paths {- let wt_at_path = Repository::at(wt_path)?;- let wt_repo = if wt_at_path.load_project_config().ok().flatten().is_some() {- wt_at_path- } else {- primary_repo.clone()- };- let ctx = CommandContext::new(- &wt_repo,- &config,- approve_branch.as_deref(),- wt_path,- yes,- );- if !approve_or_skip(&ctx, &[HookType::PreRemove], decline_msg)? {- return Ok(false);- }+ let commands =+ collect_remove_hook_commands(&primary_repo, removed_worktree_paths)?;+ if commands.is_empty() {+ return Ok(true);}- let ctx = CommandContext::new(- &primary_repo,- &config,- approve_branch.as_deref(),- &primary_path,- yes,- );- approve_or_skip(- &ctx,- &[HookType::PostRemove, HookType::PostSwitch],- decline_msg,- )+ let project_id = repo.project_identifier()?;+ let approvals = Approvals::load().context("Failed to load approvals")?;+ let approved =+ approve_command_batch(&commands, &project_id, &approvals, yes, false)?;+ if !approved {+ eprintln!("{}", info_message("Commands declined, continuing removal"));+ }+ Ok(approved)};let branches = args.branches;