Files
kandev/apps/backend/internal/github/pat_client.go
T
José Almeida 14c19ea538 feat(web): add CI hover popover on PR top-bar button (#846)
* feat(github): plumb CI popover fields + branch protection cache

Adds RequiredReviews/UnresolvedReviewThreads/ChecksTotal/ChecksPassing
to TaskPR + PRStatus. Extends the GraphQL PR query with reviewThreads
to populate UnresolvedReviewThreads on every poll. New branch_protection.go
holds an in-memory TTL cache + BranchProtectionFetcher interface;
PATClient/GHClient implement REST/CLI lookups so SyncTaskPR can resolve
required_approving_review_count for the PR's base branch. SyncTaskPR
preserves existing counts when a lightweight (GraphQL) sync returns 0
so the popover doesn't flap during the polling cycle.

* feat(github): mock controller hooks for CI popover e2e

Extends associateTaskPR to accept review/check counts, required_reviews,
and unresolved_review_threads, and switches to ReplaceTaskPR so re-POSTing
the same task drives the popover live-refresh path. Adds POST /pr-feedback
to seed PRFeedback (checks/reviews/comments) keyed by a deterministic
synthetic head_sha, and PUT /auth-health to flip the mock client's
authenticated flag for the "Reconnect GitHub" branch. Mock client gains
ReplaceCheckRuns/ReplaceReviews/ReplaceComments helpers and an
authenticated field that defaults to true.

* feat(web): CI hover popover on PR top-bar button

Hovering the PR top-bar button now reveals a popover with
Passed/In-Progress/Failed counts, a workflow-rollup list under the
non-empty buckets (with "open on GitHub" + "+ ctx" affordances on
failed rows), a review-state row ("Approved 1 / 2 required"), and
unresolved-comments count. Click on the button keeps the existing
"open PR detail panel" behavior so shipped tests stay green.

PRFeedback is lazy-fetched on hover-open via a new SWR-style hook
backed by a 20-entry LRU cache slice; the popover refetches whenever
the underlying TaskPR's updated_at changes (the WS handler already
applies poll deltas). Bucket logic + workflow grouping live in a
small util with vitest coverage. The aggregate-popover variant for
multi-PR tasks ships but the multi-PR trigger preserves its existing
DropdownMenu so per-row click → addPRPanel still works.

* test(e2e): pr-topbar-popover scenarios A–F covering CI popover

11 specs covering: count rows + zero-bucket hiding, workflow rollup
with (N/M passed) badge under Failed, review row + unresolved comments,
hover open + leave close, failed-row open/+ctx affordances, header
external link, "No checks have started" empty state, "Reconnect GitHub"
auth-lost branch, and live count updates on a re-associate.

Adds api-client helpers (mockGitHubSeedPRFeedback, mockGitHubSetAuthHealth,
extended mockGitHubAssociateTaskPR) and SessionPage popover accessors.

* fix(github): address bot review comments on CI popover

- branch_protection.go: evict stale entries on read so the cache map
  cannot grow unbounded over a long-running deployment; rewrite the
  comment to drop the inaccurate singleflight claim (no dedup logic
  exists, concurrent misses race harmlessly to set()).
- gh_client.go: replace fragile strings.Contains "HTTP 404" with an
  isNotFoundErr helper that tolerates the formats current and future
  gh CLI versions use ("HTTP 404", "404 Not Found", "status: 404").
- graphql.go: extend reviewThreads with totalCount and attribute the
  un-fetched tail to the unresolved bucket so PRs with >100 threads
  don't silently undercount in the popover.
- pr-ci-popover.tsx: drop the dead "icon" initializer in PRReviewRow
  (every branch overwrites it). Memoize useAddCheckToContext so
  PRWorkflowRow's reference equality stays stable across renders.
- pr-topbar-button.tsx: collapse the duplicate JSDoc on
  usePopoverInteractions.

* fix(github): address remaining bot review comments + tests

Real correctness fixes:
- Replace the "0/0 means counts omitted" heuristic with an explicit
  PRStatus.ChecksPopulated flag so the rich REST sync can clear stale
  totals when checks are removed from a PR upstream.
- Refresh tp.BaseBranch from status.PR on each SyncTaskPR so a
  retargeted PR's branch-protection lookup keys off the new branch.
  Persist base_branch in UpdateTaskPR.
- Cache 403 from /branches/.../protection (token lacks Administration:
  Read scope) the same way as 404 — otherwise every poller tick burns
  rate-limit quota retrying. Both PATClient and GHClient.
- usePRCIPopover: refetch on every popover-open transition (not just
  on updated_at change), via a wasEnabledRef gate. Restores the
  intended SWR semantics that the lastSyncedRef-only guard suppressed.
- groupChecksByWorkflow: prefer the URL of a job matching the group's
  bucket so clicking a "failed" workflow row navigates to a failing
  job, not an earlier passing one.

Tests:
- branch_protection_test.go: cache hit/miss/TTL/eviction, error
  not cached, no-rule cached, client-without-fetcher path.
- pat_client_test.go: TestPATClient_FetchBranchProtection table-test
  for 200/200-with-null/404/403/500.
- service_test.go: ChecksPopulated preserve-on-zero, accept real
  zero, base-branch retarget, change-publish for the new fields.

* refactor(github): trim associateTaskPR + drop unreachable PRAggregatePopover

- mock_controller.go: extract associateTaskPRRequest struct,
  buildTaskPRFromRequest, and ensureMockPRForRequest helpers so the
  handler is back under the 80-line Go limit.
- pr-ci-popover.tsx: remove unreachable PRAggregatePopover export.
  Multi-PR tasks currently use the existing DropdownMenu trigger
  (no hover popover), so the aggregate component was dead code.

* fix(github): drop unused anchorRef + tests for is{NotFound,Forbidden}Err

- pr-topbar-button.tsx: anchorRef was leftover from the dropped
  click-to-pin onInteractOutside guard. Removed.
- gh_client_test.go: tests for the new isNotFoundErr / isForbiddenErr
  helpers covering each accepted format and a few non-matches so a
  future gh CLI wording change is caught.

* fix(github): UnresolvedReviewThreadsPopulated guard + drop unreachable nil checks

- service.go: mirror the ChecksPopulated/preserve dance for
  UnresolvedReviewThreads. The REST single-PR poller (getPRStatus)
  doesn't fetch review threads, so without this guard every REST
  sync would clobber the GraphQL-populated value to 0 and emit a
  spurious github.task_pr.updated event. The GraphQL path
  (convertBatchedPRResult) sets the new flag.
- branch_protection.go: drop unreachable s == nil / fetcher == nil
  checks. fetchRequiredReviews is only invoked from SyncTaskPR on a
  service constructed via NewService, which always initialises the
  cache. After a successful type assertion, the interface value
  cannot be nil; the !ok branch already covers nil-interface inputs.
- service_test.go: new TestSyncTaskPR_UnresolvedThreads_PreservesOnLightweightSync
  covers the regression. Existing NewFieldsPublishEvent threads-change
  case updated to set UnresolvedReviewThreadsPopulated.

* refactor(web): drop CI popover progress bar — last-updated is enough

The animated progress bar was visual noise; the "updated Ns ago"
timestamp tells the user the same thing without the indicator. Footer
also hides entirely until the first fetch lands so an empty popover
doesn't show a useless "" line.

* fix(web): background-sync PRFeedback so popover is fresh on first hover

The on-hover SWR fetch was the only refresh path, so opening the popover
showed the previously-cached value while a new fetch raced behind it —
visibly stale until the refetch landed. The button icon, by contrast,
updates the moment a github.task_pr.updated WS push lands.

Add a usePRFeedbackBackgroundSync hook mounted at the PRTopbarButton
that subscribes to the same pr.updated_at change signal and refetches
PRFeedback into the cache in the background. The popover hook still
fires an on-open refetch as a safety net for the very first hover
(before any sync). No extra polling — fetches are gated on real
TaskPR changes, matching the icon's cadence.

* feat(web): CI status chip in chat status bar + tweak elapsed label

- New <PRStatusChip> renders a compact colored circle in the chat
  status bar (left of the TodoIndicator, just above the input). Hover
  opens the same PRCIPopover anchored to the chip's top edge so the
  card expands upward — matching the user's "open bottom-up" ask. The
  chip mounts the background-sync hook so the popover is fresh on
  first hover even when the top-bar PR button isn't visible.
- elapsedLabel: "just now" → "updated just now" so the footer reads
  the same regardless of how recently the cache was refreshed.

* fix(web): chip color was missing — use static class map for Tailwind JIT

\`getPRStatusColor().replace("text-", "bg-")\` produced class strings at
runtime, which Tailwind's content scanner doesn't pick up — the chip
rendered with no background. Replace with a static lookup so each
literal `bg-*` class appears in the source and gets compiled into the
bundle.

* fix(web): chip uses currentColor SVG so the dot actually renders

The previous bg-* approach relied on Tailwind compiling the literal
class strings. Even with a static map some palette entries (notably
bg-muted-foreground) didn't surface as a usable utility, so the chip
remained transparent. Apply getPRStatusColor's text-* class to the
button wrapper and fill an SVG circle with currentColor — the text-*
utilities are already compiled (PRTaskIcon uses them) so the dot
is guaranteed to render in the right color.

* fix(web): redesign PR status chip — clipboard icon + status glyph

- Move chip to right of TodoIndicator (was left).
- Render as "[clipboard icon] [status glyph]" instead of a bare circle:
  passed → green CircleCheck, failed → red CircleX, in_progress →
  yellow Loader2 (spinning), merged/neutral → muted dot. Status icons
  reuse already-compiled text-* utilities so colors render reliably.

* fix(github): ReviewCount = approved-reviewer count + ReviewCountsPopulated guard

Two bugs feeding the popover's "Approved (0)" misreport:

- Semantic: REST path set ReviewCount to len(reviews), which double-counts
  authors who left multiple reviews and includes COMMENTED rows. Replace
  with countApprovedReviewers — distinct authors whose latest review
  state is APPROVED. GraphQL converter gets the parallel
  countApprovedReviewerNodes helper and also populates PendingReviewCount
  from ReviewRequests.TotalCount (was unset, so the chip's "(K requested)"
  suffix was always missing).

- Clobber: GraphQL polls used to write ReviewCount/PendingReviewCount=0
  on every cycle because the converter never set them. Add
  ReviewCountsPopulated to PRStatus and gate SyncTaskPR's writes on it
  the same way ChecksPopulated already does, so a partial sync path
  preserves the persisted values instead of resetting them to zero.

* fix(web): popover nitpicks (icon, review row, indent, badge)

- Chip icon: ClipboardCheck → ListCheck.
- PRReviewRow always renders (drop the early-return). Fresh PRs with
  no approvals + no protection rule now show "Awaiting review" instead
  of vanishing.
- Indent workflow rows under the In Progress / Failed group headers
  (pl-5) so the hierarchy reads more clearly.
- In-progress workflow badge: "0/1 ran" → "1 running". The old phrasing
  hid whether the job had even started.

* feat(web): stacked pass-rate progress bar in CI popover

Mirrors TodoIndicator's progress bar at the top of the CI section, but
split into three coloured segments:
  green (passed) | yellow (in_progress) | red (failed)
sized proportionally to each bucket's count. The label reads
"Pass rate · K/N (P%)" so the user gets the same at-a-glance summary
TODOs shows. Skipped/cancelled-but-not-failed jobs aren't counted —
the bar always reflects the actionable picture.

* fix(web): right-align review counts + drop chip hover bg

- Move approval/required counts to the right edge of the review row
  ("Approved" on the left, "1 / 2" on the right), mirroring the
  bucket-row layout. The "(K requested)" suffix becomes a "· K requested"
  trailing fragment on the right side.
- PRStatusChip: drop hover:bg-accent/50 so the trigger doesn't grow a
  background plate when the popover is open.

* fix(web): switch CI chip icon to IconChecklist

* fix(github): clear bot review-comment backlog

Real correctness fixes:
- pr-status-chip: pending checks / pending review now beat
  checks_state === "success" in chipStatus precedence — a PR with
  CI green but reviewers outstanding is no longer rendered as
  "passed".
- branch_protection: drop the unreachable Reset() method.
- pr-topbar-button: stop double-mounting usePRFeedbackBackgroundSync;
  the chip already covers it.
- use-pr-ci-popover: dedupe key combines prFeedbackKey + updated_at
  so switching tasks with same-timestamp PRs still refetches.
- use-pr-ci-popover: drop stale comment about the removed progress bar.

Refactor:
- client_helpers + graphql: extract reviewSample +
  latestReviewStateByAuthor helper so the three near-identical
  per-reviewer dedup loops share one implementation.

Tests:
- countApprovedReviewers + reduceReviewSummary unit tests.
- TestSyncTaskPR_ReviewCounts_PreservesOnLightweightSync +
  AcceptsRealZero mirror the existing ChecksPopulated guards.
- groupChecksByWorkflow distinct-URL test verifies the failed-job
  URL-selection fix.
- branch_protection TTL tests now use testing/synctest — instant
  virtual time, no real-sleep flake on CI.

* fix(web): clicking the CI chip no longer closes the popover

HoverCard treats the trigger button as outside the content's bounding
box, so a click on the chip fired Radix's onPointerDownOutside and
auto-closed the popover. Add a triggerRef + onPointerDownOutside guard
on HoverCardContent that filters out clicks landing on the trigger —
clicking the chip is now a no-op while the popover stays open via hover.
2026-05-11 16:55:58 +01:00

694 lines
22 KiB
Go

package github
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
const (
githubAPIBase = "https://api.github.com"
githubAccept = "application/vnd.github+json"
githubAPIVersion = "2022-11-28"
)
// GitHubAPIError represents an error response from the GitHub API with a status code.
type GitHubAPIError struct {
StatusCode int
Endpoint string
Body string
}
func (e *GitHubAPIError) Error() string {
return fmt.Sprintf("GitHub API %s returned %d: %s", e.Endpoint, e.StatusCode, e.Body)
}
// PATClient implements Client using a GitHub Personal Access Token.
type PATClient struct {
token string
httpClient *http.Client
username string // cached after first GetAuthenticatedUser call
rateTracker *RateTracker
}
// NewPATClient creates a new PAT-based GitHub client.
func NewPATClient(token string) *PATClient {
return &PATClient{
token: token,
httpClient: &http.Client{
Timeout: 30 * time.Second,
},
}
}
// WithRateTracker attaches a rate tracker so response headers are recorded.
// Returns the client for chaining; safe to call before any requests are made.
func (c *PATClient) WithRateTracker(t *RateTracker) *PATClient {
c.rateTracker = t
return c
}
// recordRateHeaders feeds rate-limit data from a response into the tracker.
// endpoint is used to pick the default resource bucket when the response
// omits the X-RateLimit-Resource header.
func (c *PATClient) recordRateHeaders(resp *http.Response, endpoint string) {
if c.rateTracker == nil || resp == nil {
return
}
defaultResource := ResourceCore
if strings.HasPrefix(endpoint, "/search/") {
defaultResource = ResourceSearch
} else if strings.HasPrefix(endpoint, "/graphql") {
defaultResource = ResourceGraphQL
}
snap, headersOK := parseRateHeaders(resp, defaultResource)
if headersOK {
c.rateTracker.Record(snap)
}
if !isRateLimitStatus(resp.StatusCode) {
return
}
// On a 429, prefer the real X-RateLimit-Reset over the synthetic 1h
// fallback. parseRateHeaders may return ok=true with Remaining>0 if the
// secondary-limit response carried stale headers — only skip the
// fallback when the headers themselves report exhaustion (Remaining<=0
// + future ResetAt). Otherwise fall through to the conservative pause.
if headersOK && snap.Exhausted() {
return
}
c.rateTracker.markRateExhausted(defaultResource, time.Time{})
}
// isRateLimitStatus returns true for status codes GitHub uses to signal
// primary or secondary rate-limit exhaustion. 403 is documented for both
// abuse-detection and primary limits when the body indicates so; 429 is
// secondary limits.
func isRateLimitStatus(status int) bool {
return status == http.StatusTooManyRequests
}
// maybeMarkRateExhaustedFromBody flags a rate-limit hit when GitHub returned
// a 403/429 whose body contains the rate-limit prose. The headers may be
// missing on these responses (esp. secondary limits), so the body is the
// authoritative signal.
func (c *PATClient) maybeMarkRateExhaustedFromBody(endpoint string, status int, body []byte) {
if c.rateTracker == nil {
return
}
if status != http.StatusForbidden && status != http.StatusTooManyRequests {
return
}
lower := strings.ToLower(string(body))
if !strings.Contains(lower, "rate limit") && !strings.Contains(lower, "abuse detection") {
return
}
resource := ResourceCore
if strings.HasPrefix(endpoint, "/search/") {
resource = ResourceSearch
} else if strings.HasPrefix(endpoint, "/graphql") {
resource = ResourceGraphQL
}
// If recordRateHeaders already captured a real reset for this bucket on
// the same response, don't clobber it with the synthetic 1h fallback.
if existing, ok := c.rateTracker.Snapshot(resource); ok && existing.Exhausted() {
return
}
c.rateTracker.markRateExhausted(resource, time.Time{})
}
// setGitHubHeaders sets the common Authorization, Accept, and API version headers.
func (c *PATClient) setGitHubHeaders(req *http.Request) {
req.Header.Set("Authorization", "token "+c.token)
req.Header.Set("Accept", githubAccept)
req.Header.Set("X-GitHub-Api-Version", githubAPIVersion)
}
func (c *PATClient) IsAuthenticated(ctx context.Context) (bool, error) {
_, err := c.GetAuthenticatedUser(ctx)
return err == nil, nil
}
func (c *PATClient) GetAuthenticatedUser(ctx context.Context) (string, error) {
if c.username != "" {
return c.username, nil
}
var user struct {
Login string `json:"login"`
}
if err := c.get(ctx, "/user", &user); err != nil {
return "", err
}
c.username = user.Login
return c.username, nil
}
func (c *PATClient) GetPR(ctx context.Context, owner, repo string, number int) (*PR, error) {
var raw patPR
endpoint := fmt.Sprintf("/repos/%s/%s/pulls/%d", owner, repo, number)
if err := c.get(ctx, endpoint, &raw); err != nil {
return nil, fmt.Errorf("get PR #%d: %w", number, err)
}
return convertPatPR(&raw, owner, repo), nil
}
func (c *PATClient) FindPRByBranch(ctx context.Context, owner, repo, branch string) (*PR, error) {
var raw []patPR
endpoint := fmt.Sprintf("/repos/%s/%s/pulls?head=%s:%s&state=open&per_page=1",
owner, repo, owner, branch)
if err := c.get(ctx, endpoint, &raw); err != nil {
return nil, fmt.Errorf("find PR by branch: %w", err)
}
if len(raw) == 0 {
return nil, nil
}
return convertPatPR(&raw[0], owner, repo), nil
}
func (c *PATClient) ListAuthoredPRs(ctx context.Context, owner, repo string) ([]*PR, error) {
user, err := c.GetAuthenticatedUser(ctx)
if err != nil {
return nil, err
}
var raw []patPR
endpoint := fmt.Sprintf("/repos/%s/%s/pulls?state=open&per_page=100", owner, repo)
if err := c.get(ctx, endpoint, &raw); err != nil {
return nil, fmt.Errorf("list PRs: %w", err)
}
var result []*PR
for i := range raw {
if raw[i].User.Login == user {
result = append(result, convertPatPR(&raw[i], owner, repo))
}
}
return result, nil
}
func (c *PATClient) ListReviewRequestedPRs(ctx context.Context, scope, filter, customQuery string) ([]*PR, error) {
query := buildReviewSearchQuery(scope, filter, customQuery)
var result struct {
Items []patSearchItem `json:"items"`
}
endpoint := "/search/issues?q=" + url.QueryEscape(query) + "&per_page=50"
if err := c.get(ctx, endpoint, &result); err != nil {
return nil, fmt.Errorf("search review-requested: %w", err)
}
prs := make([]*PR, len(result.Items))
for i, item := range result.Items {
prs[i] = convertSearchItemToPR(
item.Number, item.Title, item.HTMLURL, item.State,
item.User.Login, item.RepositoryURL, item.Draft,
item.CreatedAt, item.UpdatedAt,
)
}
return prs, nil
}
func (c *PATClient) SearchPRs(ctx context.Context, filter, customQuery string) ([]*PR, error) {
page, err := c.SearchPRsPaged(ctx, filter, customQuery, 1, 50)
if err != nil {
return nil, err
}
return page.PRs, nil
}
func (c *PATClient) SearchPRsPaged(ctx context.Context, filter, customQuery string, page, perPage int) (*PRSearchPage, error) {
page, perPage = clampSearchPage(page, perPage)
query := buildPRSearchQuery(filter, customQuery)
var result struct {
TotalCount int `json:"total_count"`
Items []patSearchItem `json:"items"`
}
endpoint := fmt.Sprintf("/search/issues?q=%s&per_page=%d&page=%d",
url.QueryEscape(query), perPage, page)
if err := c.get(ctx, endpoint, &result); err != nil {
return nil, fmt.Errorf("search PRs: %w", err)
}
prs := make([]*PR, len(result.Items))
for i, item := range result.Items {
prs[i] = convertSearchItemToPR(
item.Number, item.Title, item.HTMLURL, item.State,
item.User.Login, item.RepositoryURL, item.Draft,
item.CreatedAt, item.UpdatedAt,
)
}
return &PRSearchPage{PRs: prs, TotalCount: result.TotalCount, Page: page, PerPage: perPage}, nil
}
func (c *PATClient) ListIssues(ctx context.Context, filter, customQuery string) ([]*Issue, error) {
page, err := c.ListIssuesPaged(ctx, filter, customQuery, 1, 50)
if err != nil {
return nil, err
}
return page.Issues, nil
}
func (c *PATClient) ListIssuesPaged(ctx context.Context, filter, customQuery string, page, perPage int) (*IssueSearchPage, error) {
page, perPage = clampSearchPage(page, perPage)
query := buildIssueSearchQuery(filter, customQuery)
var result struct {
TotalCount int `json:"total_count"`
Items []issueSearchItem `json:"items"`
}
endpoint := fmt.Sprintf("/search/issues?q=%s&per_page=%d&page=%d",
url.QueryEscape(query), perPage, page)
if err := c.get(ctx, endpoint, &result); err != nil {
return nil, fmt.Errorf("search issues: %w", err)
}
issues := parseIssueSearchResults(result.Items)
return &IssueSearchPage{Issues: issues, TotalCount: result.TotalCount, Page: page, PerPage: perPage}, nil
}
func (c *PATClient) GetIssueState(ctx context.Context, owner, repo string, number int) (string, error) {
var result struct {
State string `json:"state"`
}
endpoint := fmt.Sprintf("/repos/%s/%s/issues/%d", owner, repo, number)
if err := c.get(ctx, endpoint, &result); err != nil {
return "", fmt.Errorf("get issue state: %w", err)
}
return result.State, nil
}
func (c *PATClient) ListUserOrgs(ctx context.Context) ([]GitHubOrg, error) {
var raw []struct {
Login string `json:"login"`
AvatarURL string `json:"avatar_url"`
}
if err := c.get(ctx, "/user/orgs?per_page=100", &raw); err != nil {
return nil, fmt.Errorf("list user orgs: %w", err)
}
orgs := make([]GitHubOrg, len(raw))
for i, r := range raw {
orgs[i] = GitHubOrg{Login: r.Login, AvatarURL: r.AvatarURL}
}
return orgs, nil
}
func (c *PATClient) SearchOrgRepos(ctx context.Context, org, query string, limit int) ([]GitHubRepo, error) {
q := "org:" + org
if query != "" {
q += " " + query
}
if limit <= 0 {
limit = 20
}
var result struct {
Items []struct {
FullName string `json:"full_name"`
Owner struct {
Login string `json:"login"`
} `json:"owner"`
Name string `json:"name"`
Private bool `json:"private"`
} `json:"items"`
}
endpoint := fmt.Sprintf("/search/repositories?q=%s&per_page=%d", url.QueryEscape(q), limit)
if err := c.get(ctx, endpoint, &result); err != nil {
return nil, fmt.Errorf("search org repos: %w", err)
}
repos := make([]GitHubRepo, len(result.Items))
for i, item := range result.Items {
repos[i] = GitHubRepo{
FullName: item.FullName,
Owner: item.Owner.Login,
Name: item.Name,
Private: item.Private,
}
}
return repos, nil
}
func (c *PATClient) ListPRReviews(ctx context.Context, owner, repo string, number int) ([]PRReview, error) {
var raw []struct {
ID int64 `json:"id"`
State string `json:"state"`
Body string `json:"body"`
SubmittedAt time.Time `json:"submitted_at"`
User struct {
Login string `json:"login"`
AvatarURL string `json:"avatar_url"`
} `json:"user"`
}
endpoint := fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews", owner, repo, number)
if err := c.get(ctx, endpoint, &raw); err != nil {
return nil, err
}
reviews := make([]PRReview, len(raw))
for i, r := range raw {
reviews[i] = PRReview{
ID: r.ID,
Author: r.User.Login,
AuthorAvatar: r.User.AvatarURL,
State: r.State,
Body: r.Body,
CreatedAt: r.SubmittedAt,
}
}
return reviews, nil
}
func (c *PATClient) ListPRComments(ctx context.Context, owner, repo string, number int, since *time.Time) ([]PRComment, error) {
endpoint := fmt.Sprintf("/repos/%s/%s/pulls/%d/comments?per_page=100", owner, repo, number)
if since != nil {
endpoint += "&since=" + url.QueryEscape(since.Format(time.RFC3339))
}
var reviewRaw []ghComment
if err := c.get(ctx, endpoint, &reviewRaw); err != nil {
return nil, err
}
issueEndpoint := fmt.Sprintf("/repos/%s/%s/issues/%d/comments?per_page=100", owner, repo, number)
if since != nil {
issueEndpoint += "&since=" + url.QueryEscape(since.Format(time.RFC3339))
}
var issueRaw []ghIssueComment
if err := c.get(ctx, issueEndpoint, &issueRaw); err != nil {
return nil, err
}
return mergeAndSortPRComments(convertRawComments(reviewRaw), convertRawIssueComments(issueRaw)), nil
}
func (c *PATClient) ListCheckRuns(ctx context.Context, owner, repo, ref string) ([]CheckRun, error) {
var checkRunsResult struct {
CheckRuns []ghCheckRun `json:"check_runs"`
}
endpoint := fmt.Sprintf("/repos/%s/%s/commits/%s/check-runs", owner, repo, ref)
if err := c.get(ctx, endpoint, &checkRunsResult); err != nil {
return nil, err
}
var statusResult struct {
Statuses []ghStatusContext `json:"statuses"`
}
statusEndpoint := fmt.Sprintf("/repos/%s/%s/commits/%s/status", owner, repo, ref)
if err := c.get(ctx, statusEndpoint, &statusResult); err != nil {
return nil, err
}
return mergeChecks(
convertRawCheckRuns(checkRunsResult.CheckRuns),
convertRawStatusContexts(statusResult.Statuses),
), nil
}
func (c *PATClient) GetPRFeedback(ctx context.Context, owner, repo string, number int) (*PRFeedback, error) {
return getPRFeedback(ctx, c, owner, repo, number)
}
func (c *PATClient) GetPRStatus(ctx context.Context, owner, repo string, number int) (*PRStatus, error) {
return getPRStatus(ctx, c, owner, repo, number)
}
func (c *PATClient) ListPRFiles(ctx context.Context, owner, repo string, number int) ([]PRFile, error) {
var raw []ghPRFile
endpoint := fmt.Sprintf("/repos/%s/%s/pulls/%d/files?per_page=100", owner, repo, number)
if err := c.get(ctx, endpoint, &raw); err != nil {
return nil, fmt.Errorf("list PR files: %w", err)
}
return convertRawPRFiles(raw), nil
}
func (c *PATClient) ListPRCommits(ctx context.Context, owner, repo string, number int) ([]PRCommitInfo, error) {
var raw []ghPRCommit
endpoint := fmt.Sprintf("/repos/%s/%s/pulls/%d/commits?per_page=100", owner, repo, number)
if err := c.get(ctx, endpoint, &raw); err != nil {
return nil, fmt.Errorf("list PR commits: %w", err)
}
return convertRawPRCommits(raw), nil
}
func (c *PATClient) ListRepoBranches(ctx context.Context, owner, repo string) ([]RepoBranch, error) {
var branches []RepoBranch
endpoint := fmt.Sprintf("/repos/%s/%s/branches?per_page=100", owner, repo)
for endpoint != "" {
var page []struct {
Name string `json:"name"`
}
nextLink, err := c.getPaginated(ctx, endpoint, &page)
if err != nil {
return nil, fmt.Errorf("list repo branches: %w", err)
}
for _, b := range page {
branches = append(branches, RepoBranch{Name: b.Name})
}
endpoint = nextLink
}
return branches, nil
}
func (c *PATClient) SubmitReview(ctx context.Context, owner, repo string, number int, event, body string) error {
endpoint := fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews", owner, repo, number)
payload := map[string]string{"event": event}
if body != "" {
payload["body"] = body
}
jsonBody, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("marshal review payload: %w", err)
}
return c.post(ctx, endpoint, jsonBody)
}
func (c *PATClient) post(ctx context.Context, endpoint string, body []byte) error {
u := githubAPIBase + endpoint
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(body))
if err != nil {
return err
}
c.setGitHubHeaders(req)
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("request POST %s: %w", endpoint, err)
}
defer func() { _ = resp.Body.Close() }()
c.recordRateHeaders(resp, endpoint)
if resp.StatusCode >= 400 {
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
c.maybeMarkRateExhaustedFromBody(endpoint, resp.StatusCode, respBody)
return fmt.Errorf("GitHub API POST %s returned %d: %s", endpoint, resp.StatusCode, string(respBody))
}
return nil
}
func (c *PATClient) get(ctx context.Context, endpoint string, result interface{}) error {
url := githubAPIBase + endpoint
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
c.setGitHubHeaders(req)
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("request %s: %w", endpoint, err)
}
defer func() { _ = resp.Body.Close() }()
c.recordRateHeaders(resp, endpoint)
if resp.StatusCode >= 400 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
c.maybeMarkRateExhaustedFromBody(endpoint, resp.StatusCode, body)
return &GitHubAPIError{StatusCode: resp.StatusCode, Endpoint: endpoint, Body: string(body)}
}
return json.NewDecoder(resp.Body).Decode(result)
}
// getPaginated is like get but also returns the "next" link from the Link header, if any.
func (c *PATClient) getPaginated(ctx context.Context, endpoint string, result interface{}) (string, error) {
u := githubAPIBase + endpoint
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return "", err
}
c.setGitHubHeaders(req)
resp, err := c.httpClient.Do(req)
if err != nil {
return "", fmt.Errorf("request %s: %w", endpoint, err)
}
defer func() { _ = resp.Body.Close() }()
c.recordRateHeaders(resp, endpoint)
if resp.StatusCode >= 400 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
c.maybeMarkRateExhaustedFromBody(endpoint, resp.StatusCode, body)
return "", &GitHubAPIError{StatusCode: resp.StatusCode, Endpoint: endpoint, Body: string(body)}
}
if err := json.NewDecoder(resp.Body).Decode(result); err != nil {
return "", err
}
return parseNextLink(resp.Header.Get("Link")), nil
}
// parseNextLink extracts the "next" URL path+query from a GitHub Link header.
func parseNextLink(header string) string {
if header == "" {
return ""
}
for _, part := range strings.Split(header, ",") {
part = strings.TrimSpace(part)
if !strings.Contains(part, `rel="next"`) {
continue
}
start := strings.Index(part, "<")
end := strings.Index(part, ">")
if start < 0 || end < 0 || end <= start {
continue
}
link := part[start+1 : end]
// Strip the base URL to return just the path+query for our get method
if strings.HasPrefix(link, githubAPIBase) {
return link[len(githubAPIBase):]
}
return link
}
return ""
}
// FetchBranchProtection looks up the branch protection rule on a repo's base
// branch via the REST API. A 404 is treated as "no rule configured" and a 403
// is treated as "no rule we can see" (token lacks Administration: Read scope).
// Both return HasRule=false with no error so the cache stores the negative
// result and we don't burn rate-limit quota retrying every poll cycle.
// Other errors propagate so callers can decide whether to retry.
func (c *PATClient) FetchBranchProtection(ctx context.Context, owner, repo, branch string) (BranchProtection, error) {
endpoint := fmt.Sprintf("/repos/%s/%s/branches/%s/protection", owner, repo, branch)
var raw struct {
RequiredPullRequestReviews *struct {
RequiredApprovingReviewCount int `json:"required_approving_review_count"`
} `json:"required_pull_request_reviews"`
}
if err := c.get(ctx, endpoint, &raw); err != nil {
var apiErr *GitHubAPIError
if errors.As(err, &apiErr) {
if apiErr.StatusCode == http.StatusNotFound || apiErr.StatusCode == http.StatusForbidden {
return BranchProtection{HasRule: false}, nil
}
}
return BranchProtection{}, err
}
if raw.RequiredPullRequestReviews == nil {
return BranchProtection{HasRule: true}, nil
}
return BranchProtection{
HasRule: true,
RequiredApprovingReviewCount: raw.RequiredPullRequestReviews.RequiredApprovingReviewCount,
}, nil
}
// patPR is the JSON shape from the GitHub REST API for PRs.
type patPR struct {
Number int `json:"number"`
Title string `json:"title"`
HTMLURL string `json:"html_url"`
Body string `json:"body"`
State string `json:"state"`
Draft bool `json:"draft"`
Mergeable *bool `json:"mergeable"`
MergeableState string `json:"mergeable_state"`
Additions int `json:"additions"`
Deletions int `json:"deletions"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
MergedAt *string `json:"merged_at"`
ClosedAt *string `json:"closed_at"`
RequestedReviewers []struct {
Login string `json:"login"`
} `json:"requested_reviewers"`
RequestedTeams []struct {
Slug string `json:"slug"`
Name string `json:"name"`
} `json:"requested_teams"`
User struct {
Login string `json:"login"`
} `json:"user"`
Head struct {
Ref string `json:"ref"`
SHA string `json:"sha"`
} `json:"head"`
Base struct {
Ref string `json:"ref"`
} `json:"base"`
}
type patSearchItem struct {
Number int `json:"number"`
Title string `json:"title"`
HTMLURL string `json:"html_url"`
State string `json:"state"`
Draft bool `json:"draft"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
RepositoryURL string `json:"repository_url"`
User struct {
Login string `json:"login"`
} `json:"user"`
}
func convertPatPR(raw *patPR, owner, repo string) *PR {
state := strings.ToLower(raw.State)
if raw.MergedAt != nil && *raw.MergedAt != "" {
state = prStateMerged
}
mergeable := false
if raw.Mergeable != nil {
mergeable = *raw.Mergeable
}
pr := &PR{
Number: raw.Number,
Title: raw.Title,
HTMLURL: raw.HTMLURL,
Body: raw.Body,
State: state,
HeadBranch: raw.Head.Ref,
HeadSHA: raw.Head.SHA,
BaseBranch: raw.Base.Ref,
AuthorLogin: raw.User.Login,
RepoOwner: owner,
RepoName: repo,
Draft: raw.Draft,
Mergeable: mergeable,
MergeableState: strings.ToLower(raw.MergeableState),
Additions: raw.Additions,
Deletions: raw.Deletions,
RequestedReviewers: convertPatRequestedReviewers(raw),
CreatedAt: raw.CreatedAt,
UpdatedAt: raw.UpdatedAt,
}
if raw.MergedAt != nil {
pr.MergedAt = parseTimePtr(*raw.MergedAt)
}
if raw.ClosedAt != nil {
pr.ClosedAt = parseTimePtr(*raw.ClosedAt)
}
return pr
}
func convertPatRequestedReviewers(raw *patPR) []RequestedReviewer {
reviewers := make([]RequestedReviewer, 0, len(raw.RequestedReviewers)+len(raw.RequestedTeams))
for _, reviewer := range raw.RequestedReviewers {
if reviewer.Login == "" {
continue
}
reviewers = append(reviewers, RequestedReviewer{Login: reviewer.Login, Type: reviewerTypeUser})
}
for _, team := range raw.RequestedTeams {
login := team.Slug
if login == "" {
login = team.Name
}
if login == "" {
continue
}
reviewers = append(reviewers, RequestedReviewer{Login: login, Type: reviewerTypeTeam})
}
return reviewers
}