Skip to content

Add PR worktree checkout command#187

Open
scarf005 wants to merge 4 commits into
coderabbitai:mainfrom
scarf005:feat/pr-checkout
Open

Add PR worktree checkout command#187
scarf005 wants to merge 4 commits into
coderabbitai:mainfrom
scarf005:feat/pr-checkout

Conversation

@scarf005

@scarf005 scarf005 commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Description

  • Add git gtr pr <number|url|branch> to create PR review worktrees.
  • Support gtr pr <selector> --cd via shell integration.
  • Configure branch/base metadata so gh pr view works from created PR worktrees.
  • Update help, docs, completions, and tests.

Motivation

gh pr checkout checks out PRs in the current working tree; this adds the equivalent workflow for git gtr worktrees.

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

Manual Testing Checklist

Tested on:

  • macOS
  • Linux (Fedora Kinoite)
  • 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 pr, gtr pr --cd, git gtr init

Test Steps

  1. bash -n bin/git-gtr lib/commands/*.sh scripts/generate-completions.sh completions/gtr.bash tests/*.bats
  2. ./scripts/generate-completions.sh --check
  3. git diff --check
  4. Generate bash/fish init caches and syntax-check them.
  5. Create mocked PR worktrees with local bare remotes, including base-repo URL fetch, custom suffix sanitization, and existing-branch metadata preservation.
  6. Create a real PR worktree from https://github.com/cataclysmbn/Cataclysm-BN/pull/9664 in a fork clone and run gh pr view from inside it.

Expected behavior:

  • git gtr pr creates a separate worktree at the PR head commit.
  • gtr pr --cd changes into the new worktree with shell integration.
  • gh pr view resolves the PR from inside the created worktree.
  • Existing local branch metadata is not overwritten.

Actual behavior:

  • Matches expected behavior in focused smoke tests.
  • bats and shellcheck were not available locally.

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

License Acknowledgment

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

PR opened by gpt-5.5 xhigh on pi

Summary by CodeRabbit

  • New Features

    • Added git gtr pr to create a local worktree for GitHub pull requests (supports branch/repo/remote selection, editor/AI startup, and non-interactive mode).
    • Added --cd behavior for PR worktrees, including shell-integration support to land in the created directory.
  • Bug Fixes

    • Improved validation and sanitization for custom worktree naming inputs.
  • Documentation

    • Updated README, command help, and configuration docs with git gtr pr usage, options, and examples.
  • Completions

    • Added/updated Bash, Zsh, and Fish shell completions for the pr subcommand and related flags.
  • Tests

    • Added a dedicated PR command test suite and expanded help/init and folder-name coverage.

scarf005 and others added 3 commits June 26, 2026 23:54
Assisted-by: pi:gpt-5.5
Co-authored-by: chatgpt-codex-connector[bot] <199175422+chatgpt-codex-connector[bot]@users.noreply.github.com>
Assisted-by: pi:gpt-5.5
Co-authored-by: chatgpt-codex-connector[bot] <199175422+chatgpt-codex-connector[bot]@users.noreply.github.com>
Assisted-by: pi:gpt-5.5
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 July 1, 2026 00:41
@coderabbitai

coderabbitai Bot commented Jul 1, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 3863d42f-93ba-406d-8b8d-7fba152e371c

📥 Commits

Reviewing files that changed from the base of the PR and between 4c77e95 and b8b52de.

📒 Files selected for processing (3)
  • lib/commands/pr.sh
  • tests/cmd_pr.bats
  • tests/init.bats
🚧 Files skipped from review as they are similar to previous changes (3)
  • tests/init.bats
  • tests/cmd_pr.bats
  • lib/commands/pr.sh

Walkthrough

Adds a new git gtr pr <number|url|branch> command that creates a local worktree for a GitHub pull request using the gh CLI. Includes command dispatch wiring, shell integration for --cd, completions for Bash/Zsh/Fish, help/README/config documentation updates, a folder-name validation fix, and tests.

Changes

git gtr pr feature

Layer / File(s) Summary
Core pr command implementation
lib/commands/pr.sh, lib/core.sh, lib/commands/create.sh
Adds cmd_pr with helpers to resolve PR metadata via gh, derive/match git remotes, configure branch tracking config, create the worktree, and validate --name input; create.sh now reuses the shared _resolve_folder_name helper.
Command dispatch wiring
bin/git-gtr
Registers pr in the main command dispatcher.
Shell integration for --cd
lib/commands/init.sh
Extends generated Bash/Zsh/Fish wrappers and completions so gtr pr --cd switches directories like gtr new --cd; bumps cache schema version from 5 to 6.
Shell completion scripts
completions/_git-gtr, completions/git-gtr.fish, completions/gtr.bash, scripts/generate-completions.sh
Adds pr subcommand and flag completions across Bash, Zsh, and Fish, both in static files and the generator script.
Help text and documentation
lib/commands/help.sh, README.md, docs/configuration.md
Adds _help_pr, updates _help_init/_help_full, README usage/examples/comparison table, and postCd hook docs to cover gtr pr --cd.
Tests
tests/cmd_pr.bats, tests/cmd_help.bats, tests/init.bats, tests/core_create_worktree.bats
Adds cmd_pr integration tests, updates help/init/completion test expectations, and adds folder-name sanitization/validation tests.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant git_gtr as git-gtr
  participant cmd_pr
  participant gh as gh CLI
  participant Git

  User->>git_gtr: git gtr pr 123 --cd
  git_gtr->>cmd_pr: cmd_pr "$@"
  cmd_pr->>gh: gh pr view 123
  gh-->>cmd_pr: PR number, head ref, owner/repo, URL
  cmd_pr->>Git: resolve/create base remote
  cmd_pr->>Git: git fetch refs/pull/123/head
  cmd_pr->>Git: git worktree add
  cmd_pr->>Git: set branch remote/pushRemote/merge config
  cmd_pr-->>User: worktree ready, shell cd's into it
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

A rabbit hops through pull request trails,
🐇 fetching refs where the head ref sails,
Worktrees sprout with a --cd hop,
Completions bloom, they never stop.
gh whispers PR secrets, low and clear —
hop in, dear dev, your branch is here! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title matches the main change: adding a new git gtr pr command to create and check out pull request worktrees.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 (2)
tests/init.bats (1)

966-976: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Overly convoluted conditional; simplify to a direct call.

Since the cache file is always seeded with the stale init=5 stamp right before this line, [[ -f "$_gtr_init" ]] && head -n 1 ... | grep -q ' init=6 ' || cmd_init bash >/dev/null || true always reduces to just running cmd_init bash, and the trailing || true silently swallows any non-zero exit from cmd_init. This duplicates the previous test's intent (lines 953-964) with unnecessary complexity.

♻️ Simplification
-  [[ -f "$_gtr_init" ]] && head -n 1 "$_gtr_init" | grep -q ' init=6 ' || cmd_init bash >/dev/null || true
+  cmd_init bash >/dev/null
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/init.bats` around lines 966 - 976, The setup in the gtr bash cache test
is overcomplicated and effectively always falls through to initialization, so
simplify the logic in the documented bash setup regenerates old schema cache
case by calling cmd_init bash directly after seeding the stale cache. Update the
test body around the local _gtr_init and cmd_init bash usage to remove the
redundant file-check/grep conditional and the trailing || true, keeping the
intent clear and consistent with the existing cache-regeneration tests.
lib/commands/pr.sh (1)

9-44: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

gh failures are silently swallowed, hiding the real cause.

Both gh pr view invocations redirect stderr to /dev/null before falling back to a generic "Could not resolve pull request" message. Auth failures, rate limiting, or network errors will all look identical to "PR not found", making troubleshooting harder for users.

♻️ Capture and surface gh's stderr on failure
-  if [ -n "$repo_arg" ]; then
-    output=$(gh pr view "$selector" --repo "$repo_arg" --json "$json_fields" --template "$template" 2>/dev/null) || {
-      log_error "Could not resolve pull request: $selector"
-      return 1
-    }
-  else
-    output=$(gh pr view "$selector" --json "$json_fields" --template "$template" 2>/dev/null) || {
-      log_error "Could not resolve pull request: $selector"
-      return 1
-    }
-  fi
+  local gh_stderr
+  if [ -n "$repo_arg" ]; then
+    output=$(gh pr view "$selector" --repo "$repo_arg" --json "$json_fields" --template "$template" 2>&1 >/dev/null); gh_stderr="$output"
+    output=$(gh pr view "$selector" --repo "$repo_arg" --json "$json_fields" --template "$template" 2>/dev/null) || {
+      log_error "Could not resolve pull request: $selector"
+      [ -n "$gh_stderr" ] && log_info "$gh_stderr"
+      return 1
+    }
+  else
+    ...
+  fi

(Simplify by capturing stderr once via a temp var/2> >(...)-free approach appropriate for Bash 3.2.)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/commands/pr.sh` around lines 9 - 44, The _pr_resolve helper is swallowing
gh errors by redirecting stderr to /dev/null, so auth/network/rate-limit
failures are indistinguishable from a missing PR. Update _pr_resolve to capture
gh pr view stderr once and surface that detail in the log_error path, while
still handling both repo_arg and non-repo_arg calls. Keep the parsing of
_ctx_pr_number and related fields unchanged, but make the failure message
include gh’s actual stderr so users can diagnose the real cause.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/commands/pr.sh`:
- Around line 84-110: _pr_remote_for_url currently compares remote URLs after
only trimming trailing slash and .git, so SSH remotes from git remote get-url
won’t match the HTTPS URL shape used by gh pr view. Update
_pr_normalize_repo_url to canonicalize SSH/HTTPS variants of the same GitHub
repo (including scp-style git@host:owner/repo and ssh:// URLs) into one
comparable form before _pr_remote_for_url does the equality check. Keep the fix
localized to _pr_normalize_repo_url and preserve the existing lookup flow in
_pr_remote_for_url and _pr_configure_base_remote_for_gh so real remotes like
origin are reused instead of creating synthetic gtr-pr-* remotes.

In `@tests/cmd_pr.bats`:
- Around line 112-118: The cmd_pr "requires GitHub CLI" test can still hit a
real gh binary on PATH after removing only the mock symlink. Update the test
setup in cmd_pr.bats to fully control PATH (or otherwise ensure no fallback gh
exists), and assert the missing-CLI failure by checking stderr for the expected
"gh not found" / "GitHub CLI" message. Use the cmd_pr test case and the existing
TEST_MOCK_BIN setup to keep the failure path deterministic.

---

Nitpick comments:
In `@lib/commands/pr.sh`:
- Around line 9-44: The _pr_resolve helper is swallowing gh errors by
redirecting stderr to /dev/null, so auth/network/rate-limit failures are
indistinguishable from a missing PR. Update _pr_resolve to capture gh pr view
stderr once and surface that detail in the log_error path, while still handling
both repo_arg and non-repo_arg calls. Keep the parsing of _ctx_pr_number and
related fields unchanged, but make the failure message include gh’s actual
stderr so users can diagnose the real cause.

In `@tests/init.bats`:
- Around line 966-976: The setup in the gtr bash cache test is overcomplicated
and effectively always falls through to initialization, so simplify the logic in
the documented bash setup regenerates old schema cache case by calling cmd_init
bash directly after seeding the stale cache. Update the test body around the
local _gtr_init and cmd_init bash usage to remove the redundant file-check/grep
conditional and the trailing || true, keeping the intent clear and consistent
with the existing cache-regeneration tests.
🪄 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: Enterprise

Run ID: 9e39081a-7ed1-4aaf-9474-fa56092f09b7

📥 Commits

Reviewing files that changed from the base of the PR and between ad7a3c5 and 4c77e95.

📒 Files selected for processing (16)
  • README.md
  • bin/git-gtr
  • completions/_git-gtr
  • completions/git-gtr.fish
  • completions/gtr.bash
  • docs/configuration.md
  • lib/commands/create.sh
  • lib/commands/help.sh
  • lib/commands/init.sh
  • lib/commands/pr.sh
  • lib/core.sh
  • scripts/generate-completions.sh
  • tests/cmd_help.bats
  • tests/cmd_pr.bats
  • tests/core_create_worktree.bats
  • tests/init.bats

Comment thread lib/commands/pr.sh
Comment thread tests/cmd_pr.bats
Assisted-by: pi:gpt-5.5
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