Files
kandev/apps/backend/internal/github/client_helpers.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

699 lines
20 KiB
Go

package github
import (
"context"
"encoding/json"
"fmt"
"sort"
"strings"
"time"
)
// buildReviewSearchQuery assembles the full GitHub search query.
// When customQuery is non-empty, it is used verbatim as the entire query.
// Otherwise a query is built from scope + optional filter qualifier.
func buildReviewSearchQuery(scope, filter, customQuery string) string {
if customQuery != "" {
return customQuery
}
var base string
if scope == ReviewScopeUser {
base = "type:pr state:open user-review-requested:@me -is:draft"
} else {
base = "type:pr state:open review-requested:@me -is:draft"
}
if filter != "" {
base += " " + filter
}
return base
}
// getPRFeedback fetches aggregated feedback for a PR using any Client implementation.
// This shared function eliminates duplication between GHClient and PATClient.
func getPRFeedback(ctx context.Context, c Client, owner, repo string, number int) (*PRFeedback, error) {
pr, err := c.GetPR(ctx, owner, repo, number)
if err != nil {
return nil, err
}
reviews, err := c.ListPRReviews(ctx, owner, repo, number)
if err != nil {
return nil, err
}
comments, err := c.ListPRComments(ctx, owner, repo, number, nil)
if err != nil {
return nil, err
}
checks, err := c.ListCheckRuns(ctx, owner, repo, pr.HeadSHA)
if err != nil {
return nil, err
}
// Ensure non-nil slices so JSON serialization produces [] instead of null.
if reviews == nil {
reviews = []PRReview{}
}
if comments == nil {
comments = []PRComment{}
}
if checks == nil {
checks = []CheckRun{}
}
hasIssues := hasFailingChecks(checks) || hasChangesRequested(reviews)
return &PRFeedback{
PR: pr,
Reviews: reviews,
Comments: comments,
Checks: checks,
HasIssues: hasIssues,
}, nil
}
// getPRStatus fetches lightweight PR status using any Client implementation.
// Unlike getPRFeedback, it skips comments to reduce API calls.
func getPRStatus(ctx context.Context, c Client, owner, repo string, number int) (*PRStatus, error) {
pr, err := c.GetPR(ctx, owner, repo, number)
if err != nil {
return nil, err
}
reviews, err := c.ListPRReviews(ctx, owner, repo, number)
if err != nil {
return nil, err
}
checks, err := c.ListCheckRuns(ctx, owner, repo, pr.HeadSHA)
if err != nil {
return nil, err
}
if reviews == nil {
reviews = []PRReview{}
}
if checks == nil {
checks = []CheckRun{}
}
reviewState, pendingReviewCount := deriveReviewSyncState(pr, reviews)
total, passing := countCheckResults(checks)
return &PRStatus{
PR: pr,
ReviewState: reviewState,
ChecksState: computeOverallCheckStatus(checks),
MergeableState: pr.MergeableState,
// ReviewCount is the number of distinct reviewers whose latest review
// state is APPROVED — it's the value the popover renders as
// "Approved (N)" / "Approved N / M required". Counting raw review
// entries (`len(reviews)`) double-counts authors who left multiple
// reviews and also includes COMMENTED / CHANGES_REQUESTED rows.
ReviewCount: countApprovedReviewers(reviews),
PendingReviewCount: pendingReviewCount,
ChecksTotal: total,
ChecksPassing: passing,
// REST path actually counted check runs + reviews — distinguish
// from the batched-GraphQL path that only carries rollup state.
ChecksPopulated: true,
ReviewCountsPopulated: true,
}, nil
}
// reviewSample is a normalized review row consumed by latestReviewStateByAuthor.
// Adapter functions below convert PRReview (REST) and reviewNode (GraphQL)
// to this shape so the per-reviewer dedup rule is only spelled out once.
type reviewSample struct {
author string
state string
at time.Time
}
// latestReviewStateByAuthor reduces a list of reviews to "one entry per
// reviewer, latest binding state wins". COMMENTED and PENDING never
// override a prior APPROVED / CHANGES_REQUESTED for the same author so a
// reviewer who approved-then-commented still counts as approved.
// Anonymous reviewers (deleted users) get a unique synthetic key so each
// review still counts independently.
func latestReviewStateByAuthor(samples []reviewSample) map[string]reviewSample {
byAuthor := make(map[string]reviewSample, len(samples))
for _, s := range samples {
key := s.author
if key == "" {
key = "<anon>:" + s.at.UTC().Format(time.RFC3339Nano)
}
state := strings.ToUpper(s.state)
if state != reviewStateApproved && state != reviewStateChangesRequested {
if _, ok := byAuthor[key]; ok {
continue
}
}
prev, ok := byAuthor[key]
if !ok || !s.at.Before(prev.at) {
byAuthor[key] = reviewSample{author: s.author, state: state, at: s.at}
}
}
return byAuthor
}
// countApprovedAuthors counts distinct reviewers whose latest binding state is
// APPROVED. Shared between the REST and GraphQL count helpers.
func countApprovedAuthors(samples []reviewSample) int {
count := 0
for _, s := range latestReviewStateByAuthor(samples) {
if s.state == reviewStateApproved {
count++
}
}
return count
}
// reduceReviewSummary collapses the per-author map into a single overall
// review state. CHANGES_REQUESTED wins across authors; APPROVED otherwise;
// "" when nothing is binding. Shared between REST and GraphQL paths.
func reduceReviewSummary(samples []reviewSample) string {
hasApproval := false
for _, l := range latestReviewStateByAuthor(samples) {
switch l.state {
case reviewStateChangesRequested:
return computedReviewStateChangesRequested
case reviewStateApproved:
hasApproval = true
}
}
if hasApproval {
return computedReviewStateApproved
}
return ""
}
// countApprovedReviewers returns the number of distinct authors whose latest
// review state is APPROVED. REST-path adapter over the shared helper.
func countApprovedReviewers(reviews []PRReview) int {
samples := make([]reviewSample, len(reviews))
for i, r := range reviews {
samples[i] = reviewSample{author: r.Author, state: r.State, at: r.CreatedAt}
}
return countApprovedAuthors(samples)
}
// countCheckResults returns (total, passing) counts using the same logic as
// computeOverallCheckStatus: skipped/neutral and still-running checks are
// excluded from the total so the X/Y badge communicates pass rate rather
// than conflating in-flight checks with failures. The pending state is
// carried separately via ChecksState.
func countCheckResults(checks []CheckRun) (int, int) {
total, passing := 0, 0
for _, c := range checks {
if c.Status != checkStatusCompleted {
continue
}
switch c.Conclusion {
case checkConclusionSkipped, checkConclusionNeutral:
continue
case checkConclusionFail, checkConclusionTimedOut,
checkConclusionCancelled, checkConclusionActionRequired:
total++
default:
total++
passing++
}
}
return total, passing
}
// convertRawCheckRuns converts raw ghCheckRun structs into the domain CheckRun type.
func convertRawCheckRuns(raw []ghCheckRun) []CheckRun {
checks := make([]CheckRun, len(raw))
for i, cr := range raw {
conclusion := ""
if cr.Conclusion != nil {
conclusion = *cr.Conclusion
}
output := ""
if cr.Output.Summary != nil {
output = *cr.Output.Summary
}
checks[i] = CheckRun{
Name: cr.Name,
Source: checkSourceCheckRun,
Status: cr.Status,
Conclusion: conclusion,
HTMLURL: cr.HTMLURL,
Output: output,
StartedAt: parseTimePtr(cr.StartedAt),
CompletedAt: parseTimePtr(cr.CompletedAt),
}
}
return checks
}
// convertRawComments converts raw review comments into the domain PRComment type.
func convertRawComments(raw []ghComment) []PRComment {
comments := make([]PRComment, len(raw))
for i, c := range raw {
comments[i] = PRComment{
ID: c.ID,
Author: c.User.Login,
AuthorAvatar: c.User.AvatarURL,
AuthorIsBot: isGitHubBot(c.User.Type),
Body: c.Body,
Path: c.Path,
Line: c.Line,
Side: c.Side,
CommentType: commentTypeReview,
CreatedAt: c.CreatedAt,
UpdatedAt: c.UpdatedAt,
InReplyTo: c.InReplyTo,
}
}
return comments
}
// ghIssueComment is the JSON shape for issue comments from the GitHub API.
type ghIssueComment struct {
ID int64 `json:"id"`
Body string `json:"body"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
User struct {
Login string `json:"login"`
AvatarURL string `json:"avatar_url"`
Type string `json:"type"`
} `json:"user"`
}
// convertRawIssueComments converts PR conversation comments into PRComment rows.
func convertRawIssueComments(raw []ghIssueComment) []PRComment {
comments := make([]PRComment, len(raw))
for i, c := range raw {
comments[i] = PRComment{
ID: c.ID,
Author: c.User.Login,
AuthorAvatar: c.User.AvatarURL,
AuthorIsBot: isGitHubBot(c.User.Type),
Body: c.Body,
CommentType: commentTypeIssue,
CreatedAt: c.CreatedAt,
UpdatedAt: c.UpdatedAt,
}
}
return comments
}
// mergeAndSortPRComments combines review and issue comments and sorts by creation time.
func mergeAndSortPRComments(reviewComments, issueComments []PRComment) []PRComment {
comments := make([]PRComment, 0, len(reviewComments)+len(issueComments))
comments = append(comments, reviewComments...)
comments = append(comments, issueComments...)
sort.SliceStable(comments, func(i, j int) bool {
if comments[i].CreatedAt.Equal(comments[j].CreatedAt) {
return comments[i].ID < comments[j].ID
}
return comments[i].CreatedAt.Before(comments[j].CreatedAt)
})
return comments
}
func isGitHubBot(userType string) bool {
return strings.EqualFold(userType, githubUserTypeBot)
}
// ghStatusContext is the JSON shape from /commits/:ref/status.
type ghStatusContext struct {
Context string `json:"context"`
State string `json:"state"` // error, failure, pending, success
TargetURL string `json:"target_url"`
Description string `json:"description"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
// convertRawStatusContexts converts commit status contexts into CheckRun rows.
func convertRawStatusContexts(raw []ghStatusContext) []CheckRun {
checks := make([]CheckRun, len(raw))
for i, st := range raw {
status := checkStatusCompleted
conclusion := st.State
switch st.State {
case commitStatusSuccess:
conclusion = checkStatusSuccess
case commitStatusFailure, commitStatusError:
conclusion = checkConclusionFail
case commitStatusPending:
status = "in_progress"
conclusion = ""
}
checks[i] = CheckRun{
Name: st.Context,
Source: checkSourceStatusContext,
Status: status,
Conclusion: conclusion,
HTMLURL: st.TargetURL,
Output: st.Description,
StartedAt: parseTimePtr(st.CreatedAt),
}
if status == checkStatusCompleted {
checks[i].CompletedAt = parseTimePtr(st.UpdatedAt)
}
}
return checks
}
// mergeChecks deduplicates check runs and commit statuses by normalized name.
// Check-run source wins over status-context; among same-source duplicates the
// most recent entry (by StartedAt) is kept.
func mergeChecks(checkRuns, statusChecks []CheckRun) []CheckRun {
merged := make([]CheckRun, 0, len(checkRuns)+len(statusChecks))
byKey := make(map[string]int)
for _, check := range statusChecks {
key := checkMergeKey(check)
if idx, ok := byKey[key]; ok {
if isNewerCheck(check, merged[idx]) {
merged[idx] = check
}
continue
}
byKey[key] = len(merged)
merged = append(merged, check)
}
for _, check := range checkRuns {
key := checkMergeKey(check)
if idx, ok := byKey[key]; ok {
if merged[idx].Source == checkSourceStatusContext || isNewerCheck(check, merged[idx]) {
merged[idx] = check
}
continue
}
byKey[key] = len(merged)
merged = append(merged, check)
}
return merged
}
func checkMergeKey(check CheckRun) string {
return strings.ToLower(strings.TrimSpace(check.Name))
}
// isNewerCheck reports whether a started more recently than b.
func isNewerCheck(a, b CheckRun) bool {
if a.StartedAt == nil {
return false
}
if b.StartedAt == nil {
return true
}
return a.StartedAt.After(*b.StartedAt)
}
// convertSearchItemToPR converts common search result fields into a PR struct.
func convertSearchItemToPR(
number int, title, htmlURL, state, authorLogin, repositoryURL string,
draft bool, createdAt, updatedAt time.Time,
) *PR {
owner, repo := parseRepoURL(repositoryURL)
return &PR{
Number: number,
Title: title,
HTMLURL: htmlURL,
State: state,
AuthorLogin: authorLogin,
Draft: draft,
RepoOwner: owner,
RepoName: repo,
CreatedAt: createdAt,
UpdatedAt: updatedAt,
}
}
// clampSearchPage normalizes page and perPage to GitHub's Search API limits:
// page >= 1, 1 <= perPage <= 100. Defaults: page=1, perPage=50.
func clampSearchPage(page, perPage int) (int, int) {
if page < 1 {
page = 1
}
if perPage <= 0 {
perPage = 50
}
if perPage > 100 {
perPage = 100
}
return page, perPage
}
// hasTypeQualifier reports whether the query already pins the result type via
// `type:pr`, `type:issue`, `is:pr`, or `is:issue` (case-insensitive).
func hasTypeQualifier(query string) bool {
lower := strings.ToLower(query)
for _, tok := range strings.Fields(lower) {
switch tok {
case "type:pr", "type:issue", "is:pr", "is:issue":
return true
}
}
return false
}
// buildIssueSearchQuery assembles a GitHub search query for issues.
// The `type:issue` qualifier is always injected (unless the caller already
// pinned it) because `/search/issues` returns both PRs and issues otherwise.
func buildIssueSearchQuery(filter, customQuery string) string {
return buildSearchQuery("type:issue", filter, customQuery)
}
// buildPRSearchQuery assembles a GitHub search query for pull requests.
// The `type:pr` qualifier is always injected (unless the caller already pinned
// it) because `/search/issues` returns both PRs and issues otherwise.
func buildPRSearchQuery(filter, customQuery string) string {
return buildSearchQuery("type:pr", filter, customQuery)
}
func buildSearchQuery(typeQualifier, filter, customQuery string) string {
if customQuery != "" {
if hasTypeQualifier(customQuery) {
return customQuery
}
return typeQualifier + " " + customQuery
}
if filter != "" {
return typeQualifier + " " + filter
}
return typeQualifier
}
// issueSearchItem is an issue item from the GitHub search API.
type issueSearchItem struct {
Number int `json:"number"`
Title string `json:"title"`
Body string `json:"body"`
HTMLURL string `json:"html_url"`
State string `json:"state"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ClosedAt *string `json:"closed_at"`
RepositoryURL string `json:"repository_url"`
User struct {
Login string `json:"login"`
} `json:"user"`
Labels []struct {
Name string `json:"name"`
} `json:"labels"`
Assignees []struct {
Login string `json:"login"`
} `json:"assignees"`
PullRequest *struct {
URL string `json:"url"`
} `json:"pull_request"`
}
// convertSearchItemToIssue converts a search API item into an Issue struct.
func convertSearchItemToIssue(item issueSearchItem) *Issue {
owner, repo := parseRepoURL(item.RepositoryURL)
labels := make([]string, len(item.Labels))
for i, l := range item.Labels {
labels[i] = l.Name
}
assignees := make([]string, len(item.Assignees))
for i, a := range item.Assignees {
assignees[i] = a.Login
}
issue := &Issue{
Number: item.Number,
Title: item.Title,
Body: item.Body,
HTMLURL: item.HTMLURL,
State: item.State,
AuthorLogin: item.User.Login,
RepoOwner: owner,
RepoName: repo,
Labels: labels,
Assignees: assignees,
CreatedAt: item.CreatedAt,
UpdatedAt: item.UpdatedAt,
}
if item.ClosedAt != nil {
issue.ClosedAt = parseTimePtr(*item.ClosedAt)
}
return issue
}
// parseIssueSearchResults parses GitHub search API response items into Issue structs,
// filtering out any pull requests (which also appear in search/issues results).
func parseIssueSearchResults(items []issueSearchItem) []*Issue {
var issues []*Issue
for _, item := range items {
// GitHub search/issues returns both issues and PRs; skip PRs
if item.PullRequest != nil {
continue
}
issues = append(issues, convertSearchItemToIssue(item))
}
return issues
}
// latestReviewByAuthor returns a map of the most recent review per author.
func latestReviewByAuthor(reviews []PRReview) map[string]PRReview {
latest := make(map[string]PRReview)
for _, r := range reviews {
existing, ok := latest[r.Author]
if !ok || r.CreatedAt.After(existing.CreatedAt) {
latest[r.Author] = r
}
}
return latest
}
// hasFailingChecks returns true if any completed check run has failed.
func hasFailingChecks(checks []CheckRun) bool {
for _, c := range checks {
if c.Status == checkStatusCompleted && c.Conclusion == checkConclusionFail {
return true
}
}
return false
}
// hasChangesRequested returns true if any review has requested changes.
func hasChangesRequested(reviews []PRReview) bool {
for _, r := range reviews {
if r.State == reviewStateChangesRequested {
return true
}
}
return false
}
// --- PR files and commits parsing ---
// ghPRFile is the JSON shape from the GitHub REST API for PR files.
type ghPRFile struct {
Filename string `json:"filename"`
Status string `json:"status"` // added, removed, modified, renamed, copied, changed, unchanged
Additions int `json:"additions"`
Deletions int `json:"deletions"`
Patch string `json:"patch"`
PreviousFilename string `json:"previous_filename"`
}
// ghPRCommit is the JSON shape from the GitHub REST API for PR commits.
type ghPRCommit struct {
SHA string `json:"sha"`
Commit struct {
Message string `json:"message"`
Author struct {
Date string `json:"date"`
} `json:"author"`
} `json:"commit"`
Author *struct {
Login string `json:"login"`
} `json:"author"`
}
// parsePRFilesJSON parses the JSON response from the PR files API.
func parsePRFilesJSON(data string) ([]PRFile, error) {
var raw []ghPRFile
if err := json.Unmarshal([]byte(data), &raw); err != nil {
return nil, fmt.Errorf("parse PR files: %w", err)
}
return convertRawPRFiles(raw), nil
}
// convertRawPRFiles converts raw GitHub API file structs to domain PRFile.
func convertRawPRFiles(raw []ghPRFile) []PRFile {
files := make([]PRFile, len(raw))
for i, f := range raw {
files[i] = PRFile{
Filename: f.Filename,
Status: f.Status,
Additions: f.Additions,
Deletions: f.Deletions,
Patch: buildFullDiff(f.Filename, f.Status, f.Patch, f.PreviousFilename),
OldPath: f.PreviousFilename,
}
}
return files
}
// buildFullDiff wraps a GitHub patch fragment into a complete unified diff.
func buildFullDiff(filename, status, patch, previousFilename string) string {
if patch == "" {
return ""
}
var b strings.Builder
switch status {
case "added":
fmt.Fprintf(&b, "diff --git a/%s b/%s\n", filename, filename)
b.WriteString("new file mode 100644\n")
fmt.Fprintf(&b, "--- /dev/null\n")
fmt.Fprintf(&b, "+++ b/%s\n", filename)
case "removed":
fmt.Fprintf(&b, "diff --git a/%s b/%s\n", filename, filename)
b.WriteString("deleted file mode 100644\n")
fmt.Fprintf(&b, "--- a/%s\n", filename)
fmt.Fprintf(&b, "+++ /dev/null\n")
case "renamed":
oldName := previousFilename
if oldName == "" {
oldName = filename
}
fmt.Fprintf(&b, "diff --git a/%s b/%s\n", oldName, filename)
fmt.Fprintf(&b, "rename from %s\n", oldName)
fmt.Fprintf(&b, "rename to %s\n", filename)
fmt.Fprintf(&b, "--- a/%s\n", oldName)
fmt.Fprintf(&b, "+++ b/%s\n", filename)
default:
fmt.Fprintf(&b, "diff --git a/%s b/%s\n", filename, filename)
fmt.Fprintf(&b, "--- a/%s\n", filename)
fmt.Fprintf(&b, "+++ b/%s\n", filename)
}
b.WriteString(patch)
if !strings.HasSuffix(patch, "\n") {
b.WriteByte('\n')
}
return b.String()
}
// parsePRCommitsJSON parses the JSON response from the PR commits API.
func parsePRCommitsJSON(data string) ([]PRCommitInfo, error) {
var raw []ghPRCommit
if err := json.Unmarshal([]byte(data), &raw); err != nil {
return nil, fmt.Errorf("parse PR commits: %w", err)
}
return convertRawPRCommits(raw), nil
}
// convertRawPRCommits converts raw GitHub API commit structs to domain PRCommitInfo.
func convertRawPRCommits(raw []ghPRCommit) []PRCommitInfo {
commits := make([]PRCommitInfo, len(raw))
for i, c := range raw {
author := ""
if c.Author != nil {
author = c.Author.Login
}
// First line of commit message
msg := c.Commit.Message
if idx := strings.Index(msg, "\n"); idx >= 0 {
msg = msg[:idx]
}
commits[i] = PRCommitInfo{
SHA: c.SHA,
Message: msg,
AuthorLogin: author,
AuthorDate: c.Commit.Author.Date,
}
}
return commits
}