Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(prune): approve each pruned worktree's pre-remove (#2701)
Maximilian Roosf2ae7b7f1d23
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 1636dd771..b2c2eb4dd 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`, the merge destination for `wt merge` | `output::handlers::execute_pre_remove_hooks_if_needed`; approval mirrors it in `main.rs` (`wt remove`) and `merge::collect_merge_commands` (`wt merge`) |-//! | `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`, the primary worktree — the removed/feature worktree is gone by then | `worktree::finish::finish_after_merge`, `output::handlers::spawn_hooks_after_remove` (and `merge::collect_merge_commands` for approval) |+//! | `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` |//! | `pre-switch`, `pre-merge`, `wt hook <type>`, aliases | the worktree `wt` was invoked in (= where they run) | the respective command entry points |@@ -26,8 +26,11 @@//! 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 approved-//! against the exact config they execute against.+//! 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+//! 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/step/prune.rs b/src/commands/step/prune.rsindex 0427b6704..2f7ac9746 100644--- a/src/commands/step/prune.rs+++ b/src/commands/step/prune.rs@@ -10,13 +10,13 @@ use color_print::cformat;use crossbeam_channel as chan;use rayon::prelude::*;use worktrunk::HookType;-use worktrunk::config::UserConfig;+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_or_skip;-use super::super::context::CommandEnv;+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::repository_ext::{RemoveTarget, RepositoryCliExt};use crate::output::handle_remove_output;@@ -382,6 +382,70 @@ fn render_dry_run(Ok(())}+/// Approve the project commands `wt step prune` may run, mirroring the+/// executors' `.config/wt.toml` resolution.+///+/// `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.+///+/// Returns `true` when hooks should run, `false` when the user declined.+fn approve_prune_hooks(+ repo: &Repository,+ worktrees: &[WorktreeInfo],+ check_items: &[CheckItem],+ yes: bool,+) -> anyhow::Result<bool> {+ 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_repo = match Repository::at(&wt.path) {+ Ok(r) if r.load_project_config().ok().flatten().is_some() => r,+ _ => 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()));++ if all_commands.is_empty() {+ return Ok(true);+ }++ let project_id = repo.project_identifier()?;+ let approvals = Approvals::load().context("Failed to load approvals")?;+ let approved = approve_command_batch(&all_commands, &project_id, &approvals, yes, false)?;+ if !approved {+ eprintln!("{}", info_message("Commands declined, continuing removal"));+ }+ Ok(approved)+}+/// Remove worktrees and branches integrated into the default branch.////// Handles four cases: live worktrees with branches (removed + branch deleted),@@ -424,29 +488,23 @@ pub fn step_prune(let default_branch = repo.default_branch();+ // Build the candidate set before approval: `approve_prune_hooks` needs the+ // linked worktrees prune might remove (each `pre-remove` is approved against+ // that worktree's own config). The integration checks below narrow this to+ // the actually-pruned set.+ let check_items = gather_check_items(&repo, worktrees, default_branch.as_deref())?;+// For non-dry-run, approve hooks upfront so we can remove inline.let run_hooks = if dry_run {false // unused in dry-run path} else {- let env = CommandEnv::for_action_branchless()?;- let ctx = env.context(yes);- approve_or_skip(- &ctx,- &[- HookType::PreRemove,- HookType::PostRemove,- HookType::PostSwitch,- ],- "Commands declined, continuing removal",- )?+ approve_prune_hooks(&repo, worktrees, &check_items, yes)?};let mut removed: Vec<Candidate> = Vec::new();let mut deferred_current: Option<Candidate> = None;let mut skipped_young: Vec<String> = Vec::new();- let check_items = gather_check_items(&repo, worktrees, default_branch.as_deref())?;-// Parallel integration checks with inline removals.//// Spawn integration checks on a background thread via rayon par_iter,diff --git a/src/main.rs b/src/main.rsindex 219c4ac7e..770b5e8bb 100644--- a/src/main.rs+++ b/src/main.rs@@ -915,11 +915,11 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {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).unwrap_or_else(|_| repo.clone());+ let primary_repo = Repository::at(&primary_path)?;for &wt_path in removed_worktree_paths {let wt_repo = match Repository::at(wt_path) {Ok(r) if r.load_project_config().ok().flatten().is_some() => r,- _ => primary_repo(),+ _ => primary_repo.clone(),};let ctx = CommandContext::new(&wt_repo,@@ -932,9 +932,8 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {return Ok(false);}}- let pr = primary_repo();let ctx = CommandContext::new(- &pr,+ &primary_repo,&config,approve_branch.as_deref(),&primary_path,diff --git a/tests/integration_tests/approval_pty.rs b/tests/integration_tests/approval_pty.rsindex 6d4943147..2b88b55d7 100644--- a/tests/integration_tests/approval_pty.rs+++ b/tests/integration_tests/approval_pty.rs@@ -428,6 +428,43 @@ fn test_approval_prompt_remove_decline(repo: TestRepo) {});}+#[rstest]+fn test_approval_prompt_prune_decline(mut repo: TestRepo) {+ // Remove origin so worktrunk uses the directory name as the project identifier+ repo.run_git(&["remote", "remove", "origin"]);++ // A merged worktree carrying a `pre-remove` hook in its `.config/wt.toml`+ repo.write_project_config(r#"pre-remove = "echo 'pre-remove hook'""#);+ repo.commit("Add pre-remove config");+ let wt_path = repo.add_worktree("to-prune");++ let env_vars = test_env_vars_with_shell(&repo);++ // Decline the approval prompt — prune continues without running hooks+ let (output, exit_code) = exec_wt_in_pty(+ &repo,+ &["step", "prune", "--foreground", "--min-age=0s"],+ &env_vars,+ "n\n",+ );++ assert_eq!(+ exit_code, 0,+ "prune should succeed even when hooks declined; output:\n{output}"+ );+ assert!(+ output.contains("Commands declined"),+ "should show 'Commands declined' message; output:\n{output}"+ );+ assert!(+ !wt_path.exists(),+ "the merged worktree should still be pruned"+ );+ approval_pty_settings(&repo).bind(|| {+ assert_snapshot!("approval_prompt_prune_decline", &output);+ });+}+#[rstest]fn test_approval_prompt_step_commit_decline(mut repo: TestRepo) {// Remove origin so worktrunk uses directory name as project identifierdiff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rsindex af7f8d716..ed5e92f3e 100644--- a/tests/integration_tests/step_prune.rs+++ b/tests/integration_tests/step_prune.rs@@ -984,3 +984,84 @@ cleanup = "echo done"cmd.env("RAYON_NUM_THREADS", "1");assert_cmd_snapshot!(cmd);}++/// Commit a `pre-remove` hook on the default branch, branch a worktree off that+/// commit (so it carries the hook in its own `.config/wt.toml`), then drop the+/// hook from the default branch and advance past the worktree's commit. The+/// worktree is now integrated (an ancestor of the default branch) and clean,+/// while the cwd config no longer mentions `pre-remove` — the situation where+/// prune would otherwise approve against the wrong config. Returns the+/// worktree path and the marker file the hook writes.+fn prune_branch_local_pre_remove_setup(+ repo: &mut TestRepo,+) -> (std::path::PathBuf, std::path::PathBuf) {+ use path_slash::PathExt as _;++ let marker = repo.root_path().join("prune-pre-remove-ran.txt");+ repo.write_project_config(&format!(+ r#"pre-remove = "echo ran > {}""#,+ marker.to_slash_lossy()+ ));+ repo.commit("Add pre-remove hook");+ let wt_path = repo.add_worktree("merged-with-hook");+ repo.write_project_config("# no hooks on the default branch\n");+ repo.commit("Drop pre-remove hook");+ (wt_path, marker)+}++/// `wt step prune`'s approval covers each pruned worktree's own `pre-remove`,+/// not just the cwd config's. A hook that lives only in a pruned worktree's+/// branch-local `.config/wt.toml` must be approved before it runs — with no TTY+/// and no prior approval, prune aborts rather than running it silently.+#[rstest]+fn test_prune_branch_local_pre_remove_needs_approval(mut repo: TestRepo) {+ let (wt_path, marker) = prune_branch_local_pre_remove_setup(&mut repo);++ let output = repo+ .wt_command()+ .args(["step", "prune", "--foreground", "--min-age=0s"])+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr);++ assert!(+ !output.status.success(),+ "prune should abort when an un-approved branch-local pre-remove is in scope; stderr:\n{stderr}"+ );+ assert!(+ stderr.contains("needs approval") && stderr.contains("pre-remove"),+ "prune should surface the pruned worktree's pre-remove for approval; stderr:\n{stderr}"+ );+ assert!(+ wt_path.exists(),+ "the worktree must not be removed when approval fails"+ );+ assert!(+ !marker.exists(),+ "the pre-remove hook must not run without approval"+ );+}++/// With `--yes`, `wt step prune` runs the approved `pre-remove` hook from each+/// pruned worktree's own `.config/wt.toml`.+#[rstest]+fn test_prune_runs_branch_local_pre_remove_hook(mut repo: TestRepo) {+ use crate::common::wait_for_file_content;++ let (wt_path, marker) = prune_branch_local_pre_remove_setup(&mut repo);++ let output = repo+ .wt_command()+ .args(["step", "prune", "--foreground", "--yes", "--min-age=0s"])+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "wt step prune failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ wait_for_file_content(&marker);+ assert_eq!(std::fs::read_to_string(&marker).unwrap().trim(), "ran");+ assert!(!wt_path.exists(), "the merged worktree should be removed");+}diff --git a/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_prune_decline.snap b/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_prune_decline.snapnew file mode 100644index 000000000..c4ebaacb9--- /dev/null+++ b/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_prune_decline.snap@@ -0,0 +1,13 @@+---+source: tests/integration_tests/approval_pty.rs+expression: "&output"+---+[33m▲[39m [33m[1mrepo[22m needs approval to execute [1m1[22m command:[39m+[2m○[22m pre-remove:+[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'pre-remove hook'[0m[2m++[36m❯[39m [36mAllow and remember? [1m[y/N][22m[39m n+[2m○[22m Commands declined, continuing removal+[36m◎[39m [36mRemoving [1mto-prune[22m worktree...[39m+[1G[2K[32m✓[39m [32mRemoved [1mto-prune[22m worktree & branch (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39m [90m(4 files · [BYTES] B[39m[90m)[39m+[32m✓[39m [32mPruned 1 worktree & branch[39m