Repository navigation
Expand file tree
/
Copy pathgithub.go
More file actions
448 lines (398 loc) · 11.1 KB
/
Copy pathgithub.go
File metadata and controls
448 lines (398 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"regexp"
"time"
)
var httpClient = &http.Client{Timeout: 60 * time.Second}
const maxRetries = 3
type PRNode struct {
Title string `json:"title"`
URL string `json:"url"`
Number int `json:"number"`
IsDraft bool `json:"isDraft"`
CreatedAt time.Time `json:"createdAt"`
Author struct {
Login string `json:"login"`
} `json:"author"`
Repository struct {
Name string `json:"name"`
NameWithOwner string `json:"nameWithOwner"`
} `json:"repository"`
Reviews struct {
Nodes []ReviewNode `json:"nodes"`
} `json:"reviews"`
Comments struct {
Nodes []CommentNode `json:"nodes"`
} `json:"comments"`
Mergeable string `json:"mergeable"`
ReviewDecision string `json:"reviewDecision"`
Commits struct {
Nodes []CommitNode `json:"nodes"`
} `json:"commits"`
ReviewRequests struct {
Nodes []ReviewRequestNode `json:"nodes"`
} `json:"reviewRequests"`
}
type ReviewNode struct {
Author struct {
Login string `json:"login"`
} `json:"author"`
State string `json:"state"`
SubmittedAt time.Time `json:"submittedAt"`
}
type CommentNode struct {
Author struct {
Login string `json:"login"`
} `json:"author"`
CreatedAt time.Time `json:"createdAt"`
}
type CommitNode struct {
Commit struct {
CommittedDate time.Time `json:"committedDate"`
StatusCheckRollup *struct {
State string `json:"state"`
} `json:"statusCheckRollup"`
} `json:"commit"`
}
type ReviewRequestNode struct {
AsCodeOwner bool `json:"asCodeOwner"`
RequestedReviewer struct {
Login string `json:"login"`
Slug string `json:"slug"`
} `json:"requestedReviewer"`
}
type searchResult struct {
Data struct {
Search struct {
PageInfo struct {
HasNextPage bool `json:"hasNextPage"`
EndCursor string `json:"endCursor"`
} `json:"pageInfo"`
Nodes []PRNode `json:"nodes"`
} `json:"search"`
} `json:"data"`
Errors []struct {
Message string `json:"message"`
} `json:"errors"`
}
const graphQLQuery = `query($searchQuery: String!, $cursor: String) {
search(query: $searchQuery, type: ISSUE, first: 25, after: $cursor) {
pageInfo {
hasNextPage
endCursor
}
nodes {
... on PullRequest {
title
url
number
createdAt
isDraft
mergeable
reviewDecision
author { login }
repository { name nameWithOwner }
reviews(last: 100) {
nodes {
author { login }
state
submittedAt
}
}
comments(last: 100) {
nodes {
author { login }
createdAt
}
}
commits(last: 1) {
nodes {
commit {
committedDate
statusCheckRollup { state }
}
}
}
reviewRequests(first: 100) {
nodes {
asCodeOwner
requestedReviewer {
... on User { login }
... on Team { slug }
}
}
}
}
}
}
}`
func ghToken() (string, error) {
token := os.Getenv("GITHUB_TOKEN")
if token == "" {
return "", fmt.Errorf("GITHUB_TOKEN environment variable is required")
}
return token, nil
}
func isRetryable(statusCode int) bool {
return statusCode == 502 || statusCode == 503 || statusCode == 504
}
func ghRequest(method, url string, body io.Reader) ([]byte, error) {
token, err := ghToken()
if err != nil {
return nil, err
}
// Buffer body so we can retry
var bodyBytes []byte
if body != nil {
bodyBytes, err = io.ReadAll(body)
if err != nil {
return nil, fmt.Errorf("reading request body: %w", err)
}
}
var lastErr error
for attempt := range maxRetries {
var bodyReader io.Reader
if bodyBytes != nil {
bodyReader = bytes.NewReader(bodyBytes)
}
req, err := http.NewRequest(method, url, bodyReader)
if err != nil {
return nil, fmt.Errorf("creating request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Accept", "application/vnd.github+json")
if bodyBytes != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := httpClient.Do(req)
if err != nil {
lastErr = fmt.Errorf("HTTP request failed: %w", err)
time.Sleep(time.Duration(attempt+1) * 2 * time.Second)
continue
}
data, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, fmt.Errorf("reading response: %w", err)
}
if resp.StatusCode == 401 {
return nil, fmt.Errorf("authentication failed (HTTP 401): is your GITHUB_TOKEN valid?")
}
if resp.StatusCode == 403 || resp.StatusCode == 429 {
return nil, fmt.Errorf("rate limited by GitHub (HTTP %d): wait a minute and try again", resp.StatusCode)
}
if isRetryable(resp.StatusCode) {
lastErr = fmt.Errorf("GitHub API returned %d", resp.StatusCode)
time.Sleep(time.Duration(attempt+1) * 2 * time.Second)
continue
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
msg := string(data)
if len(msg) > 200 {
msg = msg[:200] + "..."
}
return nil, fmt.Errorf("GitHub API returned %d: %s", resp.StatusCode, msg)
}
return data, nil
}
return nil, fmt.Errorf("request failed after %d attempts: %w", maxRetries, lastErr)
}
// ghRequestPaginated fetches all pages of a paginated REST endpoint.
var linkNextRE = regexp.MustCompile(`<([^>]+)>;\s*rel="next"`)
func ghRequestPaginated(url string) ([]byte, error) {
token, err := ghToken()
if err != nil {
return nil, err
}
var allData []json.RawMessage
nextURL := url
for nextURL != "" {
req, err := http.NewRequest("GET", nextURL, nil)
if err != nil {
return nil, fmt.Errorf("creating request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Accept", "application/vnd.github+json")
resp, err := httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("HTTP request failed: %w", err)
}
data, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, fmt.Errorf("reading response: %w", err)
}
if resp.StatusCode == 401 {
return nil, fmt.Errorf("authentication failed (HTTP 401): is your GITHUB_TOKEN valid?")
}
if resp.StatusCode == 403 || resp.StatusCode == 429 {
return nil, fmt.Errorf("rate limited by GitHub (HTTP %d): wait a minute and try again", resp.StatusCode)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
msg := string(data)
if len(msg) > 200 {
msg = msg[:200] + "..."
}
return nil, fmt.Errorf("GitHub API returned %d: %s", resp.StatusCode, msg)
}
var page []json.RawMessage
if err := json.Unmarshal(data, &page); err != nil {
return nil, fmt.Errorf("parsing paginated response: %w", err)
}
allData = append(allData, page...)
// Parse Link header for next page
nextURL = ""
if link := resp.Header.Get("Link"); link != "" {
if m := linkNextRE.FindStringSubmatch(link); len(m) == 2 {
nextURL = m[1]
}
}
}
return json.Marshal(allData)
}
func parseUserTeams(data []byte, org string) (map[string]bool, error) {
var teams []struct {
Slug string `json:"slug"`
Organization struct {
Login string `json:"login"`
} `json:"organization"`
}
if err := json.Unmarshal(data, &teams); err != nil {
return nil, fmt.Errorf("parsing teams response: %w", err)
}
result := make(map[string]bool)
for _, t := range teams {
if t.Organization.Login == org {
result[t.Slug] = true
}
}
return result, nil
}
func fetchUserTeams(org string) (map[string]bool, error) {
out, err := ghRequestPaginated("https://api.github.com/user/teams?per_page=100")
if err != nil {
return nil, fmt.Errorf("fetching teams: %w", err)
}
return parseUserTeams(out, org)
}
func fetchCurrentUser() (string, error) {
out, err := ghRequest("GET", "https://api.github.com/user", nil)
if err != nil {
return "", fmt.Errorf("fetching current user: %w", err)
}
var user struct {
Login string `json:"login"`
}
if err := json.Unmarshal(out, &user); err != nil {
return "", fmt.Errorf("parsing user response: %w", err)
}
if user.Login == "" {
return "", fmt.Errorf("could not determine GitHub username; is your GITHUB_TOKEN valid?")
}
return user.Login, nil
}
func postComment(repo string, number int, body string) error {
url := fmt.Sprintf("https://api.github.com/repos/%s/issues/%d/comments", repo, number)
payload, _ := json.Marshal(map[string]string{"body": body})
_, err := ghRequest("POST", url, bytes.NewReader(payload))
return err
}
func fetchOpenPRs(org string, limit int) ([]PRNode, error) {
var allPRs []PRNode
searchQuery := fmt.Sprintf("is:pr is:open sort:updated org:%s", org)
var cursor *string
page := 0
for {
page++
variables := map[string]interface{}{
"searchQuery": searchQuery,
"cursor": cursor,
}
payload, _ := json.Marshal(map[string]interface{}{
"query": graphQLQuery,
"variables": variables,
})
out, err := ghRequest("POST", "https://api.github.com/graphql", bytes.NewReader(payload))
if err != nil {
return nil, fmt.Errorf("GraphQL query failed (page %d): %w", page, err)
}
var result searchResult
if err := json.Unmarshal(out, &result); err != nil {
return nil, fmt.Errorf("parsing GraphQL response: %w", err)
}
if len(result.Errors) > 0 {
return nil, fmt.Errorf("GraphQL error: %s", result.Errors[0].Message)
}
for _, node := range result.Data.Search.Nodes {
if node.Number == 0 {
continue // skip non-PR nodes
}
allPRs = append(allPRs, node)
}
if limit > 0 && len(allPRs) >= limit {
allPRs = allPRs[:limit]
break
}
if !result.Data.Search.PageInfo.HasNextPage {
break
}
c := result.Data.Search.PageInfo.EndCursor
cursor = &c
}
return allPRs, nil
}
// fetchOpenPRsStreaming fetches open PRs page by page, sending cumulative
// results on ch after each page. The channel is closed when done.
func fetchOpenPRsStreaming(org string, limit int, ch chan<- []PRNode) error {
defer close(ch)
var allPRs []PRNode
searchQuery := fmt.Sprintf("is:pr is:open sort:updated org:%s", org)
var cursor *string
page := 0
for {
page++
variables := map[string]interface{}{
"searchQuery": searchQuery,
"cursor": cursor,
}
payload, _ := json.Marshal(map[string]interface{}{
"query": graphQLQuery,
"variables": variables,
})
out, err := ghRequest("POST", "https://api.github.com/graphql", bytes.NewReader(payload))
if err != nil {
return fmt.Errorf("GraphQL query failed (page %d): %w", page, err)
}
var result searchResult
if err := json.Unmarshal(out, &result); err != nil {
return fmt.Errorf("parsing GraphQL response: %w", err)
}
if len(result.Errors) > 0 {
return fmt.Errorf("GraphQL error: %s", result.Errors[0].Message)
}
for _, node := range result.Data.Search.Nodes {
if node.Number == 0 {
continue
}
allPRs = append(allPRs, node)
}
if limit > 0 && len(allPRs) >= limit {
allPRs = allPRs[:limit]
ch <- append([]PRNode(nil), allPRs...)
return nil
}
// Send cumulative snapshot
ch <- append([]PRNode(nil), allPRs...)
if !result.Data.Search.PageInfo.HasNextPage {
return nil
}
c := result.Data.Search.PageInfo.EndCursor
cursor = &c
}
}