-
Notifications
You must be signed in to change notification settings - Fork 0
/
github.go
415 lines (369 loc) · 10.7 KB
/
github.go
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
package resource
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"path"
"strconv"
"strings"
"github.com/google/go-github/v28/github"
"github.com/shurcooL/githubv4"
"golang.org/x/oauth2"
)
// Github for testing purposes.
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -o fakes/fake_github.go . Github
type Github interface {
ListPullRequests([]githubv4.PullRequestState) ([]*PullRequest, error)
ListModifiedFiles(int) ([]string, error)
PostComment(string, string) error
GetPullRequest(string, string) (*PullRequest, error)
GetChangedFiles(string, string) ([]ChangedFileObject, error)
UpdateCommitStatus(string, string, string, string, string, string) error
DeletePreviousComments(string) error
}
// GithubClient for handling requests to the Github V3 and V4 APIs.
type GithubClient struct {
V3 *github.Client
V4 *githubv4.Client
Repository string
Owner string
}
// NewGithubClient ...
func NewGithubClient(s *Source) (*GithubClient, error) {
owner, repository, err := parseRepository(s.Repository)
if err != nil {
return nil, err
}
// Skip SSL verification for self-signed certificates
// source: https://github.com/google/go-github/pull/598#issuecomment-333039238
var ctx context.Context
if s.SkipSSLVerification {
insecureClient := &http.Client{Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
}
ctx = context.WithValue(context.TODO(), oauth2.HTTPClient, insecureClient)
} else {
ctx = context.TODO()
}
client := oauth2.NewClient(ctx, oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: s.AccessToken},
))
var v3 *github.Client
if s.V3Endpoint != "" {
endpoint, err := url.Parse(s.V3Endpoint)
if err != nil {
return nil, fmt.Errorf("failed to parse v3 endpoint: %s", err)
}
v3, err = github.NewEnterpriseClient(endpoint.String(), endpoint.String(), client)
if err != nil {
return nil, err
}
} else {
v3 = github.NewClient(client)
}
var v4 *githubv4.Client
if s.V4Endpoint != "" {
endpoint, err := url.Parse(s.V4Endpoint)
if err != nil {
return nil, fmt.Errorf("failed to parse v4 endpoint: %s", err)
}
v4 = githubv4.NewEnterpriseClient(endpoint.String(), client)
if err != nil {
return nil, err
}
} else {
v4 = githubv4.NewClient(client)
}
return &GithubClient{
V3: v3,
V4: v4,
Owner: owner,
Repository: repository,
}, nil
}
// ListPullRequests gets the last commit on all pull requests with the matching state.
func (m *GithubClient) ListPullRequests(prStates []githubv4.PullRequestState) ([]*PullRequest, error) {
var query struct {
Repository struct {
PullRequests struct {
Edges []struct {
Node struct {
PullRequestObject
Reviews struct {
TotalCount int
} `graphql:"reviews(states: $prReviewStates)"`
Commits struct {
Edges []struct {
Node struct {
Commit CommitObject
}
}
} `graphql:"commits(last:$commitsLast)"`
Labels struct {
Edges []struct {
Node struct {
LabelObject
}
}
} `graphql:"labels(first:$labelsFirst)"`
}
}
PageInfo struct {
EndCursor githubv4.String
HasNextPage bool
}
} `graphql:"pullRequests(first:$prFirst,states:$prStates,after:$prCursor)"`
} `graphql:"repository(owner:$repositoryOwner,name:$repositoryName)"`
}
vars := map[string]interface{}{
"repositoryOwner": githubv4.String(m.Owner),
"repositoryName": githubv4.String(m.Repository),
"prFirst": githubv4.Int(100),
"prStates": prStates,
"prCursor": (*githubv4.String)(nil),
"commitsLast": githubv4.Int(1),
"prReviewStates": []githubv4.PullRequestReviewState{githubv4.PullRequestReviewStateApproved},
"labelsFirst": githubv4.Int(100),
}
var response []*PullRequest
for {
if err := m.V4.Query(context.TODO(), &query, vars); err != nil {
return nil, err
}
for _, p := range query.Repository.PullRequests.Edges {
labels := make([]LabelObject, len(p.Node.Labels.Edges))
for _, l := range p.Node.Labels.Edges {
labels = append(labels, l.Node.LabelObject)
}
for _, c := range p.Node.Commits.Edges {
response = append(response, &PullRequest{
PullRequestObject: p.Node.PullRequestObject,
Tip: c.Node.Commit,
ApprovedReviewCount: p.Node.Reviews.TotalCount,
Labels: labels,
})
}
}
if !query.Repository.PullRequests.PageInfo.HasNextPage {
break
}
vars["prCursor"] = query.Repository.PullRequests.PageInfo.EndCursor
}
return response, nil
}
// ListModifiedFiles in a pull request (not supported by V4 API).
func (m *GithubClient) ListModifiedFiles(prNumber int) ([]string, error) {
var files []string
opt := &github.ListOptions{
PerPage: 100,
}
for {
result, response, err := m.V3.PullRequests.ListFiles(
context.TODO(),
m.Owner,
m.Repository,
prNumber,
opt,
)
if err != nil {
return nil, err
}
for _, f := range result {
files = append(files, *f.Filename)
}
if response.NextPage == 0 {
break
}
opt.Page = response.NextPage
}
return files, nil
}
// PostComment to a pull request or issue.
func (m *GithubClient) PostComment(prNumber, comment string) error {
pr, err := strconv.Atoi(prNumber)
if err != nil {
return fmt.Errorf("failed to convert pull request number to int: %s", err)
}
_, _, err = m.V3.Issues.CreateComment(
context.TODO(),
m.Owner,
m.Repository,
pr,
&github.IssueComment{
Body: github.String(comment),
},
)
return err
}
// GetChangedFiles ...
func (m *GithubClient) GetChangedFiles(prNumber string, commitRef string) ([]ChangedFileObject, error) {
pr, err := strconv.Atoi(prNumber)
if err != nil {
return nil, fmt.Errorf("failed to convert pull request number to int: %s", err)
}
var cfo []ChangedFileObject
var filequery struct {
Repository struct {
PullRequest struct {
Files struct {
Edges []struct {
Node struct {
ChangedFileObject
}
} `graphql:"edges"`
PageInfo struct {
EndCursor githubv4.String
HasNextPage bool
} `graphql:"pageInfo"`
} `graphql:"files(first:$changedFilesFirst, after: $changedFilesEndCursor)"`
} `graphql:"pullRequest(number:$prNumber)"`
} `graphql:"repository(owner:$repositoryOwner,name:$repositoryName)"`
}
offset := ""
for {
vars := map[string]interface{}{
"repositoryOwner": githubv4.String(m.Owner),
"repositoryName": githubv4.String(m.Repository),
"prNumber": githubv4.Int(pr),
"changedFilesFirst": githubv4.Int(100),
"changedFilesEndCursor": githubv4.String(offset),
}
if err := m.V4.Query(context.TODO(), &filequery, vars); err != nil {
return nil, err
}
for _, f := range filequery.Repository.PullRequest.Files.Edges {
cfo = append(cfo, ChangedFileObject{Path: f.Node.Path})
}
if !filequery.Repository.PullRequest.Files.PageInfo.HasNextPage {
break
}
offset = string(filequery.Repository.PullRequest.Files.PageInfo.EndCursor)
}
return cfo, nil
}
// GetPullRequest ...
func (m *GithubClient) GetPullRequest(prNumber, commitRef string) (*PullRequest, error) {
pr, err := strconv.Atoi(prNumber)
if err != nil {
return nil, fmt.Errorf("failed to convert pull request number to int: %s", err)
}
var query struct {
Repository struct {
PullRequest struct {
PullRequestObject
Commits struct {
Edges []struct {
Node struct {
Commit CommitObject
}
}
} `graphql:"commits(last:$commitsLast)"`
} `graphql:"pullRequest(number:$prNumber)"`
} `graphql:"repository(owner:$repositoryOwner,name:$repositoryName)"`
}
vars := map[string]interface{}{
"repositoryOwner": githubv4.String(m.Owner),
"repositoryName": githubv4.String(m.Repository),
"prNumber": githubv4.Int(pr),
"commitsLast": githubv4.Int(100),
}
// TODO: Pagination - in case someone pushes > 100 commits before the build has time to start :p
if err := m.V4.Query(context.TODO(), &query, vars); err != nil {
return nil, err
}
for _, c := range query.Repository.PullRequest.Commits.Edges {
if c.Node.Commit.OID == commitRef {
// Return as soon as we find the correct ref.
return &PullRequest{
PullRequestObject: query.Repository.PullRequest.PullRequestObject,
Tip: c.Node.Commit,
}, nil
}
}
// Return an error if the commit was not found
return nil, fmt.Errorf("commit with ref '%s' does not exist", commitRef)
}
// UpdateCommitStatus for a given commit (not supported by V4 API).
func (m *GithubClient) UpdateCommitStatus(commitRef, baseContext, statusContext, status, targetURL, description string) error {
if baseContext == "" {
baseContext = "concourse-ci"
}
if statusContext == "" {
statusContext = "status"
}
if targetURL == "" {
targetURL = strings.Join([]string{os.Getenv("ATC_EXTERNAL_URL"), "builds", os.Getenv("BUILD_ID")}, "/")
}
if description == "" {
description = fmt.Sprintf("Concourse CI build %s", status)
}
_, _, err := m.V3.Repositories.CreateStatus(
context.TODO(),
m.Owner,
m.Repository,
commitRef,
&github.RepoStatus{
State: github.String(strings.ToLower(status)),
TargetURL: github.String(targetURL),
Description: github.String(description),
Context: github.String(path.Join(baseContext, statusContext)),
},
)
return err
}
func (m *GithubClient) DeletePreviousComments(prNumber string) error {
pr, err := strconv.Atoi(prNumber)
if err != nil {
return fmt.Errorf("failed to convert pull request number to int: %s", err)
}
var getComments struct {
Viewer struct {
Login string
}
Repository struct {
PullRequest struct {
Id string
Comments struct {
Edges []struct {
Node struct {
DatabaseId int64
Author struct {
Login string
}
}
}
} `graphql:"comments(last:$commentsLast)"`
} `graphql:"pullRequest(number:$prNumber)"`
} `graphql:"repository(owner:$repositoryOwner,name:$repositoryName)"`
}
vars := map[string]interface{}{
"repositoryOwner": githubv4.String(m.Owner),
"repositoryName": githubv4.String(m.Repository),
"prNumber": githubv4.Int(pr),
"commentsLast": githubv4.Int(100),
}
if err := m.V4.Query(context.TODO(), &getComments, vars); err != nil {
return err
}
for _, e := range getComments.Repository.PullRequest.Comments.Edges {
if e.Node.Author.Login == getComments.Viewer.Login {
_, err := m.V3.Issues.DeleteComment(context.TODO(), m.Owner, m.Repository, e.Node.DatabaseId)
if err != nil {
return err
}
}
}
return nil
}
func parseRepository(s string) (string, string, error) {
parts := strings.Split(s, "/")
if len(parts) != 2 {
return "", "", errors.New("malformed repository")
}
return parts[0], parts[1], nil
}