feat(github-workflow): add auto-create-pr hook#46
Conversation
Automatically creates a PR via `gh pr create --fill` after git push when no PR exists for the branch, and reports the result back to the AI. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
Warning Rate limit exceeded
Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 11 minutes and 26 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughBumps github-workflow plugin to v0.0.10 and adds a new PostToolUse hook Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant HookRunner as Hook Runner
participant Git as Git (local)
participant GH as GitHub CLI (gh)
participant Scheduler as Deferred Scheduler
HookRunner->>Git: inspect current branch (git rev-parse --abbrev-ref HEAD)
alt branch missing or HEAD
HookRunner-->>HookRunner: exit success (no-op)
else branch present
HookRunner->>GH: query default branch (gh repo view --json defaultBranchRef)
GH-->>HookRunner: default branch info
alt branch == default
HookRunner-->>HookRunner: exit success (skip default)
else
HookRunner->>GH: check for existing PR (gh pr view --head <branch>)
alt PR exists
HookRunner-->>HookRunner: exit success (PR exists)
else no PR
HookRunner->>Scheduler: defer async PR creation task (timeout 30s)
Scheduler->>GH: run gh pr create --fill --head <branch>
alt gh pr create succeeds
GH-->>Scheduler: stdout (PR URL)
Scheduler->>GH: gh pr view --json title,url
GH-->>Scheduler: PR details
Scheduler-->>HookRunner: deferred success with additionalContext (Created PR + URL/title)
else fails
GH-->>Scheduler: stderr/exit non-zero
Scheduler-->>HookRunner: deferred failure with additionalContext (Failed to create PR + output)
end
end
end
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@plugins/github-workflow/hooks/entry/auto-create-pr.ts`:
- Around line 38-69: The createPr function can leave spawned processes (proc and
viewProc) running if the surrounding context.defer times out; modify createPr to
create an AbortController (or receive an AbortSignal from the defer) and pass
its signal to Bun.spawn calls for both proc and viewProc, and ensure you
abort/kill the controller when the defer timeout triggers (or on Promise.race
timeout) so proc.kill()/viewProc.kill() (or controller.abort()) is invoked to
terminate hanging subprocesses; update the Bun.spawn invocations in createPr to
include the signal option and handle abort errors appropriately so you always
clean up subprocesses on timeout or error.
🪄 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: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 82eb5316-d06e-44b3-a219-49919fd165c1
📒 Files selected for processing (5)
.claude-plugin/marketplace.jsonplugins/github-workflow/AGENTS.mdplugins/github-workflow/hooks/entry/auto-create-pr.tsplugins/github-workflow/hooks/hooks.jsonplugins/github-workflow/plugin.json
| async function createPr(branch: string): Promise<PrCreateResult> { | ||
| const proc = Bun.spawn(["gh", "pr", "create", "--fill", "--head", branch], { | ||
| stdout: "pipe", | ||
| stderr: "pipe", | ||
| }); | ||
| await proc.exited; | ||
|
|
||
| const stdout = (await new Response(proc.stdout).text()).trim(); | ||
| const stderr = (await new Response(proc.stderr).text()).trim(); | ||
|
|
||
| if (proc.exitCode !== 0) { | ||
| return { created: false, url: null, title: null, error: stderr || "Unknown error" }; | ||
| } | ||
|
|
||
| // gh pr create --fill outputs the PR URL on success | ||
| const url = stdout; | ||
|
|
||
| // Fetch the title from the created PR | ||
| let title: string | null = null; | ||
| try { | ||
| const viewProc = Bun.spawn(["gh", "pr", "view", branch, "--json", "title", "--jq", ".title"], { | ||
| stdout: "pipe", | ||
| stderr: "pipe", | ||
| }); | ||
| await viewProc.exited; | ||
| title = (await new Response(viewProc.stdout).text()).trim() || null; | ||
| } catch { | ||
| // title is optional | ||
| } | ||
|
|
||
| return { created: true, url, title, error: null }; | ||
| } |
There was a problem hiding this comment.
Subprocess may outlive the defer timeout.
The context.defer wrapper enforces a 30-second timeout, but if gh pr create hangs, the spawned process continues running in the background after the timeout rejects. Consider explicitly killing the process on timeout to avoid resource leaks.
♻️ Suggested approach with AbortSignal
-async function createPr(branch: string): Promise<PrCreateResult> {
- const proc = Bun.spawn(["gh", "pr", "create", "--fill", "--head", branch], {
+async function createPr(branch: string, signal?: AbortSignal): Promise<PrCreateResult> {
+ const proc = Bun.spawn(["gh", "pr", "create", "--fill", "--head", branch], {
stdout: "pipe",
stderr: "pipe",
});
+
+ signal?.addEventListener("abort", () => proc.kill(), { once: true });
+
await proc.exited;Then pass an AbortController signal from the defer block and abort it on timeout. Alternatively, you could use Promise.race with a timeout that kills the process.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@plugins/github-workflow/hooks/entry/auto-create-pr.ts` around lines 38 - 69,
The createPr function can leave spawned processes (proc and viewProc) running if
the surrounding context.defer times out; modify createPr to create an
AbortController (or receive an AbortSignal from the defer) and pass its signal
to Bun.spawn calls for both proc and viewProc, and ensure you abort/kill the
controller when the defer timeout triggers (or on Promise.race timeout) so
proc.kill()/viewProc.kill() (or controller.abort()) is invoked to terminate
hanging subprocesses; update the Bun.spawn invocations in createPr to include
the signal option and handle abort errors appropriately so you always clean up
subprocesses on timeout or error.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
plugins/github-workflow/hooks/auto-create-pr.test.ts (1)
56-59:deferoptions are currently unverified.At Line 56-Line 59, the mock drops the second
deferargument, so the test at Line 166-Line 168 won’t catch regressions where timeout options stop being passed.Suggested fix
- defer: vi.fn((fn: () => Promise<unknown>) => { + defer: vi.fn((fn: () => Promise<unknown>, _opts?: { timeoutMs?: number }) => { deferFn = fn; return { type: "defer" }; }), @@ expect(result).toStrictEqual({ type: "defer" }); - expect(ctx.defer).toHaveBeenCalled(); + expect(ctx.defer).toHaveBeenCalledWith( + expect.any(Function), + expect.objectContaining({ timeoutMs: expect.any(Number) }), + );Also applies to: 166-168
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@plugins/github-workflow/hooks/auto-create-pr.test.ts` around lines 56 - 59, The mock for defer in auto-create-pr.test.ts currently only captures the first argument and drops the second (timeout options); update the vi.fn mock for defer to accept both parameters (e.g., (fn, opts)) and store the options in a new variable (e.g., deferFnOptions) alongside deferFn so the test can inspect them, and then update the assertion near where defer is expected to be called (the assertions around the defer usage at lines ~166-168) to verify the captured options are passed through correctly; refer to the existing mock and the defer invocation sites to implement and assert the second argument.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@plugins/github-workflow/hooks/auto-create-pr.test.ts`:
- Around line 35-45: The test suite mutates globalThis.Bun via mockBunGlobal
(which captures originalBun) but never restores it; add an afterEach hook that
resets globalThis.Bun back to originalBun and clears or restores any mocked
functions (e.g., restore mockSpawnSync/mockSpawn) so tests do not leak state—use
the captured originalBun from the top-level variable and ensure mockBunGlobal
continues to assign overridden methods only during a test.
---
Nitpick comments:
In `@plugins/github-workflow/hooks/auto-create-pr.test.ts`:
- Around line 56-59: The mock for defer in auto-create-pr.test.ts currently only
captures the first argument and drops the second (timeout options); update the
vi.fn mock for defer to accept both parameters (e.g., (fn, opts)) and store the
options in a new variable (e.g., deferFnOptions) alongside deferFn so the test
can inspect them, and then update the assertion near where defer is expected to
be called (the assertions around the defer usage at lines ~166-168) to verify
the captured options are passed through correctly; refer to the existing mock
and the defer invocation sites to implement and assert the second argument.
🪄 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: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 73f00033-ff83-4921-b72a-f927a21da589
📒 Files selected for processing (1)
plugins/github-workflow/hooks/auto-create-pr.test.ts
| const originalBun = globalThis.Bun; | ||
|
|
||
| function mockBunGlobal(overrides: { spawnSync?: typeof mockSpawnSync; spawn?: typeof mockSpawn }) { | ||
| Object.assign(globalThis, { | ||
| Bun: { | ||
| ...originalBun, | ||
| spawnSync: overrides.spawnSync ?? mockSpawnSync, | ||
| spawn: overrides.spawn ?? mockSpawn, | ||
| }, | ||
| }); | ||
| } |
There was a problem hiding this comment.
Restore globalThis.Bun and mock state after each test.
At Line 38-Line 44, the suite mutates a global and never restores it. This can pollute later tests and cause order-dependent failures.
Suggested fix
-import { describe, expect, test, vi } from "vitest";
+import { afterEach, describe, expect, test, vi } from "vitest";
@@
const originalBun = globalThis.Bun;
+
+afterEach(() => {
+ mockExecFileSync.mockReset();
+ mockSpawnSync.mockReset();
+ mockSpawn.mockReset();
+ Object.assign(globalThis, { Bun: originalBun });
+});🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@plugins/github-workflow/hooks/auto-create-pr.test.ts` around lines 35 - 45,
The test suite mutates globalThis.Bun via mockBunGlobal (which captures
originalBun) but never restores it; add an afterEach hook that resets
globalThis.Bun back to originalBun and clears or restores any mocked functions
(e.g., restore mockSpawnSync/mockSpawn) so tests do not leak state—use the
captured originalBun from the top-level variable and ensure mockBunGlobal
continues to assign overridden methods only during a test.
github.ts, prompt.ts, and index.ts have no tests and were dragging coverage below the 80% threshold, failing CI across all branches. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Server-side and UI component files have no tests; scoping coverage to model and lib directories prevents false threshold failures. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Summary
gh pr create --fillで自動的に PR を作成する PostToolUse hook を追加additionalContextで AI に報告Test plan
git pushした際に PR が自動作成されることを確認🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Documentation
Tests
Chores