Skip to content
This repository was archived by the owner on Nov 18, 2026. It is now read-only.
This repository was archived by the owner on Nov 18, 2026. It is now read-only.

auto-delete merged branches #75

Closed

Description

@scarf005

since it's easy to create too many worktrees, a command like git gtr rm --merged would be great for cleaning up merged branches.

been using: https://github.com/scarf005/gh-cli-extension/blob/main/gh-delete-all-merged-branches.ts but it only handles branches so would need tweaking to make it work for worktrees too.

Activity

  1. traycerai commented on Jan 7, 2026

    @traycerai

    Plan

    Observations

    The codebase already implements merged branch cleanup functionality in cmd_clean --merged (file:bin/gtr lines 926-1024), which uses GitHub CLI to detect merged PRs and removes associated worktrees. However, this feature is undocumented in the README and the user is requesting it under the rm command instead. The current implementation checks for uncommitted changes, untracked files, and uses gh pr list to verify merge status before removal.

    Approach

    Add a --merged flag to the existing cmd_remove function to enable bulk removal of worktrees with merged branches. This provides a more intuitive UX (git gtr rm --merged) compared to the existing clean --merged command. The implementation will reuse the merge detection logic from cmd_clean but integrate it into the rm command's workflow, maintaining consistency with existing flags like --delete-branch, --force, and --yes.

    Implementation Steps

    1. Extend cmd_remove Function Flag Parsing

    Location: file:bin/gtr lines 338-368

    Add --merged flag handling in the argument parser:

    • Add a merged_mode variable (default: 0)
    • Parse --merged flag to set merged_mode=1
    • When --merged is set, ignore the identifiers requirement check (line 370-373)
    • Add --dry-run flag support for preview mode

    2. Extract Merge Detection Logic into Reusable Function

    Location: file:lib/core.sh (new function at end)

    Create a new function is_worktree_merged() that encapsulates the merge detection logic:

    • Parameters: worktree_path, branch_name, main_branch
    • Check for uncommitted changes using git diff --quiet and git diff --cached --quiet
    • Check for untracked files using git ls-files --others --exclude-standard
    • Query GitHub PR status using gh pr list --head "$branch" --state merged --json state --jq '.[0].state'
    • Return 0 if merged and clean, 1 otherwise
    • Include appropriate logging for skip reasons (uncommitted changes, untracked files, not merged)

    3. Implement Merged Mode in cmd_remove

    Location: file:bin/gtr lines 380-432

    Add conditional logic after line 378 (after resolving repo context):

    • If merged_mode=1, perform bulk merged branch removal:
      • Verify gh CLI is available (similar to cmd_clean lines 930-941)
      • Fetch from origin with git fetch origin --prune
      • Get main branch using current_branch "$repo_root"
      • Iterate through worktree directories in $base_dir/${prefix}*
      • For each worktree, call is_worktree_merged() function
      • If merged, proceed with removal using existing removal logic (lines 394-432)
      • Track counters for removed/skipped worktrees
      • Display summary at the end
    • If merged_mode=0, use existing identifier-based removal logic

    4. Update Help Text

    Location: file:bin/gtr lines 1431-1435

    Extend the rm command documentation:

    • Add --merged flag description: "remove all worktrees with merged PRs (requires gh CLI)"
    • Add --dry-run, -n flag description: "preview what would be removed"
    • Add usage example: git gtr rm --merged --yes for non-interactive cleanup

    5. Update README Documentation

    Location: file:README.md lines 216-226

    Enhance the git gtr rm section:

    • Add --merged to the options list with description
    • Add example: git gtr rm --merged --dry-run to preview merged branches
    • Add example: git gtr rm --merged --yes for automated cleanup
    • Add note about GitHub CLI requirement for --merged flag

    6. Update CHANGELOG

    Location: file:CHANGELOG.md lines 7-10

    Add to the [Unreleased] section under ### Added:

    • "--merged flag for rm command to bulk remove worktrees with merged PRs (requires GitHub CLI)"
    • "--dry-run flag for rm command to preview removals"

    Sequence Diagram

    sequenceDiagram
        participant User
        participant cmd_remove
        participant is_worktree_merged
        participant gh CLI
        participant remove_worktree
    
        User->>cmd_remove: git gtr rm --merged
        cmd_remove->>cmd_remove: Parse --merged flag
        cmd_remove->>gh CLI: Verify gh CLI available
        cmd_remove->>cmd_remove: git fetch origin --prune
        
        loop For each worktree
            cmd_remove->>is_worktree_merged: Check if merged
            is_worktree_merged->>is_worktree_merged: Check uncommitted changes
            is_worktree_merged->>is_worktree_merged: Check untracked files
            is_worktree_merged->>gh CLI: gh pr list --head branch --state merged
            gh CLI-->>is_worktree_merged: PR state
            is_worktree_merged-->>cmd_remove: merged status
            
            alt If merged and clean
                cmd_remove->>remove_worktree: Remove worktree
                cmd_remove->>cmd_remove: Delete branch
            else If not merged or dirty
                cmd_remove->>cmd_remove: Skip with warning
            end
        end
        
        cmd_remove-->>User: Summary (removed/skipped counts)
    
    Loading

    Additional Considerations

    • Backward Compatibility: The existing clean --merged functionality should remain unchanged to avoid breaking existing workflows
    • Error Handling: Ensure proper error messages when gh CLI is not installed or not authenticated
    • Safety Checks: Maintain existing safety checks (uncommitted changes, untracked files) to prevent data loss
    • Dry Run Mode: The --dry-run flag allows users to preview what would be removed before committing to the operation
    • Confirmation Prompts: Respect the --yes flag for non-interactive mode, otherwise prompt for each worktree removal

    Import In IDE

    VSCode Icon Cursor Icon Windsurf Icon

    🤖 Prompt for AI Agents
    ## Observations
    
    The codebase already implements merged branch cleanup functionality in `cmd_clean --merged` (file:bin/gtr lines 926-1024), which uses GitHub CLI to detect merged PRs and removes associated worktrees. However, this feature is undocumented in the README and the user is requesting it under the `rm` command instead. The current implementation checks for uncommitted changes, untracked files, and uses `gh pr list` to verify merge status before removal.
    
    ## Approach
    
    Add a `--merged` flag to the existing `cmd_remove` function to enable bulk removal of worktrees with merged branches. This provides a more intuitive UX (`git gtr rm --merged`) compared to the existing `clean --merged` command. The implementation will reuse the merge detection logic from `cmd_clean` but integrate it into the `rm` command's workflow, maintaining consistency with existing flags like `--delete-branch`, `--force`, and `--yes`.
    
    ## Implementation Steps
    
    ### 1. Extend `cmd_remove` Function Flag Parsing
    
    **Location:** file:bin/gtr lines 338-368
    
    Add `--merged` flag handling in the argument parser:
    - Add a `merged_mode` variable (default: 0)
    - Parse `--merged` flag to set `merged_mode=1`
    - When `--merged` is set, ignore the `identifiers` requirement check (line 370-373)
    - Add `--dry-run` flag support for preview mode
    
    ### 2. Extract Merge Detection Logic into Reusable Function
    
    **Location:** file:lib/core.sh (new function at end)
    
    Create a new function `is_worktree_merged()` that encapsulates the merge detection logic:
    - Parameters: `worktree_path`, `branch_name`, `main_branch`
    - Check for uncommitted changes using `git diff --quiet` and `git diff --cached --quiet`
    - Check for untracked files using `git ls-files --others --exclude-standard`
    - Query GitHub PR status using `gh pr list --head "$branch" --state merged --json state --jq '.[0].state'`
    - Return 0 if merged and clean, 1 otherwise
    - Include appropriate logging for skip reasons (uncommitted changes, untracked files, not merged)
    
    ### 3. Implement Merged Mode in `cmd_remove`
    
    **Location:** file:bin/gtr lines 380-432
    
    Add conditional logic after line 378 (after resolving repo context):
    - If `merged_mode=1`, perform bulk merged branch removal:
      - Verify `gh` CLI is available (similar to `cmd_clean` lines 930-941)
      - Fetch from origin with `git fetch origin --prune`
      - Get main branch using `current_branch "$repo_root"`
      - Iterate through worktree directories in `$base_dir/${prefix}*`
      - For each worktree, call `is_worktree_merged()` function
      - If merged, proceed with removal using existing removal logic (lines 394-432)
      - Track counters for removed/skipped worktrees
      - Display summary at the end
    - If `merged_mode=0`, use existing identifier-based removal logic
    
    ### 4. Update Help Text
    
    **Location:** file:bin/gtr lines 1431-1435
    
    Extend the `rm` command documentation:
    - Add `--merged` flag description: "remove all worktrees with merged PRs (requires gh CLI)"
    - Add `--dry-run, -n` flag description: "preview what would be removed"
    - Add usage example: `git gtr rm --merged --yes` for non-interactive cleanup
    
    ### 5. Update README Documentation
    
    **Location:** file:README.md lines 216-226
    
    Enhance the `git gtr rm` section:
    - Add `--merged` to the options list with description
    - Add example: `git gtr rm --merged --dry-run` to preview merged branches
    - Add example: `git gtr rm --merged --yes` for automated cleanup
    - Add note about GitHub CLI requirement for `--merged` flag
    
    ### 6. Update CHANGELOG
    
    **Location:** file:CHANGELOG.md lines 7-10
    
    Add to the `[Unreleased]` section under `### Added`:
    - "`--merged` flag for `rm` command to bulk remove worktrees with merged PRs (requires GitHub CLI)"
    - "`--dry-run` flag for `rm` command to preview removals"
    
    ## Sequence Diagram
    
    ```mermaid
    sequenceDiagram
        participant User
        participant cmd_remove
        participant is_worktree_merged
        participant gh CLI
        participant remove_worktree
    
        User->>cmd_remove: git gtr rm --merged
        cmd_remove->>cmd_remove: Parse --merged flag
        cmd_remove->>gh CLI: Verify gh CLI available
        cmd_remove->>cmd_remove: git fetch origin --prune
        
        loop For each worktree
            cmd_remove->>is_worktree_merged: Check if merged
            is_worktree_merged->>is_worktree_merged: Check uncommitted changes
            is_worktree_merged->>is_worktree_merged: Check untracked files
            is_worktree_merged->>gh CLI: gh pr list --head branch --state merged
            gh CLI-->>is_worktree_merged: PR state
            is_worktree_merged-->>cmd_remove: merged status
            
            alt If merged and clean
                cmd_remove->>remove_worktree: Remove worktree
                cmd_remove->>cmd_remove: Delete branch
            else If not merged or dirty
                cmd_remove->>cmd_remove: Skip with warning
            end
        end
        
        cmd_remove-->>User: Summary (removed/skipped counts)
    ```
    
    ## Additional Considerations
    
    - **Backward Compatibility:** The existing `clean --merged` functionality should remain unchanged to avoid breaking existing workflows
    - **Error Handling:** Ensure proper error messages when `gh` CLI is not installed or not authenticated
    - **Safety Checks:** Maintain existing safety checks (uncommitted changes, untracked files) to prevent data loss
    - **Dry Run Mode:** The `--dry-run` flag allows users to preview what would be removed before committing to the operation
    - **Confirmation Prompts:** Respect the `--yes` flag for non-interactive mode, otherwise prompt for each worktree removal

    Execution Information

    Branch: main
    Commit: 1fc840e


    💡 Tips

    Supported Commands (Inside Comments)

    • Use @traycerai generate to iterate on the previous version of the implementation plan.

    Supported Commands (Inside Description)

    • Add @traycerai ignore anywhere in the ticket description to prevent this ticket from being processed.
    • Add @traycerai branch:<branch-name> anywhere in the ticket description to specify the target branch for the implementation plan.

    Community

    • Join our Discord Community to get help, request features, and share feedback.
    • Follow us on X/Twitter for updates and announcements.
  2. helizaga commented on Jan 7, 2026

    @helizaga
    Contributor

    This already exists as git gtr clean --merged (added in #64). Does that cover your use case?

     # Dry-run to preview what would be removed
      git gtr clean --merged --dry-run
    
      # Remove all worktrees with merged PRs
      git gtr clean --merged --yes
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions