Skip to content

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

Run pre-remove hooks for detached HEAD worktrees

Maximilian Roosf6c7a7f83943
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 666b613d1..02643b41a 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -462,6 +462,23 @@ fn handle_removed_worktree_output(
let repo = worktrunk::git::Repository::current();
+ // Execute pre-remove hooks in the worktree being removed
+ // Non-zero exit aborts removal (FailFast strategy)
+ // For detached HEAD, branch expands to empty string in templates
+ if verify && let Ok(config) = WorktrunkConfig::load() {
+ let target_repo = Repository::at(worktree_path);
+ let hook_branch = branch_name.unwrap_or("");
+ let ctx = CommandContext::new(
+ &target_repo,
+ &config,
+ hook_branch,
+ worktree_path,
+ main_path,
+ false, // force=false, prompt for approval
+ );
+ execute_pre_remove_commands(&ctx, false)?;
+ }
+
// Handle detached HEAD case (no branch known)
let Some(branch_name) = branch_name else {
// No branch associated - just remove the worktree
@@ -495,21 +512,6 @@ 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
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 2e94c8ce8..2faa734fb 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -1023,3 +1023,105 @@ approved-commands = ["echo 'hook ran' > {}"]
"Worktree should be removed even with --no-verify"
);
}
+
+/// Test that pre-remove hook runs for detached HEAD worktrees.
+///
+/// Even when a worktree is in detached HEAD state (no branch), the pre-remove
+/// hook should still execute. The `{{ branch }}` template variable expands to empty string.
+#[test]
+fn test_pre_remove_hook_runs_for_detached_head() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create marker file path in the repo root
+ let marker_file = repo.root_path().join("detached-hook-marker.txt");
+ let branch_file = repo.root_path().join("detached-hook-branch.txt");
+
+ // Create project config with pre-remove hook that creates marker files
+ let marker_path = marker_file.to_string_lossy().replace('\\', "/");
+ let branch_path = branch_file.to_string_lossy().replace('\\', "/");
+ repo.write_project_config(&format!(
+ r#"pre-remove = "touch {marker_path} && echo 'branch={{{{ branch }}}}' > {branch_path}""#,
+ ));
+ repo.commit("Add config");
+
+ // Pre-approve the commands
+ repo.write_test_config(&format!(
+ r#"worktree-path = "../{{{{ main_worktree }}}}.{{{{ branch }}}}"
+
+[projects."repo"]
+approved-commands = ["touch {marker_path} && echo 'branch={{{{ branch }}}}' > {branch_path}"]
+"#,
+ ));
+
+ // Create a worktree and detach HEAD
+ let worktree_path = repo.add_worktree("feature-detached-hook");
+ repo.detach_head_in_worktree("feature-detached-hook");
+
+ // Remove with --no-background to ensure synchronous execution
+ snapshot_remove(
+ "pre_remove_hook_runs_for_detached_head",
+ &repo,
+ &["--no-background"],
+ Some(&worktree_path),
+ );
+
+ // Marker file should exist - hook ran
+ assert!(
+ marker_file.exists(),
+ "Pre-remove hook should run for detached HEAD worktrees"
+ );
+
+ // Check that {{ branch }} expanded to empty string
+ let branch_content = std::fs::read_to_string(&branch_file).unwrap();
+ assert_eq!(
+ branch_content.trim(),
+ "branch=",
+ "{{ branch }} should expand to empty string for detached HEAD worktrees"
+ );
+}
+
+/// Test that pre-remove hook runs for detached HEAD worktrees in background mode.
+///
+/// This complements `test_pre_remove_hook_runs_for_detached_head` by verifying
+/// the hook also runs when removal happens in background (the default).
+#[test]
+fn test_pre_remove_hook_runs_for_detached_head_background() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create marker file path in the repo root
+ let marker_file = repo.root_path().join("detached-bg-hook-marker.txt");
+
+ // Create project config with pre-remove hook that creates a marker file
+ let marker_path = marker_file.to_string_lossy().replace('\\', "/");
+ repo.write_project_config(&format!(r#"pre-remove = "touch {marker_path}""#,));
+ repo.commit("Add config");
+
+ // Pre-approve the commands
+ repo.write_test_config(&format!(
+ r#"worktree-path = "../{{{{ main_worktree }}}}.{{{{ branch }}}}"
+
+[projects."repo"]
+approved-commands = ["touch {marker_path}"]
+"#,
+ ));
+
+ // Create a worktree and detach HEAD
+ let worktree_path = repo.add_worktree("feature-detached-bg");
+ repo.detach_head_in_worktree("feature-detached-bg");
+
+ // Remove in background mode (default)
+ snapshot_remove(
+ "pre_remove_hook_runs_for_detached_head_background",
+ &repo,
+ &[],
+ Some(&worktree_path),
+ );
+
+ // Marker file should exist - hook ran before background spawn
+ assert!(
+ marker_file.exists(),
+ "Pre-remove hook should run for detached HEAD worktrees in background mode"
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_runs_for_detached_head.snap b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_runs_for_detached_head.snap
new file mode 100644
index 000000000..35adccb62
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_runs_for_detached_head.snap
@@ -0,0 +1,30 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - "--no-background"
+ 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 current worktree...
+πŸ”„ Running pre-remove:
+  touch [REPO]/detached-hook-marker.txt && echo 'branch=''' >
+  [REPO]/detached-hook-branch.txt
+βœ… Removed worktree (detached HEAD, no branch to delete)
diff --git a/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_runs_for_detached_head_background.snap b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_runs_for_detached_head_background.snap
new file mode 100644
index 000000000..516d387c0
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__pre_remove_hook_runs_for_detached_head_background.snap
@@ -0,0 +1,27 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ 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 -----
+πŸ”„ Running pre-remove:
+  touch [REPO]/detached-bg-hook-marker.txt
+πŸ”„ Removing worktree in background (detached HEAD, no branch to delete)