-
Notifications
You must be signed in to change notification settings - Fork 7
/
github.go
449 lines (406 loc) · 11.3 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
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
449
package main
import (
"context"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/shurcooL/githubv4"
"golang.org/x/oauth2"
yaml "gopkg.in/yaml.v2"
"sigs.k8s.io/kustomize/api/types"
)
// GitHub, or more typically GitHub Instance as we call in our codebase,
// is a GitHub + GitOps client that can be used to interact with GitHub
// to do GitOps.
//
// It has methods to get files, create pull requests, request reviews,
// get kustomization, and so on.
//
// This is used by deploy models so that each deploy model
// does not need to implement the same logic to interact with GitHub.
type GitHub struct {
client githubv4.Client
httpClient *http.Client
org string
repo string
defaultBranch string
appOrg string
appClient githubv4.Client
}
type GitHubInput struct {
Repository string
Branch string
}
// appRepositoryAccess provides the interface to get the app repository org and GitHub access token.
type appRepositoryAccess interface {
GetAppRepositoryOrg() string
GetAppRepositoryGitHubAccessToken() string
}
func CreateGitHubInstance(url, token, org, repo, defaultBranch string, appRepoAccess appRepositoryAccess) GitHub {
client, httpClient := createGitHubClients(token, url)
appClient, _ := createGitHubClients(appRepoAccess.GetAppRepositoryGitHubAccessToken(), url)
return GitHub{client, httpClient, org, repo, defaultBranch,
appRepoAccess.GetAppRepositoryOrg(),
appClient,
}
}
func createGitHubClients(token, url string) (githubv4.Client, *http.Client) {
src := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
httpClient := oauth2.NewClient(context.Background(), src)
var client *githubv4.Client
if url != "" {
client = githubv4.NewEnterpriseClient(url, httpClient)
} else {
client = githubv4.NewClient(httpClient)
}
return *client, httpClient
}
func (g GitHub) GetFile(path string) (b []byte, err error) {
req, _ := http.NewRequest("GET", fmt.Sprintf("https://api.github.com/repos/%s/%s/contents/%s", g.org, g.repo, path), nil)
req.Header.Set("Accept", "application/vnd.github.v3.raw")
resp, err := g.httpClient.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
b, err = io.ReadAll(resp.Body)
if err != nil {
return
}
return
}
func (g GitHub) GetUsers() (users map[string]string, err error) {
users = map[string]string{}
type user struct {
ID string
Login string
}
var query struct {
Organization struct {
MembersWithRole struct {
Nodes []user
} `graphql:"membersWithRole(first: 100)"`
} `graphql:"organization(login: $org)"`
}
variables := map[string]interface{}{
"org": githubv4.String(g.org),
}
err = g.client.Query(context.Background(), &query, variables)
if err != nil {
return map[string]string{}, err
}
for _, node := range query.Organization.MembersWithRole.Nodes {
users[node.Login] = node.ID
}
return
}
func (g GitHub) GetKustomization(path string) (obj types.Kustomization, err error) {
b, err := g.GetFile(path)
if err != nil {
return
}
err = yaml.Unmarshal(b, &obj)
if err != nil {
err = fmt.Errorf("[ERROR] The file should be kustomization format")
return
}
return
}
func (g GitHub) ListBranch(name string) ([]string, error) {
type refs struct {
Name string
}
var query struct {
Repository struct {
Refs struct {
Nodes []refs
} `graphql:"refs(first: 50, refPrefix: \"refs/heads/\")"`
} `graphql:"repository(owner: $org, name: $name)"`
}
variables := map[string]interface{}{
"name": githubv4.String(name),
"org": githubv4.String(g.appOrg),
}
err := g.appClient.Query(context.Background(), &query, variables)
if err != nil {
return []string{}, err
}
var arr []string
for _, v := range query.Repository.Refs.Nodes {
arr = append(arr, v.Name)
}
return arr, nil
}
func (g GitHub) GitHash(branch string) (string, error) {
var query struct {
Repository struct {
Ref struct {
Target struct {
CommitUrl string
}
} `graphql:"ref(qualifiedName: $branch)"`
} `graphql:"repository(owner: $org, name: $repo)"`
}
variables := map[string]interface{}{
"repo": githubv4.String(g.repo),
"branch": githubv4.String(branch),
"org": githubv4.String(g.org),
}
err := g.client.Query(context.Background(), &query, variables)
if err != nil {
return "", err
}
return strings.TrimPrefix(query.Repository.Ref.Target.CommitUrl, fmt.Sprintf("https://github.com/%s/%s/commit/", g.org, g.repo)), nil
}
func (g GitHub) RepositoryID() (string, error) {
var query struct {
Repository struct {
ID string
} `graphql:"repository(owner: $org, name: $repo)"`
}
variables := map[string]interface{}{
"repo": githubv4.String(g.repo),
"org": githubv4.String(g.org),
}
err := g.client.Query(context.Background(), &query, variables)
if err != nil {
return "", err
}
return query.Repository.ID, nil
}
func (g GitHub) BranchID(refName string) (string, error) {
var query struct {
Repository struct {
Ref struct {
ID string
} `graphql:"ref(qualifiedName: $ref)"`
} `graphql:"repository(owner: $org, name: $repo)"`
}
variables := map[string]interface{}{
"repo": githubv4.String(g.repo),
"org": githubv4.String(g.org),
"ref": githubv4.String(refName),
}
err := g.client.Query(context.Background(), &query, variables)
if err != nil {
return "", err
}
return query.Repository.Ref.ID, nil
}
func (g GitHub) CreatePullRequest(branch string, title string, description string) (string, int, error) {
repoID, err := g.RepositoryID()
if err != nil {
return "", -1, err
}
var mutate struct {
CreatePullRequest struct {
PullRequest struct {
ID string
BaseRefName string
HeadRefName string
Title string
Body string
Number int
}
} `graphql:"createPullRequest(input:$input)"`
}
body := githubv4.String(fmt.Sprintf("from bot\n\n%s", description))
modify := githubv4.Boolean(true)
refName := "refs/heads/master"
if g.defaultBranch != "" {
refName = g.defaultBranch
}
input := githubv4.CreatePullRequestInput{
RepositoryID: repoID,
BaseRefName: githubv4.String(refName),
HeadRefName: githubv4.String(branch), //"refs/heads/bot/test-update"
Title: githubv4.String(title), //"Deploy super staging",
Body: &body,
MaintainerCanModify: &modify,
}
err = g.client.Mutate(context.Background(), &mutate, input, nil)
return mutate.CreatePullRequest.PullRequest.ID, mutate.CreatePullRequest.PullRequest.Number, err
}
func (g GitHub) UpdatePullRequest(prID string, assigneeIDs string) error {
var mutate struct {
UpdatePullRequest struct {
PullRequest struct {
ID string
}
} `graphql:"updatePullRequest(input:$input)"`
}
ids := []githubv4.ID{assigneeIDs}
input := githubv4.UpdatePullRequestInput{
PullRequestID: prID,
AssigneeIDs: &ids,
}
return g.client.Mutate(context.Background(), &mutate, input, nil)
}
func (g GitHub) RequestReviews(prID string, assigneeIDs string) error {
var mutate struct {
RequestReviews struct {
PullRequest struct {
ID string
}
} `graphql:"requestReviews(input:$input)"`
}
ids := []githubv4.ID{assigneeIDs}
input := githubv4.RequestReviewsInput{
PullRequestID: prID,
UserIDs: &ids,
}
return g.client.Mutate(context.Background(), &mutate, input, nil)
}
func (g GitHub) MergePullRequest(prID string) error {
var mutate struct {
MergePullRequest struct {
PullRequest struct {
ID string
}
} `graphql:"mergePullRequest(input:$input)"`
}
input := githubv4.MergePullRequestInput{
PullRequestID: prID,
}
return g.client.Mutate(context.Background(), &mutate, input, nil)
}
func (g GitHub) ClosePullRequest(prID string) error {
var mutate struct {
ClosePullRequest struct {
PullRequest struct {
ID string
}
} `graphql:"closePullRequest(input:$input)"`
}
input := githubv4.ClosePullRequestInput{
PullRequestID: prID,
}
if err := g.client.Mutate(context.Background(), &mutate, input, nil); err != nil {
// Without this, we end up seeing an unhelpful error message from gocat like the below when we fail to close a pull request:
//
// [INFO] Action Value: deploy_kustomize_reject|PR_hogehoge_2_bot/docker-image-tag-project-foo-staging-14e308b
// Could not resolve to a node with the global id of 'PR'
// [ERROR] Internal Server Error
//
// "Internal Server Error" is emitted in handler.go and "Could not resolve..." is emitted by GitHub API.
// The message lacks context and is not helpful for debugging.
// We want to see that the error is caused by the failure to close a pull request.
// We also want to see the inputs to the mutation to see which side of the mutation failed, us or GitHub.
return fmt.Errorf("unable to close pull request: input=%v, err=%v", input, err)
}
return nil
}
func (g GitHub) DeleteBranch(refName string) error {
refID, err := g.BranchID(refName)
if err != nil {
return err
}
var mutate struct {
DeleteRef struct {
ClientMutationID string
} `graphql:"deleteRef(input: $input)"`
}
input := githubv4.DeleteRefInput{
RefID: refID,
}
return g.client.Mutate(context.Background(), &mutate, input, nil)
}
type Commit struct {
ID string
Oid string
Message string
CommittedDate time.Time
}
func (g GitHub) Commits(repo string, branch string) ([]Commit, error) {
type edge struct {
Node Commit
}
var query struct {
Repository struct {
Ref struct {
Target struct {
Commit struct {
History struct {
Edges []edge
} `graphql:"history(first: 100)"`
} `graphql:"... on Commit"`
}
} `graphql:"ref(qualifiedName: $branch)"`
} `graphql:"repository(owner: $org, name: $repo)"`
}
variables := map[string]interface{}{
"repo": githubv4.String(repo),
"branch": githubv4.String(branch),
"org": githubv4.String(g.org),
}
err := g.client.Query(context.Background(), &query, variables)
if err != nil {
return []Commit{}, err
}
commits := []Commit{}
for _, e := range query.Repository.Ref.Target.Commit.History.Edges {
commits = append(commits, e.Node)
}
return commits, nil
}
type GitHubCommitsBetweenInput struct {
Repository string
Branch string
FirstCommitID string
LastCommitID string
}
func (g GitHub) CommitsBetween(input GitHubCommitsBetweenInput) ([]Commit, error) {
output := []Commit{}
commits, err := g.Commits(input.Repository, input.Branch)
if err != nil {
return output, err
}
between := false
for _, c := range commits {
if c.Oid == input.LastCommitID {
between = true
}
if c.Oid == input.FirstCommitID {
break
}
if between {
output = append(output, c)
}
}
return output, nil
}
type GitHubGetPullRequestInput struct {
GitHubInput
Number int
}
type PullRequest struct {
ID string
Number int
Body string
BodyHTML string `graphql:"bodyHTML"`
}
func (g GitHub) GetPullRequest(input GitHubGetPullRequestInput) (PullRequest, error) {
repo := input.Repository
if repo == "" {
repo = g.repo
}
var query struct {
Repository struct {
PullRequest PullRequest `graphql:"pullRequest(number: $number)"`
} `graphql:"repository(owner: $org, name: $repo)"`
}
variables := map[string]interface{}{
"repo": githubv4.String(repo),
"org": githubv4.String(g.org),
"number": githubv4.Int(input.Number),
}
err := g.client.Query(context.Background(), &query, variables)
if err != nil {
return PullRequest{}, err
}
return query.Repository.PullRequest, nil
}