| 1 | package github |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "net/http" |
| 10 | "os/exec" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | // PRSnapshot is what one poll reads about a PR. |
| 17 | type PRSnapshot struct { |
| 18 | Number int |
| 19 | State string // OPEN, MERGED, CLOSED or StateNoAccess |
| 20 | CI string // passing, failing or pending |
| 21 | Conflicts string // yes, none or unknown |
| 22 | ReviewDecision string // APPROVED, CHANGES_REQUESTED, REVIEW_REQUIRED or "" |
| 23 | Draft bool |
| 24 | Labels []string |
| 25 | HeadSHA string |
| 26 | BaseSHA string // the base branch's tip; "" when the branch is gone |
| 27 | Activity *PRActivity // nil unless asked for |
| 28 | } |
| 29 | |
| 30 | // PRActivity is the review activity on a PR that decides whether trusted |
| 31 | // reviewers wait on a fix. |
| 32 | type PRActivity struct { |
| 33 | Operator string // the account gh runs as |
| 34 | Author string |
| 35 | Reviews []Review |
| 36 | Comments []IssueComment // the PR conversation |
| 37 | LastCommitAt time.Time // the head commit's committer date |
| 38 | } |
| 39 | |
| 40 | // Review is a submitted review and the bodies of its inline comments. |
| 41 | type Review struct { |
| 42 | ID int64 |
| 43 | Author string |
| 44 | State string |
| 45 | Body string |
| 46 | SubmittedAt time.Time |
| 47 | Comments []string |
| 48 | } |
| 49 | |
| 50 | // IssueComment is a PR conversation comment. |
| 51 | type IssueComment struct { |
| 52 | Author string |
| 53 | Body string |
| 54 | UpdatedAt time.Time |
| 55 | } |
| 56 | |
| 57 | // RateLimitError is GitHub refusing a call for a primary or secondary rate |
| 58 | // limit. Until is when GitHub says to try again, or a short backoff when it |
| 59 | // doesn't say. |
| 60 | type RateLimitError struct { |
| 61 | Until time.Time |
| 62 | } |
| 63 | |
| 64 | func (e *RateLimitError) Error() string { |
| 65 | return "GitHub rate-limited until " + e.Until.Format("15:04") |
| 66 | } |
| 67 | |
| 68 | // rateLimitBackoff is how long to wait on a rate limit that names no time. |
| 69 | const rateLimitBackoff = 2 * time.Minute |
| 70 | |
| 71 | // prFields are the fields of a PR one poll reads; prActivityFields are added |
| 72 | // when review activity is asked for. Bot logins come without GraphQL's |
| 73 | // "[bot]" suffix, so __typename restores it. |
| 74 | const ( |
| 75 | prFields = `state isDraft mergeable reviewDecision headRefOid |
| 76 | baseRef { target { oid } } |
| 77 | labels(first: 50) { nodes { name } } |
| 78 | commits(last: 1) { nodes { commit { committedDate statusCheckRollup { state } } } }` |
| 79 | prActivityFields = ` |
| 80 | author { __typename login } |
| 81 | reviews(last: 30) { nodes { databaseId author { __typename login } state submittedAt body comments(first: 10) { nodes { body } } } } |
| 82 | comments(last: 100) { nodes { author { __typename login } body updatedAt } }` |
| 83 | ) |
| 84 | |
| 85 | // PRSnapshots reads, in one GraphQL query, the given PRs of the repository |
| 86 | // slug (owner/repo). A PR GitHub can't find, or whose repository it can't, |
| 87 | // reads StateNoAccess. A rate limit is a *RateLimitError. |
| 88 | func (c *GHCLIClient) PRSnapshots(ctx context.Context, slug string, numbers []int, activity bool) (map[int]*PRSnapshot, error) { |
| 89 | owner, name, ok := strings.Cut(slug, "/") |
| 90 | if !ok || len(numbers) == 0 { |
| 91 | return nil, fmt.Errorf("PR snapshots: bad request for %q", slug) |
| 92 | } |
| 93 | fields := prFields |
| 94 | if activity { |
| 95 | fields += prActivityFields |
| 96 | } |
| 97 | var q strings.Builder |
| 98 | q.WriteString("query {") |
| 99 | if activity { |
| 100 | q.WriteString(" viewer { login }") |
| 101 | } |
| 102 | fmt.Fprintf(&q, " repository(owner: %q, name: %q) {", owner, name) |
| 103 | for _, n := range numbers { |
| 104 | fmt.Fprintf(&q, " pr%d: pullRequest(number: %d) { ...f }", n, n) |
| 105 | } |
| 106 | q.WriteString(" } } fragment f on PullRequest { " + fields + " }") |
| 107 | |
| 108 | body, err := c.api(ctx, "graphql", "-f", "query="+q.String()) |
| 109 | if err != nil { |
| 110 | var rl *RateLimitError |
| 111 | if !errors.As(err, &rl) && IsNoAccess(err.Error()) { |
| 112 | return noAccess(numbers), nil |
| 113 | } |
| 114 | return nil, err |
| 115 | } |
| 116 | return parseSnapshots(body, numbers) |
| 117 | } |
| 118 | |
| 119 | func noAccess(numbers []int) map[int]*PRSnapshot { |
| 120 | out := make(map[int]*PRSnapshot, len(numbers)) |
| 121 | for _, n := range numbers { |
| 122 | out[n] = &PRSnapshot{Number: n, State: StateNoAccess} |
| 123 | } |
| 124 | return out |
| 125 | } |
| 126 | |
| 127 | type gqlActor struct { |
| 128 | Typename string `json:"__typename"` |
| 129 | Login string `json:"login"` |
| 130 | } |
| 131 | |
| 132 | func (a *gqlActor) login() string { |
| 133 | if a == nil { |
| 134 | return "" |
| 135 | } |
| 136 | if a.Typename == "Bot" { |
| 137 | return a.Login + "[bot]" |
| 138 | } |
| 139 | return a.Login |
| 140 | } |
| 141 | |
| 142 | type gqlPR struct { |
| 143 | State string `json:"state"` |
| 144 | IsDraft bool `json:"isDraft"` |
| 145 | Mergeable string `json:"mergeable"` |
| 146 | ReviewDecision string `json:"reviewDecision"` |
| 147 | HeadRefOid string `json:"headRefOid"` |
| 148 | BaseRef *struct { |
| 149 | Target struct { |
| 150 | Oid string `json:"oid"` |
| 151 | } `json:"target"` |
| 152 | } `json:"baseRef"` |
| 153 | Labels struct { |
| 154 | Nodes []struct { |
| 155 | Name string `json:"name"` |
| 156 | } `json:"nodes"` |
| 157 | } `json:"labels"` |
| 158 | Commits struct { |
| 159 | Nodes []struct { |
| 160 | Commit struct { |
| 161 | CommittedDate time.Time `json:"committedDate"` |
| 162 | StatusCheckRollup *struct { |
| 163 | State string `json:"state"` |
| 164 | } `json:"statusCheckRollup"` |
| 165 | } `json:"commit"` |
| 166 | } `json:"nodes"` |
| 167 | } `json:"commits"` |
| 168 | Author *gqlActor `json:"author"` |
| 169 | Reviews *struct { |
| 170 | Nodes []struct { |
| 171 | DatabaseID int64 `json:"databaseId"` |
| 172 | Author *gqlActor `json:"author"` |
| 173 | State string `json:"state"` |
| 174 | SubmittedAt time.Time `json:"submittedAt"` |
| 175 | Body string `json:"body"` |
| 176 | Comments struct { |
| 177 | Nodes []struct { |
| 178 | Body string `json:"body"` |
| 179 | } `json:"nodes"` |
| 180 | } `json:"comments"` |
| 181 | } `json:"nodes"` |
| 182 | } `json:"reviews"` |
| 183 | Comments *struct { |
| 184 | Nodes []struct { |
| 185 | Author *gqlActor `json:"author"` |
| 186 | Body string `json:"body"` |
| 187 | UpdatedAt time.Time `json:"updatedAt"` |
| 188 | } `json:"nodes"` |
| 189 | } `json:"comments"` |
| 190 | } |
| 191 | |
| 192 | // parseSnapshots reads a PRSnapshots response. A PR, or a repository, |
| 193 | // GraphQL reports NOT_FOUND or FORBIDDEN beside the others' data reads |
| 194 | // StateNoAccess; one with any other error, on it or on one of its fields, is |
| 195 | // left out, so it keeps its last status. |
| 196 | func parseSnapshots(body []byte, numbers []int) (map[int]*PRSnapshot, error) { |
| 197 | var resp struct { |
| 198 | Data *struct { |
| 199 | Viewer *struct { |
| 200 | Login string `json:"login"` |
| 201 | } `json:"viewer"` |
| 202 | Repository map[string]*gqlPR `json:"repository"` |
| 203 | } `json:"data"` |
| 204 | Errors []struct { |
| 205 | Type string `json:"type"` |
| 206 | Path []interface{} `json:"path"` |
| 207 | Message string `json:"message"` |
| 208 | } `json:"errors"` |
| 209 | } |
| 210 | if err := json.Unmarshal(body, &resp); err != nil { |
| 211 | return nil, fmt.Errorf("parsing PR snapshots: %w", err) |
| 212 | } |
| 213 | unreadable := make(map[string]bool) // "repository" or a PR's alias |
| 214 | failed := make(map[string]bool) // PR aliases with an error on them or a field |
| 215 | for _, e := range resp.Errors { |
| 216 | if (e.Type == "NOT_FOUND" || e.Type == "FORBIDDEN") && len(e.Path) > 0 && len(e.Path) <= 2 { |
| 217 | unreadable[fmt.Sprint(e.Path[len(e.Path)-1])] = true |
| 218 | } else if len(e.Path) >= 2 { |
| 219 | failed[fmt.Sprint(e.Path[1])] = true |
| 220 | } |
| 221 | } |
| 222 | if resp.Data == nil || resp.Data.Repository == nil { |
| 223 | if unreadable["repository"] { |
| 224 | return noAccess(numbers), nil |
| 225 | } |
| 226 | return nil, fmt.Errorf("PR snapshots: no data in %.200s", body) |
| 227 | } |
| 228 | operator := "" |
| 229 | if resp.Data.Viewer != nil { |
| 230 | operator = resp.Data.Viewer.Login |
| 231 | } |
| 232 | out := make(map[int]*PRSnapshot, len(numbers)) |
| 233 | for _, n := range numbers { |
| 234 | alias := "pr" + strconv.Itoa(n) |
| 235 | pr := resp.Data.Repository[alias] |
| 236 | if failed[alias] { |
| 237 | continue |
| 238 | } |
| 239 | if pr == nil { |
| 240 | if unreadable[alias] { |
| 241 | out[n] = &PRSnapshot{Number: n, State: StateNoAccess} |
| 242 | } |
| 243 | continue |
| 244 | } |
| 245 | s := &PRSnapshot{Number: n} |
| 246 | out[n] = s |
| 247 | s.State = strings.ToUpper(pr.State) |
| 248 | s.Draft = pr.IsDraft |
| 249 | s.ReviewDecision = pr.ReviewDecision |
| 250 | s.HeadSHA = pr.HeadRefOid |
| 251 | if pr.BaseRef != nil { |
| 252 | s.BaseSHA = pr.BaseRef.Target.Oid |
| 253 | } |
| 254 | switch pr.Mergeable { |
| 255 | case "CONFLICTING": |
| 256 | s.Conflicts = "yes" |
| 257 | case "MERGEABLE": |
| 258 | s.Conflicts = "none" |
| 259 | default: |
| 260 | s.Conflicts = "unknown" |
| 261 | } |
| 262 | for _, l := range pr.Labels.Nodes { |
| 263 | s.Labels = append(s.Labels, l.Name) |
| 264 | } |
| 265 | // A PR without checks has nothing to fail. |
| 266 | s.CI = "passing" |
| 267 | var lastCommitAt time.Time |
| 268 | if len(pr.Commits.Nodes) > 0 { |
| 269 | head := pr.Commits.Nodes[len(pr.Commits.Nodes)-1].Commit |
| 270 | lastCommitAt = head.CommittedDate |
| 271 | if head.StatusCheckRollup != nil { |
| 272 | s.CI = rollupCI(head.StatusCheckRollup.State) |
| 273 | } |
| 274 | } |
| 275 | if pr.Reviews != nil || pr.Comments != nil { |
| 276 | a := &PRActivity{Operator: operator, Author: pr.Author.login(), LastCommitAt: lastCommitAt} |
| 277 | if pr.Reviews != nil { |
| 278 | for _, r := range pr.Reviews.Nodes { |
| 279 | rv := Review{ID: r.DatabaseID, Author: r.Author.login(), State: r.State, Body: r.Body, SubmittedAt: r.SubmittedAt} |
| 280 | for _, c := range r.Comments.Nodes { |
| 281 | rv.Comments = append(rv.Comments, c.Body) |
| 282 | } |
| 283 | a.Reviews = append(a.Reviews, rv) |
| 284 | } |
| 285 | } |
| 286 | if pr.Comments != nil { |
| 287 | for _, c := range pr.Comments.Nodes { |
| 288 | a.Comments = append(a.Comments, IssueComment{Author: c.Author.login(), Body: c.Body, UpdatedAt: c.UpdatedAt}) |
| 289 | } |
| 290 | } |
| 291 | s.Activity = a |
| 292 | } |
| 293 | } |
| 294 | return out, nil |
| 295 | } |
| 296 | |
| 297 | // rollupCI maps a commit's check rollup state to passing, failing or pending. |
| 298 | func rollupCI(state string) string { |
| 299 | switch state { |
| 300 | case "SUCCESS": |
| 301 | return "passing" |
| 302 | case "FAILURE", "ERROR": |
| 303 | return "failing" |
| 304 | default: |
| 305 | return "pending" |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | // CommitsBehindSHA returns how many commits base has that head lacks, in the |
| 310 | // repository slug. A rate limit is a *RateLimitError. |
| 311 | func (c *GHCLIClient) CommitsBehindSHA(ctx context.Context, slug, base, head string) (int, error) { |
| 312 | body, err := c.api(ctx, fmt.Sprintf("repos/%s/compare/%s...%s", slug, base, head)) |
| 313 | if err != nil { |
| 314 | return 0, err |
| 315 | } |
| 316 | var cmp struct { |
| 317 | BehindBy *int `json:"behind_by"` |
| 318 | } |
| 319 | if err := json.Unmarshal(body, &cmp); err != nil || cmp.BehindBy == nil { |
| 320 | return 0, fmt.Errorf("comparing %s...%s: unexpected response %.200s", base, head, body) |
| 321 | } |
| 322 | return *cmp.BehindBy, nil |
| 323 | } |
| 324 | |
| 325 | // api runs `gh api --include` and returns the response body. It reads the |
| 326 | // status line and headers --include adds, so a rate limit comes back as a |
| 327 | // *RateLimitError with the time GitHub says to wait for. A GraphQL response |
| 328 | // that carries data succeeds even though gh exits non-zero for the errors |
| 329 | // beside it. |
| 330 | func (c *GHCLIClient) api(ctx context.Context, args ...string) ([]byte, error) { |
| 331 | ctx, cancel := ensureTimeout(ctx) |
| 332 | defer cancel() |
| 333 | cmd := exec.CommandContext(ctx, "gh", append([]string{"api", "--include"}, args...)...) |
| 334 | var stdout, stderr bytes.Buffer |
| 335 | cmd.Stdout, cmd.Stderr = &stdout, &stderr |
| 336 | runErr := cmd.Run() |
| 337 | status, hdr, body := splitInclude(stdout.Bytes()) |
| 338 | if rateLimited(status, body, stderr.String()) { |
| 339 | return nil, &RateLimitError{Until: rateLimitUntil(hdr, time.Now())} |
| 340 | } |
| 341 | if runErr != nil && (status < 200 || status > 299) { |
| 342 | return nil, fmt.Errorf("gh api: %w: %s", wrapTimeoutErr(ctx, "gh api", runErr), strings.TrimSpace(stderr.String())) |
| 343 | } |
| 344 | return body, nil |
| 345 | } |
| 346 | |
| 347 | // splitInclude splits `gh api --include` output into the status code, the |
| 348 | // headers and the body. Output without a status line is all body, status 0. |
| 349 | func splitInclude(out []byte) (int, http.Header, []byte) { |
| 350 | hdr := http.Header{} |
| 351 | s := strings.ReplaceAll(string(out), "\r\n", "\n") |
| 352 | head, body, ok := strings.Cut(s, "\n\n") |
| 353 | if !ok || !strings.HasPrefix(head, "HTTP/") { |
| 354 | return 0, hdr, out |
| 355 | } |
| 356 | lines := strings.Split(head, "\n") |
| 357 | status := 0 |
| 358 | if f := strings.Fields(lines[0]); len(f) >= 2 { |
| 359 | status, _ = strconv.Atoi(f[1]) |
| 360 | } |
| 361 | for _, l := range lines[1:] { |
| 362 | if k, v, ok := strings.Cut(l, ":"); ok { |
| 363 | hdr.Add(strings.TrimSpace(k), strings.TrimSpace(v)) |
| 364 | } |
| 365 | } |
| 366 | return status, hdr, []byte(body) |
| 367 | } |
| 368 | |
| 369 | // rateLimited reports whether a response is GitHub refusing for a rate |
| 370 | // limit: a GraphQL RATE_LIMITED error, or a 403 or 429 (or a failure before |
| 371 | // any response) saying "rate limit". A successful body isn't searched for |
| 372 | // the words, since PR text can contain them. |
| 373 | func rateLimited(status int, body []byte, stderr string) bool { |
| 374 | if status >= 200 && status <= 299 { |
| 375 | var resp struct { |
| 376 | Errors []struct { |
| 377 | Type string `json:"type"` |
| 378 | } `json:"errors"` |
| 379 | } |
| 380 | if json.Unmarshal(body, &resp) == nil { |
| 381 | for _, e := range resp.Errors { |
| 382 | if e.Type == "RATE_LIMITED" { |
| 383 | return true |
| 384 | } |
| 385 | } |
| 386 | } |
| 387 | return false |
| 388 | } |
| 389 | if status != 0 && status != http.StatusForbidden && status != http.StatusTooManyRequests { |
| 390 | return false |
| 391 | } |
| 392 | return strings.Contains(strings.ToLower(string(body)+stderr), "rate limit") |
| 393 | } |
| 394 | |
| 395 | // rateLimitUntil is when a rate-limited response says to try again: after |
| 396 | // Retry-After, else at X-RateLimit-Reset once the budget is spent, else after |
| 397 | // rateLimitBackoff. |
| 398 | func rateLimitUntil(hdr http.Header, now time.Time) time.Time { |
| 399 | if s, err := strconv.Atoi(hdr.Get("Retry-After")); err == nil && s > 0 { |
| 400 | return now.Add(time.Duration(s) * time.Second) |
| 401 | } |
| 402 | if hdr.Get("X-RateLimit-Remaining") == "0" { |
| 403 | if r, err := strconv.ParseInt(hdr.Get("X-RateLimit-Reset"), 10, 64); err == nil && r > now.Unix() { |
| 404 | return time.Unix(r, 0) |
| 405 | } |
| 406 | } |
| 407 | return now.Add(rateLimitBackoff) |
| 408 | } |