Skip to content

Conversation

@satococoa
Copy link
Owner

@satococoa satococoa commented Jul 24, 2025

Summary

  • Fixed error handling in wtp remove command to properly display errors when removing dirty worktrees
  • Added proper error messages for branch removal failures with --with-branch flag
  • Updated error detection to match actual git error messages

Problem

The wtp remove command was not showing error messages when attempting to remove worktrees with uncommitted changes. Instead, it would incorrectly report success while the worktree remained.

Solution

  1. Fixed the error handling in removeCommandWithCommandExecutor and removeBranchWithCommandExecutor to check individual command results
  2. Updated error messages to include git output for better diagnostics
  3. Updated error pattern matching to recognize "contains modified or untracked files" message from git

Test plan

  • Added unit tests for removing dirty worktrees without force flag (should fail)
  • Added unit tests for removing dirty worktrees with force flag (should succeed)
  • Added unit tests for branch removal with unmerged commits
  • Manually tested with actual dirty worktree to verify error messages
  • All existing tests pass

Manual Test Results

# Without --force (shows proper error)
$ ./wtp remove test-dirty-removal
failed to remove worktree at '/path/to/worktree'

Suggestions:
  • Commit or stash changes in the worktree first
  • Use '--force' flag to remove anyway

Original error: exit status 128: fatal: '/path/to/worktree' contains modified or untracked files, use --force to delete it

# With --force (succeeds)
$ ./wtp remove --force test-dirty-removal
Removed worktree 'test-dirty-removal' at /path/to/worktree

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Enhanced user-facing success messages when creating worktrees, providing clearer guidance and feedback.
    • Improved error reporting when removing worktrees or branches, with more informative messages for dirty worktrees or unmerged branches.
    • Introduced a compatibility mode for wtp add to align syntax with git worktree add.
  • Bug Fixes

    • Refined error handling to better detect and communicate specific Git operation failures during worktree and branch removal.
  • Documentation

    • Updated documentation and examples to reflect a simplified interface for the wtp add command, removing outdated flags and clarifying usage.
    • Added details on compatibility mode matching git worktree add behavior.
  • Tests

    • Refactored and expanded tests to cover the streamlined wtp add interface and improved success/error messaging.
    • Added new tests for edge cases in worktree and branch removal, and updated or removed tests for deprecated features.
  • Refactor

    • Simplified the wtp add command interface by removing support for --detach, --track, and --force flags, focusing on clearer usage patterns.

satococoa and others added 2 commits July 24, 2025 03:56
This change dramatically simplifies the `wtp add` command interface by removing complex features and flags that added cognitive overhead without significant value for most users.

## Removed Features
- `--detach` flag and detached HEAD support
- `--track` flag (auto-tracking of remote branches is now automatic)
- `--force` flag (users can use git worktree directly for edge cases)
- `--cd`/`--no-cd` flags (shell integration handles directory switching)
- `wtp add <worktree-name> <commit-ish>` pattern (ambiguous with branch names)

## New Simplified Interface
- `wtp add <existing-branch>` - Create worktree from existing local/remote branch
- `wtp add -b <new-branch>` - Create new branch and worktree from HEAD
- `wtp add -b <new-branch> <commit>` - Create new branch from specific commit

## Benefits
- Reduced complexity: Only 1 flag instead of 6
- Consistent with git-checkout pattern (`-b` for new branches)
- Eliminates ambiguous argument parsing
- Maintains all common workflows while removing edge cases
- Better error messages and user guidance

## Implementation Details
- Removed 100+ lines of complex argument parsing logic
- Simplified test suite by removing tests for deleted features
- Updated documentation and help text
- Enhanced success messages with friendly emojis and guidance
- Maintained backward compatibility for core use cases

This change follows the principle that software should be easy to use correctly and hard to use incorrectly.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
The remove command now correctly shows error messages when attempting to:
- Remove worktrees with uncommitted changes (without --force)
- Remove branches with unmerged commits (without --force-branch)

Previously, these errors were silently ignored due to incorrect error handling
in the command executor. The fix ensures users receive helpful error messages
suggesting the use of appropriate force flags.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings July 24, 2025 04:22
@coderabbitai
Copy link

coderabbitai bot commented Jul 24, 2025

Walkthrough

This update streamlines the wtp add command by removing several flags (--detach, --track, --force, --cd, --no-cd) and simplifying its interface. Documentation and tests were updated to match the new behavior. Error handling for worktree and branch removal was improved, and related tests were added or modified accordingly.

Changes

File(s) Change Summary
CLAUDE.md, README.md Documentation updated to reflect new wtp add interface, removed flag usage, and clarified examples.
cmd/wtp/add.go Simplified command logic and input validation; removed support for several flags; improved success messages; refactored branch tracking logic.
cmd/wtp/add_test.go Refactored and expanded tests to match the streamlined interface; removed obsolete flag tests; enhanced success message checks.
cmd/wtp/remove.go Improved error handling after Git command execution for more informative error reporting.
cmd/wtp/remove_test.go Added tests for dirty worktree and unmerged branch removal scenarios; updated CLI flag handling in tests.
internal/errors/errors.go Adjusted error substring detection for dirty worktree errors.
test/e2e/error_test.go Updated error message expectations and removed conflicting flags test.
test/e2e/framework/assertions.go Accepted new success message format in worktree creation assertions.
test/e2e/remote_test.go Replaced --track flag usage with simplified interface; renamed and rewrote related tests.
test/e2e/worktree_test.go Removed detached head and force flag tests; added branch conflict test for duplicate worktree creation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant AddCmd
    participant Git
    User->>CLI: wtp add [options] <branch> [commit-ish]
    CLI->>AddCmd: Parse args, validate input
    AddCmd->>Git: Resolve branch/tracking (if -b used)
    AddCmd->>Git: git worktree add ...
    Git-->>AddCmd: Worktree created or error
    AddCmd->>CLI: Display enhanced success or error message
    CLI-->>User: Output result
Loading
sequenceDiagram
    participant User
    participant CLI
    participant RemoveCmd
    participant Git
    User->>CLI: wtp remove <worktree/branch>
    CLI->>RemoveCmd: Parse args
    RemoveCmd->>Git: git worktree remove ...
    Git-->>RemoveCmd: Result (success or error)
    RemoveCmd->>RemoveCmd: Inspect result for errors/output
    RemoveCmd->>CLI: Display error or success message
    CLI-->>User: Output result
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~35 minutes

Possibly related PRs

  • Simplify add command interface for better usability #9: Implements the same core simplification of the wtp add command interface by removing --force, --detach, and --track flags, refactoring branch tracking resolution, updating usage text and examples, and enhancing success messages.

Poem

Hopping through code with a jubilant twitch,
Old flags are gone—no more force, track, or switch!
The interface gleams, so simple and neat,
With tests and docs pruned, this update’s a treat.
Worktrees now flourish, success messages cheer,
A rabbit’s delight—clean changes are here! 🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4df44bd and dc72cb9.

📒 Files selected for processing (1)
  • cmd/wtp/remove_test.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/wtp/remove_test.go
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-dirty-worktree-remove

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@satococoa satococoa self-assigned this Jul 24, 2025
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR fixes error handling in the wtp remove command to properly display error messages when attempting to remove worktrees with uncommitted changes. Previously, the command would incorrectly report success while leaving the worktree in place.

Key changes include:

  • Fixed error handling to check individual command results rather than just overall execution status
  • Updated error pattern matching to recognize the actual git error message "contains modified or untracked files"
  • Added comprehensive test coverage for dirty worktree removal scenarios and branch removal with unmerged commits

Reviewed Changes

Copilot reviewed 11 out of 11 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
cmd/wtp/remove.go Fixed error handling in remove and branch removal functions to properly check command results
internal/errors/errors.go Updated error pattern matching to recognize actual git error messages
cmd/wtp/remove_test.go Added comprehensive tests for dirty worktree and unmerged branch removal scenarios
test/e2e/*.go Updated end-to-end tests to reflect simplified interface changes
cmd/wtp/add.go Simplified add command interface by removing complex flags and options
test/e2e/framework/assertions.go Updated assertion to check for new friendly success message format
README.md Updated documentation to reflect simplified command syntax
CLAUDE.md Added documentation of recent interface simplification changes
Comments suppressed due to low confidence (1)

cmd/wtp/add_test.go:27

  • The test only checks for the 'branch' flag but the comment suggests this is testing the simplified interface. Consider adding a test to verify that removed flags (force, detach, track) are no longer present to ensure the simplification was complete.
	// Check simplified flags exist (only -b/--branch remains)

if err != nil {
return errors.WorktreeRemovalFailed(targetWorktree.Path, err)
}
if len(result.Results) > 0 && result.Results[0].Error != nil {
Copy link

Copilot AI Jul 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The error handling pattern for checking result.Results[0].Error is duplicated in both removeCommandWithCommandExecutor and removeBranchWithCommandExecutor. Consider extracting this logic into a helper function to reduce code duplication.

Copilot uses AI. Check for mistakes.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
cmd/wtp/add.go (1)

371-383: Consider normalizing paths before comparison.

While the isMainWorktree function uses filepath.Abs for comparison, consider also using filepath.Clean to normalize paths and handle edge cases like trailing slashes:

 func isMainWorktree(workTreePath, mainRepoPath string) bool {
-    absWorkTreePath, err := filepath.Abs(workTreePath)
+    absWorkTreePath, err := filepath.Abs(filepath.Clean(workTreePath))
     if err != nil {
         return false
     }
 
-    absMainRepoPath, err := filepath.Abs(mainRepoPath)
+    absMainRepoPath, err := filepath.Abs(filepath.Clean(mainRepoPath))
     if err != nil {
         return false
     }
 
     return absWorkTreePath == absMainRepoPath
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cc3e51b and 4df44bd.

📒 Files selected for processing (11)
  • CLAUDE.md (2 hunks)
  • README.md (2 hunks)
  • cmd/wtp/add.go (8 hunks)
  • cmd/wtp/add_test.go (6 hunks)
  • cmd/wtp/remove.go (2 hunks)
  • cmd/wtp/remove_test.go (2 hunks)
  • internal/errors/errors.go (1 hunks)
  • test/e2e/error_test.go (2 hunks)
  • test/e2e/framework/assertions.go (1 hunks)
  • test/e2e/remote_test.go (2 hunks)
  • test/e2e/worktree_test.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (7)
cmd/wtp/remove.go (2)
internal/command/types.go (1)
  • Command (4-8)
internal/errors/errors.go (2)
  • WorktreeRemovalFailed (119-152)
  • BranchRemovalFailed (154-177)
test/e2e/worktree_test.go (1)
test/e2e/framework/assertions.go (3)
  • AssertNoError (68-71)
  • AssertError (73-76)
  • AssertOutputContains (29-32)
test/e2e/error_test.go (1)
test/e2e/framework/assertions.go (1)
  • AssertTrue (144-147)
test/e2e/remote_test.go (2)
test/e2e/framework/framework.go (1)
  • NewTestEnvironment (25-38)
test/e2e/framework/assertions.go (3)
  • AssertNoError (68-71)
  • AssertWorktreeCreated (10-21)
  • AssertWorktreeExists (109-122)
cmd/wtp/add_test.go (1)
internal/config/config.go (2)
  • Config (12-16)
  • Defaults (19-21)
cmd/wtp/remove_test.go (1)
internal/command/types.go (1)
  • Result (11-15)
cmd/wtp/add.go (3)
internal/command/builders.go (1)
  • GitWorktreeAddOptions (4-9)
internal/errors/errors.go (1)
  • BranchNameRequired (38-48)
internal/git/repository.go (1)
  • NewRepository (16-21)
🔇 Additional comments (18)
internal/errors/errors.go (1)

129-129: LGTM: Error pattern updated to match actual Git output.

The change from "working tree is dirty" to "contains modified or untracked files" aligns with Git's actual error message format, improving error detection accuracy for dirty worktrees.

cmd/wtp/remove.go (2)

155-166: Excellent error handling improvement.

The enhanced error checking properly inspects individual command results in addition to executor errors. This addresses the core issue where worktree removal could appear to succeed while actually failing, ensuring users receive appropriate error messages for dirty worktrees.


196-207: Consistent error handling implementation.

The branch removal function now uses the same improved error handling pattern as worktree removal, ensuring consistent and thorough error reporting across all removal operations.

README.md (1)

134-134: Inconsistency between changes and PR objectives.

The documentation updates show changes to the wtp add command interface (removing --track flag), but the PR objectives specifically state this is about fixing error handling in the wtp remove command for dirty worktrees. These appear to be unrelated changes that may have been bundled together inadvertently.

Please verify if these wtp add interface changes are intentionally included in this PR or if they should be in a separate pull request focused on command interface simplification.

Also applies to: 148-148

Likely an incorrect or invalid review comment.

test/e2e/framework/assertions.go (1)

13-15: Another inconsistency with PR objectives.

This change adds support for a new worktree creation success message, but the PR objectives are specifically about fixing error handling when removing dirty worktrees. This appears to be unrelated functionality bundled in the same PR.

Likely an incorrect or invalid review comment.

test/e2e/worktree_test.go (1)

60-74: Test changes don't match PR objectives.

The removal of DetachedHead test and addition of BranchConflict test are related to simplifying the wtp add command interface, not fixing error handling in the wtp remove command as stated in the PR objectives.

While the test logic itself appears sound (testing that duplicate branch addition fails appropriately), these changes seem to belong in a different PR focused on command interface simplification rather than error handling fixes.

Likely an incorrect or invalid review comment.

test/e2e/error_test.go (1)

68-73: PR objectives and code changes appear misaligned.

The changes in this file modify test expectations for the wtp add command by removing references to --force and --track flags. However, the PR objectives state this PR is specifically about "fixing error handling in the wtp remove command when removing dirty worktrees."

These changes appear to be related to simplifying the wtp add interface rather than fixing wtp remove error handling.

Also applies to: 106-112

Likely an incorrect or invalid review comment.

test/e2e/remote_test.go (2)

46-47: Interface change looks correct but doesn't match PR objectives.

The change from --track to -b flag usage is implemented correctly. However, this change is related to simplifying the wtp add interface, not fixing error handling in wtp remove as stated in the PR objectives.

Likely an incorrect or invalid review comment.


148-173: Test refactoring aligns with add command simplification.

The test function rename and content changes correctly reflect the new simplified interface patterns. The tests properly verify:

  • Creating new branches from remote branches
  • Creating new branches from specific commits

However, these changes are unrelated to the stated PR objective of fixing wtp remove error handling.

Likely an incorrect or invalid review comment.

CLAUDE.md (1)

5-98: Documentation describes major wtp add changes not mentioned in PR objectives.

This extensive documentation section details a major refactoring of the wtp add command, including:

  • Removal of multiple flags (--detach, --track, --force, --cd/--no-cd)
  • Introduction of a simplified interface
  • Compatibility mode changes

However, the PR objectives explicitly state this PR is about "fixing error handling in the wtp remove command when removing dirty worktrees." There's no mention of these substantial wtp add changes in the PR description.

This appears to be either:

  1. Wrong PR objectives/description
  2. Wrong set of files included in this PR
  3. Multiple unrelated changes bundled together

Please clarify the actual scope of this PR.

Likely an incorrect or invalid review comment.

cmd/wtp/remove_test.go (2)

413-499: Excellent test coverage for dirty worktree removal scenarios.

These tests properly verify the enhanced error handling for dirty worktrees:

  • ✅ Removal without --force fails with clear error message
  • ✅ Error message includes helpful suggestion to use --force
  • ✅ Removal with --force succeeds

This aligns perfectly with the PR objectives to fix error handling when removing dirty worktrees.


501-596: Good coverage for branch removal with unmerged commits.

The tests verify:

  • ✅ Removal of unmerged branches fails without --force-branch
  • ✅ Error message suggests using --force-branch
  • ✅ Removal succeeds with the flag

Well-structured test cases that complement the dirty worktree scenarios.

cmd/wtp/add_test.go (2)

27-28: Code changes don't match PR objectives.

While these test updates for the simplified wtp add interface are well-implemented:

  • Proper validation of the new -b flag pattern
  • Good test coverage for various scenarios
  • Clear test names and assertions

They are completely unrelated to the PR's stated objective of "fixing error handling in the wtp remove command."

Also applies to: 516-607

Likely an incorrect or invalid review comment.


709-805: Enhanced success messages with emojis are user-friendly.

The updated success message format with emojis (✅, 📁, 🌿, 💡) provides a much better user experience. The tests thoroughly cover various scenarios including:

  • Regular branches
  • Main worktree (@)
  • Detached HEAD
  • Commit references

However, these UX improvements for wtp add are outside the scope of the stated PR objectives.

Likely an incorrect or invalid review comment.

cmd/wtp/add.go (4)

25-31: Clear and focused command interface improvements.

The simplified usage text and examples make the command interface more intuitive and align well with the overall simplification effort mentioned in the PR summary.


118-151: Verify the branch name assignment logic when using resolved tracking.

The logic at lines 137-140 assigns the first argument as the branch name when using resolved tracking without -b. This seems correct, but please ensure this behavior is well-documented and tested, as it's a key part of the auto-tracking feature.

if cmd.Args().Len() > 0 && opts.Branch == "" {
    // The first argument is the branch name when using resolved tracking without -b
    opts.Branch = cmd.Args().Get(0)
}

312-312: Consistent error messaging with new interface.

The updated error message correctly reflects the simplified command syntax.


406-439: Well-structured branch resolution logic.

The resolveBranchTracking function cleanly implements the auto-tracking feature with proper error handling for ambiguous cases. The logic correctly skips resolution when creating a new branch with -b flag.

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
@satococoa satococoa merged commit 8724957 into main Jul 24, 2025
7 checks passed
@satococoa satococoa deleted the fix-dirty-worktree-remove branch July 24, 2025 14:19
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