Skip to content

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

Add pre-remove hook for cleanup before worktree removal (#107)

Maximilian Roos22698cf182e6
diff --git a/docs/content/hooks.md b/docs/content/hooks.md
index e23311a1a..117fefd9c 100644
--- a/docs/content/hooks.md
+++ b/docs/content/hooks.md
@@ -6,7 +6,7 @@ weight = 21
group = "Reference"
+++
-Hooks automate setup and validation at worktree lifecycle events. They're defined in `.config/wt.toml` (project config) and run automatically during `wt switch --create` and `wt merge`.
+Hooks automate setup and validation at worktree lifecycle events. They're defined in `.config/wt.toml` (project config) and run automatically during `wt switch --create`, `wt merge`, and `wt remove`.
## Hook types
@@ -17,6 +17,7 @@ Hooks automate setup and validation at worktree lifecycle events. They're define
| **pre-commit** | Before commit during merge | Yes | Yes | Sequential |
| **pre-merge** | Before merging to target | Yes | Yes | Sequential |
| **post-merge** | After successful merge | Yes | No | Sequential |
+| **pre-remove** | Before worktree removed | Yes | Yes | Sequential |
**Blocking**: Command waits for hook to complete before continuing.
**Fail-fast**: First failure aborts the operation.
@@ -176,10 +177,30 @@ post-merge = "cargo install --path ."
- Runs after cleanup completes
- Failures show errors but don't affect the completed merge
+### pre-remove
+
+Runs before worktree removal during `wt remove`, **fail-fast**. All commands must exit with code 0 for the removal to proceed.
+
+**Use cases**: Cleanup tasks, saving state, notifying external systems — validation before removal.
+
+```toml
+[pre-remove]
+cleanup = "rm -rf /tmp/cache/{{ branch }}"
+notify = "echo 'Removing {{ branch }}' >> ~/worktree-log.txt"
+```
+
+**Behavior**:
+- Commands run sequentially in the **worktree being removed**
+- First failure aborts the removal (worktree preserved)
+- Runs for both foreground and background removal modes
+- Does **not** run for branch-only removal (no worktree)
+- Use `--no-verify` to skip
+
## When hooks run during merge
- **pre-commit** — After staging, before squash commit
- **pre-merge** — After rebase, before merge to target
+- **pre-remove** — Before removing worktree during cleanup (failures abort)
- **post-merge** — After cleanup completes
See [wt merge](@/merge.md#pipeline) for the complete pipeline.
@@ -226,6 +247,7 @@ Use `--no-verify` to skip all project hooks:
```bash
wt switch --create temp --no-verify # Skip post-create and post-start
wt merge --no-verify # Skip pre-commit, pre-merge, post-merge
+wt remove feature --no-verify # Skip pre-remove
```
## Logging
@@ -247,6 +269,7 @@ Use `wt step` to run individual hooks:
wt step post-create # Run post-create hooks
wt step pre-merge # Run pre-merge hooks
wt step post-merge # Run post-merge hooks
+wt step pre-remove # Run pre-remove hooks
```
## Example configurations
diff --git a/docs/content/merge.md b/docs/content/merge.md
index fc680d055..9313dd18f 100644
--- a/docs/content/merge.md
+++ b/docs/content/merge.md
@@ -52,8 +52,9 @@ wt merge --no-commit
2. **Rebase** — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately.
3. **Pre-merge hooks** — Project commands run after rebase, before merge. Failures abort. See [Hooks](@/hooks.md).
4. **Merge** — Fast-forward merge to the target branch. Non-fast-forward merges are rejected.
-5. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree.
-6. **Post-merge hooks** — Project commands run after cleanup. Failures are logged but don't abort.
+5. **Pre-remove hooks** — Project commands run before removing worktree. Failures abort.
+6. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree.
+7. **Post-merge hooks** — Project commands run after cleanup. Failures are logged but don't abort.
Use `--no-commit` to skip all git operations (steps 1-2) and only run hooks and merge. Useful after preparing commits manually with `wt step`. Requires a clean working tree.
diff --git a/docs/content/remove.md b/docs/content/remove.md
index 70f7d1766..50f9510b8 100644
--- a/docs/content/remove.md
+++ b/docs/content/remove.md
@@ -86,6 +86,9 @@ Options:
--no-background
Run removal in foreground
+ --no-verify
+ Skip pre-remove hooks
+
-h, --help
Print help (see a summary with '-h')
diff --git a/docs/content/step.md b/docs/content/step.md
index 2978f7ea8..c1ebc7172 100644
--- a/docs/content/step.md
+++ b/docs/content/step.md
@@ -75,6 +75,7 @@ Commands:
pre-commit Run pre-commit hook
pre-merge Run pre-merge hook
post-merge Run post-merge hook
+ pre-remove Run pre-remove hook
Options:
-h, --help
diff --git a/src/cli.rs b/src/cli.rs
index 619cf3e19..bd9e81ce4 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -637,6 +637,13 @@ pub enum StepCommand {
#[arg(short, long)]
force: bool,
},
+
+ /// Run pre-remove hook
+ PreRemove {
+ /// Skip approval prompts
+ #[arg(short, long)]
+ force: bool,
+ },
}
/// Subcommands for `wt list`
@@ -1302,6 +1309,10 @@ Arguments resolve by path first, then branch name. [Shortcuts](@/switch.md#short
/// Run removal in foreground
#[arg(long = "no-background", action = clap::ArgAction::SetFalse, default_value_t = true)]
background: bool,
+
+ /// Skip pre-remove hooks
+ #[arg(long = "no-verify", action = clap::ArgAction::SetFalse, default_value_t = true)]
+ verify: bool,
},
/// Merge worktree into target branch
@@ -1350,8 +1361,9 @@ wt merge --no-commit
2. **Rebase** — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately.
3. **Pre-merge hooks** — Project commands run after rebase, before merge. Failures abort. See [Hooks](@/hooks.md).
4. **Merge** — Fast-forward merge to the target branch. Non-fast-forward merges are rejected.
-5. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree.
-6. **Post-merge hooks** — Project commands run after cleanup. Failures are logged but don't abort.
+5. **Pre-remove hooks** — Project commands run before removing worktree. Failures abort.
+6. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree.
+7. **Post-merge hooks** — Project commands run after cleanup. Failures are logged but don't abort.
Use `--no-commit` to skip all git operations (steps 1-2) and only run hooks and merge. Useful after preparing commits manually with `wt step`. Requires a clean working tree.
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 40457e32c..5e4d9d77f 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -209,7 +209,8 @@ pub fn handle_merge(
force_delete: false,
target_branch: Some(target_branch.clone()),
};
- crate::output::handle_remove_output(&remove_result, Some(&current_branch), true)?;
+ // Run hooks during merge removal (verify=true)
+ crate::output::handle_remove_output(&remove_result, Some(&current_branch), true, true)?;
} else {
// Print comprehensive summary (worktree preserved)
// Priority: main worktree > on target > --no-remove flag
@@ -315,3 +316,33 @@ pub fn execute_post_merge_commands(
HookFailureStrategy::Warn,
)
}
+
+/// Execute pre-remove commands sequentially in the worktree (blocking)
+///
+/// Runs before a worktree is removed. Non-zero exit aborts the removal.
+///
+/// # Arguments
+/// * `ctx` - Command context pointing to the worktree being removed
+/// * `auto_trust` - When true, skip approval prompts
+pub fn execute_pre_remove_commands(ctx: &CommandContext, auto_trust: bool) -> anyhow::Result<()> {
+ let project_config = match ctx.repo.load_project_config()? {
+ Some(cfg) => cfg,
+ None => return Ok(()),
+ };
+
+ let Some(pre_remove_config) = &project_config.pre_remove else {
+ return Ok(());
+ };
+
+ let pipeline = HookPipeline::new(*ctx);
+
+ pipeline.run_sequential(
+ pre_remove_config,
+ CommandPhase::PreRemove,
+ auto_trust,
+ &[],
+ "pre-remove",
+ HookType::PreRemove,
+ HookFailureStrategy::FailFast,
+ )
+}
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index e10718cd2..8fdfb263d 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -24,7 +24,7 @@ pub use config::{
pub use configure_shell::{ConfigAction, handle_configure_shell, handle_unconfigure_shell};
pub use init::handle_init;
pub use list::handle_list;
-pub use merge::handle_merge;
+pub use merge::{execute_pre_remove_commands, handle_merge};
#[cfg(unix)]
pub use select::handle_select;
pub use standalone::{
diff --git a/src/commands/project_config.rs b/src/commands/project_config.rs
index 97bf2993c..c66730c8d 100644
--- a/src/commands/project_config.rs
+++ b/src/commands/project_config.rs
@@ -14,6 +14,7 @@ pub fn collect_commands_for_hooks(
HookType::PreCommit => &project_config.pre_commit,
HookType::PreMerge => &project_config.pre_merge,
HookType::PostMerge => &project_config.post_merge,
+ HookType::PreRemove => &project_config.pre_remove,
};
if let Some(config) = cfg {
commands.extend(config.commands_with_phase(*hook));
diff --git a/src/commands/standalone.rs b/src/commands/standalone.rs
index a0a29f05f..3f619e0b7 100644
--- a/src/commands/standalone.rs
+++ b/src/commands/standalone.rs
@@ -7,7 +7,9 @@ use worktrunk::styling::format_with_gutter;
use super::commit::{CommitGenerator, CommitOptions};
use super::context::CommandEnv;
use super::hooks::HookPipeline;
-use super::merge::{execute_post_merge_commands, run_pre_merge_commands};
+use super::merge::{
+ execute_post_merge_commands, execute_pre_remove_commands, run_pre_merge_commands,
+};
use super::project_config::collect_commands_for_hooks;
use super::repository_ext::RepositoryCliExt;
@@ -54,6 +56,10 @@ pub fn handle_standalone_run_hook(hook_type: HookType, force: bool) -> anyhow::R
// branch being merged into)
execute_post_merge_commands(&ctx, &env.branch, false)
}
+ HookType::PreRemove => {
+ check_hook_configured(&project_config.pre_remove, hook_type)?;
+ execute_pre_remove_commands(&ctx, false)
+ }
}
}
diff --git a/src/config/project.rs b/src/config/project.rs
index c3434664a..084da2943 100644
--- a/src/config/project.rs
+++ b/src/config/project.rs
@@ -70,6 +70,14 @@ pub struct ProjectConfig {
#[serde(default, rename = "post-merge")]
pub post_merge: Option<CommandConfig>,
+ /// Commands to execute before a worktree is removed (blocking)
+ /// Supports string (single command) or table (named, sequential)
+ /// Runs in the worktree before removal; non-zero exit aborts removal
+ ///
+ /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ worktree_name }}`, `{{ repo_root }}`, `{{ default_branch }}`, `{{ commit }}`, `{{ short_commit }}`, `{{ remote }}`, `{{ upstream }}`
+ #[serde(default, rename = "pre-remove")]
+ pub pre_remove: Option<CommandConfig>,
+
/// Captures unknown fields for validation warnings
#[serde(flatten, default, skip_serializing)]
unknown: std::collections::HashMap<String, toml::Value>,
diff --git a/src/git/mod.rs b/src/git/mod.rs
index c8743e61b..34beabc2e 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -78,6 +78,7 @@ pub enum HookType {
PreCommit,
PreMerge,
PostMerge,
+ PreRemove,
}
/// Worktree information
diff --git a/src/main.rs b/src/main.rs
index c6ee4bb00..97529ab48 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -818,6 +818,9 @@ fn main() {
StepCommand::PostMerge { force } => {
handle_standalone_run_hook(HookType::PostMerge, force)
}
+ StepCommand::PreRemove { force } => {
+ handle_standalone_run_hook(HookType::PreRemove, force)
+ }
},
#[cfg(unix)]
Commands::Select => handle_select(cli.internal),
@@ -929,6 +932,7 @@ fn main() {
delete_branch,
force_delete,
background,
+ verify,
} => WorktrunkConfig::load()
.context("Failed to load config")
.and_then(|config| {
@@ -944,7 +948,7 @@ fn main() {
// No worktrees specified, remove current worktree
// Uses path-based removal to handle detached HEAD state
let result = handle_remove_current(!delete_branch, force_delete, background)?;
- handle_remove_output(&result, None, background)
+ handle_remove_output(&result, None, background, verify)
} else {
use worktrunk::git::ResolvedWorktree;
@@ -983,12 +987,12 @@ fn main() {
force_delete,
background,
)?;
- handle_remove_output(&result, Some(branch_name), background)?;
+ handle_remove_output(&result, Some(branch_name), background, verify)?;
} else {
// Non-current worktree is detached - remove by path (no branch to delete)
let result =
handle_remove_by_path(path, None, force_delete, background)?;
- handle_remove_output(&result, None, background)?;
+ handle_remove_output(&result, None, background, verify)?;
}
}
@@ -996,14 +1000,14 @@ fn main() {
for branch in &branch_only {
let result =
handle_remove(branch, !delete_branch, force_delete, background)?;
- handle_remove_output(&result, Some(branch), background)?;
+ handle_remove_output(&result, Some(branch), background, verify)?;
}
// Remove current worktree last (if it was in the list)
if let Some((_path, branch)) = current {
let result =
handle_remove_current(!delete_branch, force_delete, background)?;
- handle_remove_output(&result, branch.as_deref(), background)?;
+ handle_remove_output(&result, branch.as_deref(), background, verify)?;
}
Ok(())
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 408af9c9e..183bec633 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -3,8 +3,11 @@
use color_print::cformat;
use std::path::Path;
+use crate::commands::command_executor::CommandContext;
+use crate::commands::execute_pre_remove_commands;
use crate::commands::process::spawn_detached;
use crate::commands::worktree::{RemoveResult, SwitchResult};
+use worktrunk::config::WorktrunkConfig;
use worktrunk::git::GitError;
use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
@@ -364,6 +367,7 @@ pub fn handle_remove_output(
result: &RemoveResult,
branch: Option<&str>,
background: bool,
+ verify: bool,
) -> anyhow::Result<()> {
match result {
RemoveResult::RemovedWorktree {
@@ -384,6 +388,7 @@ pub fn handle_remove_output(
target_branch.as_deref(),
branch,
background,
+ verify,
),
RemoveResult::BranchOnly {
branch_name,
@@ -447,6 +452,7 @@ fn handle_removed_worktree_output(
target_branch: Option<&str>,
branch: Option<&str>,
background: bool,
+ verify: bool,
) -> anyhow::Result<()> {
// 1. Emit cd directive if needed - shell will execute this immediately
if changed_directory {
@@ -482,6 +488,21 @@ fn handle_removed_worktree_output(
return Ok(());
};
+ // Execute pre-remove hooks in the worktree being removed
+ // Non-zero exit aborts removal (FailFast strategy)
+ if verify && let Ok(config) = WorktrunkConfig::load() {
+ let target_repo = Repository::at(worktree_path);
+ let ctx = CommandContext::new(
+ &target_repo,
+ &config,
+ branch_name,
+ worktree_path,
+ main_path,
+ false, // force=false, prompt for approval
+ );
+ execute_pre_remove_commands(&ctx, false)?;
+ }
+
if background {
// Background mode: spawn detached process
@@ -589,6 +610,7 @@ fn handle_removed_worktree_output(
integration_reason,
target_branch,
))?;
+
super::flush()?;
Ok(())
}
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
index e2fd116a8..fba5d8dc0 100644
--- a/tests/integration_tests/completion.rs
+++ b/tests/integration_tests/completion.rs
@@ -707,10 +707,11 @@ fn test_complete_step_subcommands() {
assert!(subcommands.contains(&"pre-commit"), "Missing pre-commit");
assert!(subcommands.contains(&"pre-merge"), "Missing pre-merge");
assert!(subcommands.contains(&"post-merge"), "Missing post-merge");
+ assert!(subcommands.contains(&"pre-remove"), "Missing pre-remove");
assert_eq!(
subcommands.len(),
- 9,
- "Should have exactly 9 step subcommands"
+ 10,
+ "Should have exactly 10 step subcommands"
);
// Test 2: Partial input "po" - filters to post-* subcommands
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 53780ae9b..18249f6b9 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -5,6 +5,7 @@ use crate::common::{
use insta_cmd::assert_cmd_snapshot;
use std::path::PathBuf;
use std::process::Command;
+use std::time::Duration;
use tempfile::TempDir;
/// Helper to create snapshot with normalized paths
@@ -715,3 +716,272 @@ fn test_remove_squash_merged_then_main_advanced() {
None,
);
}
+
+// ============================================================================
+// Pre-Remove Hook Tests
+// ============================================================================
+
+/// Test pre-remove hook executes before worktree removal.
+#[test]
+fn test_pre_remove_hook_executes() {
+ // Use simple repo without remote for predictable project ID
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create project config with pre-remove hook
+ repo.write_project_config(r#"pre-remove = "echo 'About to remove worktree'""#);
+ repo.commit("Add config");
+
+ // Pre-approve the command
+ repo.write_test_config(
+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"
+
+[projects."repo"]
+approved-commands = ["echo 'About to remove worktree'"]
+"#,
+ );
+
+ // Create a worktree to remove
+ let _worktree_path = repo.add_worktree("feature-hook");
+
+ // Remove with --no-background to ensure synchronous execution
+ snapshot_remove(
+ "pre_remove_hook_executes",
+ &repo,
+ &["--no-background", "feature-hook"],
+ None,
+ );
+}
+
+/// Test pre-remove hook has access to template variables.
+#[test]
+fn test_pre_remove_hook_template_variables() {
+ // Use simple repo without remote for predictable project ID
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create project config with template variables
+ repo.write_project_config(
+ r#"[pre-remove]
+branch = "echo 'Branch: {{ branch }}'"
+worktree = "echo 'Worktree: {{ worktree }}'"
+worktree_name = "echo 'Name: {{ worktree_name }}'"
+"#,
+ );
+ repo.commit("Add config with templates");
+
+ // Pre-approve the commands (use expanded forms for approval)
+ repo.write_test_config(
+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"
+
+[projects."repo"]
+approved-commands = [
+ "echo 'Branch: {{ branch }}'",
+ "echo 'Worktree: {{ worktree }}'",
+ "echo 'Name: {{ worktree_name }}'",
+]
+"#,
+ );
+
+ // Create a worktree to remove
+ let _worktree_path = repo.add_worktree("feature-templates");
+
+ // Remove with --no-background
+ snapshot_remove(
+ "pre_remove_hook_template_variables",
+ &repo,
+ &["--no-background", "feature-templates"],
+ None,
+ );
+}
+
+/// Test pre-remove hook runs even in background mode (before spawning background process).
+#[test]
+fn test_pre_remove_hook_runs_in_background_mode() {
+ use crate::common::wait_for_file;
+
+ // Use simple repo without remote for predictable project ID
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create a marker file that the hook will create
+ let marker_file = repo.root_path().join("hook-ran.txt");
+
+ // Create project config with hook that creates a file
+ repo.write_project_config(&format!(
+ r#"pre-remove = "echo 'hook ran' > {}""#,
+ marker_file.to_string_lossy().replace('\\', "/")
+ ));
+ repo.commit("Add config");
+
+ // Pre-approve the command
+ repo.write_test_config(&format!(
+ r#"worktree-path = "../{{{{ main_worktree }}}}.{{{{ branch }}}}"
+
+[projects."repo"]
+approved-commands = ["echo 'hook ran' > {}"]
+"#,
+ marker_file.to_string_lossy().replace('\\', "/")
+ ));
+
+ // Create a worktree to remove
+ let _worktree_path = repo.add_worktree("feature-bg");
+
+ // Remove in background mode (default)
+ let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_wt"));
+ repo.clean_cli_env(&mut cmd);
+ cmd.current_dir(repo.root_path())
+ .args(["remove", "feature-bg"])
+ .output()
+ .unwrap();
+
+ // Wait for the hook to create the marker file
+ wait_for_file(&marker_file, Duration::from_secs(5));
+
+ // Marker file SHOULD exist - pre-remove hooks run before background removal starts
+ assert!(
+ marker_file.exists(),
+ "Pre-remove hook should run even in background mode"
+ );
+}
+
+/// Test pre-remove hook failure aborts removal (FailFast strategy).
+#[test]
+fn test_pre_remove_hook_failure_aborts() {
+ // Use simple repo without remote for predictable project ID
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create project config with failing hook
+ repo.write_project_config(r#"pre-remove = "exit 1""#);
+ repo.commit("Add config");
+
+ // Pre-approve the command
+ repo.write_test_config(
+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"
+
+[projects."repo"]
+approved-commands = ["exit 1"]
+"#,
+ );
+
+ // Create a worktree to remove
+ let worktree_path = repo.add_worktree("feature-fail");
+
+ // Remove - should FAIL due to hook failure
+ snapshot_remove(
+ "pre_remove_hook_failure_aborts",
+ &repo,
+ &["--no-background", "feature-fail"],
+ None,
+ );
+
+ // Verify worktree was NOT removed (hook failure aborted removal)
+ assert!(
+ worktree_path.exists(),
+ "Worktree should NOT be removed when hook fails"
+ );
+}
+
+/// Test pre-remove hook does NOT run for branch-only removal (no worktree).
+#[test]
+fn test_pre_remove_hook_not_for_branch_only() {
+ // Use simple repo without remote for predictable project ID
+ let repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create a marker file that the hook would create
+ let marker_file = repo.root_path().join("branch-only-hook.txt");
+
+ // Create project config with hook
+ repo.write_project_config(&format!(
+ r#"pre-remove = "echo 'hook ran' > {}""#,
+ marker_file.to_string_lossy().replace('\\', "/")
+ ));
+ repo.commit("Add config");
+
+ // Pre-approve the command
+ repo.write_test_config(&format!(
+ r#"worktree-path = "../{{{{ main_worktree }}}}.{{{{ branch }}}}"
+
+[projects."repo"]
+approved-commands = ["echo 'hook ran' > {}"]
+"#,
+ marker_file.to_string_lossy().replace('\\', "/")
+ ));
+
+ // Create a branch without a worktree
+ repo.git_command(&["branch", "branch-only"])
+ .output()
+ .unwrap();
+
+ // Remove the branch (no worktree)
+ let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_wt"));
+ repo.clean_cli_env(&mut cmd);
+ cmd.current_dir(repo.root_path())
+ .args(["remove", "branch-only"])
+ .output()
+ .unwrap();
+
+ // Marker file should NOT exist - pre-remove hooks only run for worktree removal
+ assert!(
+ !marker_file.exists(),
+ "Pre-remove hook should NOT run for branch-only removal"
+ );
+}
+
+/// Test --no-verify flag skips pre-remove hooks.
+#[test]
+fn test_pre_remove_hook_skipped_with_no_verify() {
+ use std::thread;
+
+ // Use simple repo without remote for predictable project ID
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create a marker file that the hook would create
+ let marker_file = repo.root_path().join("should-not-exist.txt");
+
+ // Create project config with hook that creates a file
+ repo.write_project_config(&format!(
+ r#"pre-remove = "echo 'hook ran' > {}""#,
+ marker_file.to_string_lossy().replace('\\', "/")
+ ));
+ repo.commit("Add config");
+
+ // Pre-approve the command (even though it shouldn't run)
+ repo.write_test_config(&format!(
+ r#"worktree-path = "../{{{{ main_worktree }}}}.{{{{ branch }}}}"
+
+[projects."repo"]
+approved-commands = ["echo 'hook ran' > {}"]
+"#,
+ marker_file.to_string_lossy().replace('\\', "/")
+ ));
+
+ // Create a worktree to remove
+ let worktree_path = repo.add_worktree("feature-skip");
+
+ // Remove with --no-verify to skip hooks
+ snapshot_remove(
+ "pre_remove_hook_skipped_with_no_verify",
+ &repo,
+ &["--no-background", "--no-verify", "feature-skip"],
+ None,
+ );
+
+ // Wait a bit for any potential hook execution
+ thread::sleep(Duration::from_millis(100));
+
+ // Marker file should NOT exist - --no-verify skips the hook
+ assert!(
+ !marker_file.exists(),
+ "Pre-remove hook should NOT run with --no-verify"
+ );
+
+ // Worktree should be removed (removal itself succeeds)
+ assert!(
+ !worktree_path.exists(),
+ "Worktree should be removed even with --no-verify"
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__help__help_merge_long.snap b/tests/snapshots/integration__integration_tests__help__help_merge_long.snap
index 74a21f3c3..4b1242471 100644
--- a/tests/snapshots/integration__integration_tests__help__help_merge_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_merge_long.snap
@@ -97,8 +97,9 @@ Skip git operations, only run hooks and push:
2. Rebase — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately.
3. Pre-merge hooks — Project commands run after rebase, before merge. Failures abort. See Hooks.
4. Merge — Fast-forward merge to the target branch. Non-fast-forward merges are rejected.
-5. Cleanup — Removes the worktree and branch. Use --no-remove to keep the worktree.
-6. Post-merge hooks — Project commands run after cleanup. Failures are logged but don't abort.
+5. Pre-remove hooks — Project commands run before removing worktree. Failures abort.
+6. Cleanup — Removes the worktree and branch. Use --no-remove to keep the worktree.
+7. Post-merge hooks — Project commands run after cleanup. Failures are logged but don't abort.
Use --no-commit to skip all git operations (steps 1-2) and only run hooks and merge. Useful after preparing commits manually with wt step. Requires a clean working tree.
diff --git a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
index 97cb599fd..c5bd9dcdc 100644
--- a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
@@ -34,6 +34,9 @@ Usage: wt remove [OPTIONS] [WORKTREES]...
--no-background
Run removal in foreground
+ --no-verify
+ Skip pre-remove hooks
+
-h, --help
Print help (see a summary with '-h')
diff --git a/tests/snapshots/integration__integration_tests__help__help_remove_short.snap b/tests/snapshots/integration__integration_tests__help__help_remove_short.snap
index 20686b04f..96530694b 100644
--- a/tests/snapshots/integration__integration_tests__help__help_remove_short.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_remove_short.snap
@@ -27,6 +27,7 @@ Usage: wt remove [OPTIONS] [WORKTREES]...
--no-delete-branch Keep branch after removal
-D, --force-delete Delete unmerged branches
--no-background Run removal in foreground
+ --no-verify Skip pre-remove hooks
-h, --help Print help (see more with '--help')
Global Options:
diff --git a/tests/snapshots/integration__integration_tests__help__help_step_long.snap b/tests/snapshots/integration__integration_tests__help__help_step_long.snap
index 03dd97663..6e719ee0f 100644
--- a/tests/snapshots/integration__integration_tests__help__help_step_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_step_long.snap
@@ -30,6 +30,7 @@ Usage: wt step [OPTIONS] <COMMAND>
pre-commit Run pre-commit hook
pre-merge Run pre-merge hook
post-merge Run post-merge hook
+ pre-remove Run pre-remove hook
Options:
-h, --help
diff --git a/tests/snapshots/integration__integration_tests__help__help_step_short.snap b/tests/snapshots/integration__integration_tests__help__help_step_short.snap
index 387b80c86..730b2db10 100644
--- a/tests/snapshots/integration__integration_tests__help__help_step_short.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_step_short.snap
@@ -30,6 +30,7 @@ Usage: wt step [OPTIONS] <COMMAND>
pre-commit Run pre-commit hook
pre-merge Run pre-merge hook
post-merge Run post-merge hook
+ pre-remove Run pre-remove hook
Options:
-h, --help Print help (see more with '--help')
diff --git a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_executes.snap b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_executes.snap
new file mode 100644
index 000000000..1269aa611
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_executes.snap
@@ -0,0 +1,31 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - "--no-background"
+ - feature-hook
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1735776000"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+🔄 Removing worktree for feature-hook...
+🔄 Running pre-remove:
+  echo 'About to remove worktree'
+About to remove worktree
+✅ Removed feature-hook worktree & branch (already in main)
diff --git a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_failure_aborts.snap b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_failure_aborts.snap
new file mode 100644
index 000000000..fdebf022b
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_failure_aborts.snap
@@ -0,0 +1,32 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - "--no-background"
+ - feature-fail
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1735776000"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+🔄 Removing worktree for feature-fail...
+🔄 Running pre-remove:
+  exit 1
+❌ pre-remove command failed: exit status: 1
+
+💡 Use --no-verify to skip pre-remove commands
diff --git a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_skipped_with_no_verify.snap b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_skipped_with_no_verify.snap
new file mode 100644
index 000000000..2d77e1f7c
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_skipped_with_no_verify.snap
@@ -0,0 +1,29 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - "--no-background"
+ - "--no-verify"
+ - feature-skip
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1735776000"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+🔄 Removing worktree for feature-skip...
+✅ Removed feature-skip worktree & branch (already in main)
diff --git a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_template_variables.snap b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_template_variables.snap
new file mode 100644
index 000000000..e6d78e2fd
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_template_variables.snap
@@ -0,0 +1,37 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - "--no-background"
+ - feature-templates
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1735776000"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+🔄 Removing worktree for feature-templates...
+🔄 Running pre-remove branch:
+  echo 'Branch: feature-templates'
+Branch: feature-templates
+🔄 Running pre-remove worktree:
+  echo 'Worktree: [REPO].feature-templates'
+Worktree: [REPO].feature-templates
+🔄 Running pre-remove worktree_name:
+  echo 'Name: repo.feature-templates'
+Name: repo.feature-templates
+✅ Removed feature-templates worktree & branch (already in main)