Skip to content

feat(clean): add --to filter for git gtr clean --merged#167

Open
scarf005 wants to merge 2 commits intocoderabbitai:mainfrom
scarf005:feat/clean-merged-target
Open

feat(clean): add --to filter for git gtr clean --merged#167
scarf005 wants to merge 2 commits intocoderabbitai:mainfrom
scarf005:feat/clean-merged-target

Conversation

@scarf005
Copy link
Copy Markdown
Contributor

@scarf005 scarf005 commented Apr 10, 2026

Pull Request

Description

Adds --to <Ref> option to git gtr clean --merged and tightens merged cleanup so only worktrees whose current branch tip matches a merged PR/MR for the requested target ref are considered.

Motivation

For teams that merge PRs into staging or release branches before main, git gtr clean --merged --to main must not treat staging-only merges as eligible for deletion. This also needs to avoid false positives when branch names are reused.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Code refactoring (no functional changes)
  • Other (please describe):

Testing

  • bats tests/cmd_clean.bats tests/provider.bats tests/cmd_help.bats tests/completion.bats
  • shellcheck lib/commands/clean.sh lib/provider.sh lib/commands/help.sh
  • ./bin/gtr clean
  • git gtr clean
  • ./scripts/generate-completions.sh --check

Manual Testing Checklist

Tested on:

  • macOS
  • Linux (specify distro: __)
  • Windows (Git Bash)

Core functionality tested:

  • git gtr new <branch> - Create worktree
  • git gtr go <branch> - Navigate to worktree
  • git gtr editor <branch> - Open in editor (if applicable)
  • git gtr ai <branch> - Start AI tool (if applicable)
  • git gtr rm <branch> - Remove worktree
  • git gtr list - List worktrees
  • git gtr config - Configuration commands (if applicable)
  • Other commands affected by this change: git gtr clean --merged --to <ref>

Test Steps

  1. Create a worktree and commit on the feature branch.
  2. Open a PR targeting a non-main branch such as dummy.
  3. Run git gtr clean --merged --to main.
  4. Verify the worktree is not removed because the PR was not merged into main.
  5. Reuse a previously merged branch name and verify cleanup only matches the current branch tip.

Expected behavior:
Only worktrees whose current branch tip belongs to a merged PR/MR into the specified target ref are removed.

Actual behavior:
git gtr clean --merged --to main ignores non-merged worktrees, rejects --to without --merged, and does not emit dirty-skip warnings for branches that were never eligible for deletion.

Breaking Changes

  • This PR introduces breaking changes
  • I have discussed this in an issue first
  • Migration guide is included in documentation

Checklist

Before submitting this PR, please check:

  • I have read CONTRIBUTING.md
  • My code follows the project's style guidelines
  • I have performed manual testing on at least one platform
  • I have updated documentation (README.md, CLAUDE.md, etc.) if needed
  • My changes work on multiple platforms (or I've noted platform-specific behavior)
  • I have added/updated shell completions (if adding new commands or flags)
  • I have tested with both git gtr (production) and ./bin/gtr (development)
  • No new external dependencies are introduced (Bash + git only)
  • All existing functionality still works

Additional Context

This also fixes the completion generator so regenerated bash/zsh/fish completions keep the --to option.


License Acknowledgment

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache License 2.0.

Summary by CodeRabbit

  • New Features

    • Added --to <ref> for git gtr clean --merged to restrict cleanup to worktrees whose PRs/MRs were merged into the specified base ref.
  • Documentation

    • Updated command help, examples, and overall docs to describe the new --to <ref> option and its usage.
  • Shell Completions

    • Added completion support for the new --to option across shells.
  • Tests

    • Added tests covering --to <ref> behavior and related merged-check logic.

Assisted-by: gpt-5.4-high on opencode
Co-authored-by: chatgpt-codex-connector[bot] <199175422+chatgpt-codex-connector[bot]@users.noreply.github.com>
@scarf005 scarf005 requested a review from NatoBoram as a code owner April 10, 2026 04:52
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 10, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6f9751f4-c217-4a80-8314-7679bb693508

📥 Commits

Reviewing files that changed from the base of the PR and between 6f39450 and c06bdd8.

📒 Files selected for processing (5)
  • lib/commands/clean.sh
  • lib/provider.sh
  • scripts/generate-completions.sh
  • tests/cmd_clean.bats
  • tests/provider.bats
🚧 Files skipped from review as they are similar to previous changes (4)
  • tests/provider.bats
  • lib/provider.sh
  • tests/cmd_clean.bats
  • lib/commands/clean.sh

Walkthrough

Adds a new --to <ref> option to git gtr clean --merged, threads the target ref through completion scripts, CLI parsing, merged-worktree logic, and provider queries (GitHub/GitLab), and adds tests and help/docs for the new option.

Changes

Cohort / File(s) Summary
Documentation & Help
README.md, lib/commands/help.sh
Documented --to <ref> for git gtr clean --merged and added example usage (git gtr clean --merged --to main).
Shell Completions
completions/_git-gtr, completions/git-gtr.fish, completions/gtr.bash, scripts/generate-completions.sh
Added --to completion entry (accepts a ref) to Zsh, Fish, and Bash completion definitions and regen helper.
Clean command logic
lib/commands/clean.sh
Added --to CLI parsing; introduced target_ref passed into _clean_merged; adjusted merged detection flow and branch-tip computation.
Provider queries
lib/provider.sh
Extended check_branch_merged() signature to accept optional target_ref and branch_tip; GitHub queries include --base "$target_ref" and match head commit when provided; GitLab queries add --target-branch when target_ref is given.
Tests
tests/cmd_clean.bats, tests/cmd_help.bats, tests/provider.bats
Added/updated Bats tests to validate --to usage restrictions, merged-filtering behavior, provider invocation args (including base/target ref and head oid), and help output.

Sequence Diagram

sequenceDiagram
    participant User
    participant CLI as cmd_clean
    participant Cleaner as _clean_merged
    participant ProviderCheck as check_branch_merged
    participant Provider as GitHub/GitLab

    User->>CLI: git gtr clean --merged --to main
    CLI->>CLI: parse --merged and --to main → target_ref='main'
    CLI->>Cleaner: invoke _clean_merged(target_ref='main')
    Cleaner->>Cleaner: iterate worktrees (compute branch_tip)
    Cleaner->>ProviderCheck: check_branch_merged(provider, branch, 'main', branch_tip)
    ProviderCheck->>Provider: query PRs/MRs filtered by base/target='main' (and headRefOid==branch_tip if provided)
    Provider-->>ProviderCheck: return count/status of merged PRs/MRs
    ProviderCheck-->>Cleaner: return merged? (exit 0) / not merged
    Cleaner->>Cleaner: remove matching worktrees (only those merged into 'main')
    Cleaner-->>User: report cleanup results
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A patch hops in to trim and comb,
--to main guides each branch back home,
Providers queried, tips in a line,
Only merged twigs fall off the vine,
Clean trails make my burrow sublime. 🌿

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 21.62% 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 change: adding a --to filter option to the git gtr clean --merged command.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Copy link
Copy Markdown

@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: 2

🧹 Nitpick comments (1)
tests/cmd_clean.bats (1)

147-159: Strengthen this test with a non-matching target branch assertion.

Current test validates the positive path. Add a second worktree that should not be removed to lock in filter behavior and prevent false positives.

Suggested test hardening
 `@test` "cmd_clean --merged --to filters by target ref" {
   create_test_worktree "merged-to-main"
+  create_test_worktree "merged-to-develop"

   _clean_detect_provider() { printf "github"; }
   ensure_provider_cli() { return 0; }
-  check_branch_merged() { [ "$2" = "merged-to-main" ] && [ "$3" = "main" ]; }
+  check_branch_merged() {
+    [ "$3" = "main" ] && [ "$2" = "merged-to-main" ]
+  }
   run_hooks_in() { return 0; }
   run_hooks() { return 0; }

   run cmd_clean --merged --to main --yes
   [ "$status" -eq 0 ]
   [ ! -d "$TEST_WORKTREES_DIR/merged-to-main" ]
+  [ -d "$TEST_WORKTREES_DIR/merged-to-develop" ]
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/cmd_clean.bats` around lines 147 - 159, The test "cmd_clean --merged
--to filters by target ref" currently only verifies removal of the matching
worktree; add a second non-matching worktree (e.g., create_test_worktree
"merged-to-feature") and stub the same helpers (_clean_detect_provider,
ensure_provider_cli, check_branch_merged, run_hooks_in, run_hooks) so that
check_branch_merged returns true only for branch "merged-to-main" -> "main" and
false for the non-matching pair, then after running run cmd_clean --merged --to
main --yes assert status is 0, assert the "merged-to-main" directory was removed
and assert the "merged-to-feature" directory still exists to lock in the
negative case.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@completions/_git-gtr`:
- Around line 82-84: The completions for the new flags (--merged, --to, --yes)
are stale; re-run the project's completion-generation script/tool to regenerate
shell completions for the gtr command, ensure the generated artifacts for all
three completion targets (gtr.bash, _git-gtr, git-gtr.fish) include the new
flags/options, and commit those regenerated files together in the same change so
CI no longer reports stale completions.

In `@lib/commands/clean.sh`:
- Around line 149-157: After parsing args in lib/commands/clean.sh, validate
that --to (_arg_to -> target_ref) is only used when --merged (_arg_merged ->
merged_mode) is enabled: if target_ref is non-empty and merged_mode is false/0,
print a clear error message and exit non-zero; implement this check near where
merged_mode and target_ref are set (after parse_args) so the script rejects the
unsupported combination early rather than silently ignoring --to.

---

Nitpick comments:
In `@tests/cmd_clean.bats`:
- Around line 147-159: The test "cmd_clean --merged --to filters by target ref"
currently only verifies removal of the matching worktree; add a second
non-matching worktree (e.g., create_test_worktree "merged-to-feature") and stub
the same helpers (_clean_detect_provider, ensure_provider_cli,
check_branch_merged, run_hooks_in, run_hooks) so that check_branch_merged
returns true only for branch "merged-to-main" -> "main" and false for the
non-matching pair, then after running run cmd_clean --merged --to main --yes
assert status is 0, assert the "merged-to-main" directory was removed and assert
the "merged-to-feature" directory still exists to lock in the negative case.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4910c592-4cf8-4508-9cbc-4c8b29a846d6

📥 Commits

Reviewing files that changed from the base of the PR and between 025de7f and 6f39450.

📒 Files selected for processing (10)
  • README.md
  • completions/_git-gtr
  • completions/git-gtr.fish
  • completions/gtr.bash
  • lib/commands/clean.sh
  • lib/commands/help.sh
  • lib/provider.sh
  • tests/cmd_clean.bats
  • tests/cmd_help.bats
  • tests/provider.bats

Comment on lines 82 to 84
'--merged[Remove worktrees with merged PRs/MRs]' \
'--to[Only remove worktrees for PRs/MRs merged into this ref]:ref:' \
'--yes[Skip confirmation prompts]' \
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Generated completion artifacts are out-of-sync with CI expectations.

CI reports stale completion generation for this command surface. Please re-run completion generation and commit all produced completion files in the same change to clear the stale check.

As per coding guidelines, completions/*.{bash,fish} requires updating all three completion files (completions/gtr.bash, completions/_git-gtr, completions/git-gtr.fish) when adding commands or flags.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@completions/_git-gtr` around lines 82 - 84, The completions for the new flags
(--merged, --to, --yes) are stale; re-run the project's completion-generation
script/tool to regenerate shell completions for the gtr command, ensure the
generated artifacts for all three completion targets (gtr.bash, _git-gtr,
git-gtr.fish) include the new flags/options, and commit those regenerated files
together in the same change so CI no longer reports stale completions.

Avoid dirty skip noise for non-merged worktrees and reject --to without --merged.

Co-authored-by: chatgpt-codex-connector[bot] <199175422+chatgpt-codex-connector[bot]@users.noreply.github.com>
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.

1 participant