Skip to content

Conversation

@Cl3MM
Copy link

@Cl3MM Cl3MM commented Jan 13, 2026

Add support for cleanup-worktree scripts that run automatically when removing a worktree with wt remove.

Summary

  • Add cleanup-worktree array support in worktrees.json for automatic cleanup before worktree removal
  • Scripts execute automatically when using wt remove
  • Add --skip-cleanup (-s) option to bypass cleanup scripts
  • Add --trust (-t) option for CI environments (no confirmation)
  • Add runCleanupScriptsSecure() function to src/utils/setup.ts
  • Extract shared script execution logic to src/utils/scripts.ts (removes code duplication from setup.ts)
  • Use same security filters as setup-worktree (dangerous commands blocked)
  • Update README with cleanup documentation

Example worktrees.json

{
  "setup-worktree": ["npm install"],
  "cleanup-worktree": ["docker-compose down", "rm -rf node_modules"]
}

Usage

wt remove my-branch # Runs cleanup scripts, then removes worktree
wt remove my-branch -s # Skips cleanup scripts
wt remove my-branch --force # Force removal (for untracked files)

Test plan

[x] wt setup still executes setup-worktree scripts correctly
[x] wt remove executes cleanup-worktree scripts before removal
[x] wt remove --skip-cleanup bypasses cleanup scripts
[x] wt remove --force works with untracked files
[x] Security filters block dangerous commands in cleanup scripts
[x] pnpm build compiles without errors

Summary by CodeRabbit

Release Notes

  • New Features

    • Added cleanup-worktree scripts support: Define cleanup commands in worktrees.json to execute before removing a worktree.
    • New CLI options for remove command:
      • -s, --skip-cleanup: Skip cleanup script execution.
      • -t, --trust: Run cleanup without user confirmation (ideal for CI/CD environments).
    • Cleanup scripts run with user confirmation by default before worktree removal.
  • Documentation

    • Updated README with cleanup configuration examples and new CLI option details.

✏️ Tip: You can customize this high-level summary in your review settings.

Add support for cleanup-worktree scripts that run automatically when
removing a worktree with wt remove.

Changes:
- Add cleanup-worktree array support in worktrees.json
- Scripts execute automatically before worktree removal (with confirmation)
- Add --skip-cleanup (-s) option to bypass cleanup scripts
- Add --trust (-t) option for CI environments (no confirmation)
- Add runCleanupScriptsSecure() function to src/utils/setup.ts
- Update README with cleanup documentation

Example worktrees.json:
{
  "setup-worktree": ["npm install"],
  "cleanup-worktree": ["docker-compose down"]
}
@coderabbitai
Copy link

coderabbitai bot commented Jan 13, 2026

📝 Walkthrough

Walkthrough

This PR introduces cleanup script execution for worktree removal. Users can define cleanup-worktree commands in worktrees.json that execute before worktree removal with optional confirmation. Two new CLI flags (--skip-cleanup, --trust) control cleanup behavior. Documentation, CLI configuration, and two new utility functions (loadCleanupCommands, runCleanupScriptsSecure) support the feature.

Changes

Cohort / File(s) Summary
Documentation
README.md
Adds "Cleanup Worktree Configuration" section documenting cleanup-worktree array, new -s/--skip-cleanup and -t/--trust removal flags, execution flow, environment variables, and CI integration
CLI Configuration
src/index.ts, build/index.js
Introduces -s/--skip-cleanup and -t/--trust boolean options for remove command; updates description to reference cleanup-worktree scripts from worktrees.json
Cleanup Utilities
src/utils/setup.ts, build/utils/setup.js
Adds loadCleanupCommands(repoRoot) to locate and load cleanup-worktree commands from worktrees.json; adds runCleanupScriptsSecure(worktreePath, options) for secure execution with user confirmation (bypassed with --trust) and per-command error handling; extends WorktreeSetupData interface with optional cleanup-worktree field
Remove Command
src/commands/remove.ts, build/commands/remove.js
Integrates cleanup script execution before git worktree removal; extends removeWorktreeHandler options with skipCleanup and trust flags; executes runCleanupScriptsSecure unless skipCleanup is set

Sequence Diagram

sequenceDiagram
    participant User
    participant RemoveCmd as Remove Command
    participant CleanupUtil as Cleanup Utility
    participant Worktree as Git Worktree
    
    User->>RemoveCmd: remove [path] [--skip-cleanup] [--trust]
    alt skip-cleanup not set
        RemoveCmd->>CleanupUtil: loadCleanupCommands(repoRoot)
        CleanupUtil-->>RemoveCmd: cleanup commands + filePath
        alt trust not set
            RemoveCmd->>User: Confirm cleanup execution?
            User-->>RemoveCmd: Yes/No
        end
        RemoveCmd->>CleanupUtil: Execute cleanup commands in worktree
        CleanupUtil->>Worktree: Run each cleanup command
        CleanupUtil-->>RemoveCmd: Cleanup complete (with error handling)
    end
    RemoveCmd->>Worktree: git worktree remove [path]
    Worktree-->>RemoveCmd: Worktree removed
    RemoveCmd-->>User: Success
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 Hoppy cleanup time has come,
Before the worktrees say goodbye,
We scrub and sweep, then trust or run,
With scripts defined and files to tie!

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main feature: adding automatic cleanup scripts that run on worktree removal, which is the core functionality across all changed files.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

🧹 Recent nitpick comments
src/utils/setup.ts (1)

217-244: Cleaner implementation pattern than loadSetupCommands.

The loop-based approach here is more maintainable than the duplicated try/catch blocks in loadSetupCommands. Consider refactoring loadSetupCommands to use a similar pattern for consistency.

README.md (1)

157-173: Documentation is clear and comprehensive.

The new cleanup configuration section follows the established patterns from the setup documentation. The examples are practical and cover the key use cases.

Minor formatting suggestion: On line 172, $ROOT_WORKTREE_PATH should be rendered in code format (backticks) for consistency with line 371 in the setup section.

📝 Suggested improvement
 Cleanup behavior:
 - **Automatic execution**: Runs before `wt remove` (after confirmation)
 - **Skip option**: Use `--skip-cleanup` or `-s` to bypass
 - **Trust mode**: Use `--trust` to run without confirmation (CI environments)
-- **Environment variables**: `$ROOT_WORKTREE_PATH` is available
+- **Environment variables**: `ROOT_WORKTREE_PATH` is available
📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1301994 and 5ad8d28.

📒 Files selected for processing (7)
  • README.md
  • build/commands/remove.js
  • build/index.js
  • build/utils/setup.js
  • src/commands/remove.ts
  • src/index.ts
  • src/utils/setup.ts
🧰 Additional context used
📓 Path-based instructions (3)
src/index.ts

📄 CodeRabbit inference engine (.cursor/rules/project.mdc)

src/index.ts: The main entry point for the CLI is src/index.ts, which sets up CLI commands and orchestrates command handlers.
Utilize Commander for parsing CLI commands and handling options.

Files:

  • src/index.ts
src/commands/remove.ts

📄 CodeRabbit inference engine (.cursor/rules/project.mdc)

Handle removal of Git worktrees, including support for force deletion, in src/commands/remove.ts.

Files:

  • src/commands/remove.ts
src/commands/*.ts

📄 CodeRabbit inference engine (.cursor/rules/project.mdc)

src/commands/*.ts: Leverage Execa to execute Git commands and other external processes.
Provide clear, colored console feedback for success and error messages in CLI commands.

Files:

  • src/commands/remove.ts
🧠 Learnings (6)
📓 Common learnings
Learnt from: CR
Repo: johnlindquist/worktree-cli PR: 0
File: .cursor/rules/project.mdc:0-0
Timestamp: 2025-08-04T13:02:29.847Z
Learning: Applies to src/commands/remove.ts : Handle removal of Git worktrees, including support for force deletion, in src/commands/remove.ts.
Learnt from: CR
Repo: johnlindquist/worktree-cli PR: 0
File: .cursor/rules/project.mdc:0-0
Timestamp: 2025-08-04T13:02:29.847Z
Learning: Applies to src/commands/new.ts : Implement logic for creating new Git worktrees, including options for branch creation, dependency installation, and opening in an editor, in src/commands/new.ts.
Learnt from: CR
Repo: johnlindquist/worktree-cli PR: 0
File: .cursor/rules/project.mdc:0-0
Timestamp: 2025-08-04T13:02:29.847Z
Learning: Applies to src/commands/list.ts : Provide functionality to list existing Git worktrees in src/commands/list.ts.
Learnt from: juristr
Repo: johnlindquist/worktree-cli PR: 20
File: src/commands/extract.ts:124-127
Timestamp: 2025-08-04T14:22:29.156Z
Learning: The worktree-cli project prioritizes consistency across commands. When implementing new commands like `extract`, developers follow existing patterns from similar commands like `new` to maintain API and implementation consistency.
📚 Learning: 2025-08-04T13:02:29.847Z
Learnt from: CR
Repo: johnlindquist/worktree-cli PR: 0
File: .cursor/rules/project.mdc:0-0
Timestamp: 2025-08-04T13:02:29.847Z
Learning: Applies to src/commands/remove.ts : Handle removal of Git worktrees, including support for force deletion, in src/commands/remove.ts.

Applied to files:

  • build/commands/remove.js
  • src/index.ts
  • build/utils/setup.js
  • src/utils/setup.ts
  • README.md
  • build/index.js
  • src/commands/remove.ts
📚 Learning: 2025-08-04T13:02:29.847Z
Learnt from: CR
Repo: johnlindquist/worktree-cli PR: 0
File: .cursor/rules/project.mdc:0-0
Timestamp: 2025-08-04T13:02:29.847Z
Learning: Applies to src/commands/list.ts : Provide functionality to list existing Git worktrees in src/commands/list.ts.

Applied to files:

  • build/commands/remove.js
  • src/index.ts
  • build/utils/setup.js
  • src/utils/setup.ts
  • README.md
  • build/index.js
  • src/commands/remove.ts
📚 Learning: 2025-08-04T13:02:29.847Z
Learnt from: CR
Repo: johnlindquist/worktree-cli PR: 0
File: .cursor/rules/project.mdc:0-0
Timestamp: 2025-08-04T13:02:29.847Z
Learning: Applies to src/commands/new.ts : Implement logic for creating new Git worktrees, including options for branch creation, dependency installation, and opening in an editor, in src/commands/new.ts.

Applied to files:

  • build/commands/remove.js
  • src/index.ts
  • build/utils/setup.js
  • src/utils/setup.ts
  • README.md
  • build/index.js
  • src/commands/remove.ts
📚 Learning: 2025-08-04T14:22:29.156Z
Learnt from: juristr
Repo: johnlindquist/worktree-cli PR: 20
File: src/commands/extract.ts:124-127
Timestamp: 2025-08-04T14:22:29.156Z
Learning: The worktree-cli project prioritizes consistency across commands. When implementing new commands like `extract`, developers follow existing patterns from similar commands like `new` to maintain API and implementation consistency.

Applied to files:

  • src/index.ts
  • build/utils/setup.js
  • src/utils/setup.ts
  • README.md
  • build/index.js
  • src/commands/remove.ts
📚 Learning: 2025-08-04T13:02:29.847Z
Learnt from: CR
Repo: johnlindquist/worktree-cli PR: 0
File: .cursor/rules/project.mdc:0-0
Timestamp: 2025-08-04T13:02:29.847Z
Learning: Applies to src/commands/*.ts : Leverage Execa to execute Git commands and other external processes.

Applied to files:

  • src/utils/setup.ts
🧬 Code graph analysis (3)
build/commands/remove.js (1)
src/utils/setup.ts (1)
  • runCleanupScriptsSecure (256-301)
src/utils/setup.ts (3)
build/utils/setup.js (15)
  • repoRoot (70-70)
  • repoRoot (122-122)
  • repoRoot (235-235)
  • paths (202-205)
  • commands (19-19)
  • commands (39-39)
  • commands (154-154)
  • commands (212-212)
  • runCleanupScriptsSecure (234-272)
  • cleanupResult (239-239)
  • shouldRun (81-84)
  • shouldRun (245-248)
  • env (90-90)
  • env (167-167)
  • env (254-254)
src/utils/git.ts (1)
  • getRepoRoot (154-162)
src/utils/tui.ts (1)
  • confirmCommands (162-180)
src/commands/remove.ts (1)
src/utils/setup.ts (1)
  • runCleanupScriptsSecure (256-301)
🔇 Additional comments (9)
src/utils/setup.ts (2)

10-14: LGTM! Clean interface extension.

The addition of the optional cleanup-worktree property to WorktreeSetupData is well-typed and backward-compatible with existing config files.


256-301: Good implementation following established patterns.

The function correctly mirrors runSetupScriptsSecure with appropriate messaging changes. The continue-on-failure behavior (lines 290-297) is appropriate for cleanup workflows.

Minor consideration: The PR description mentions "security filters to block dangerous commands" but the actual security model here is confirmation-based prompting. This is a reasonable approach, but ensure the documentation accurately reflects this trust model rather than implying command filtering.

build/utils/setup.js (1)

198-272: Build output matches TypeScript source.

This is the transpiled JavaScript from src/utils/setup.ts. The generated code correctly implements the cleanup functionality.

build/index.js (1)

47-49: LGTM! CLI options are well-defined and consistent.

The new options follow established patterns:

  • -s, --skip-cleanup matches the naming convention for skip flags
  • -t, --trust is consistent with the existing setup command's trust flag (line 34)

Good consistency with the project's existing API patterns. Based on learnings, this project prioritizes consistency across commands.

build/commands/remove.js (1)

74-77: Correct integration of cleanup scripts.

The cleanup phase is properly positioned:

  1. After user confirmation (line 68)
  2. Before actual worktree removal (line 80)

This ensures cleanup scripts run in a confirmed context but can still access the worktree files before deletion.

src/commands/remove.ts (2)

8-12: LGTM! Clean integration with proper typing.

The import and options type extension are well-structured. The optional properties with ?: ensure backward compatibility with existing call sites.


89-92: Cleanup integration is correctly implemented.

The cleanup script execution:

  • Runs only when skipCleanup is falsy (default behavior)
  • Passes trust option through to avoid double-prompting in CI
  • Awaits completion but doesn't block removal on failure (correct for cleanup semantics)

This follows the coding guidelines for clear, colored console feedback (handled within runCleanupScriptsSecure). Based on learnings, this handles removal of Git worktrees with appropriate support for the new cleanup feature.

src/index.ts (1)

87-100: LGTM! CLI options are well-structured and follow existing patterns.

The -t/--trust option maintains consistency with the setup and pr commands. The updated description clearly communicates the new cleanup behavior.

Minor note: The -s shorthand has different meanings across commands (--setup in pr, --skip-cleanup in remove). This is acceptable since they're different subcommands, but worth being aware of for user documentation.

README.md (1)

140-155: LGTM! Documentation clearly explains the new cleanup workflow.

The options, examples, and behavior descriptions accurately reflect the PR implementation. Users will understand how cleanup scripts integrate with the removal workflow.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants