/
githubapi.go
375 lines (338 loc) · 12 KB
/
githubapi.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
//go:generate go run github.com/golang/mock/mockgen -package mock -source=githubapi.go -destination=mock/githubapi.go
package githubapi
import (
"context"
"fmt"
"strings"
"github.com/cloudnativedaysjp/seaman/pkg/log"
"github.com/cloudnativedaysjp/seaman/pkg/utils"
"github.com/shurcooL/githubv4"
"golang.org/x/oauth2"
"golang.org/x/xerrors"
)
type GitHubApiClient interface {
CheckPrIsForInfraAndCreatedByRenovate(ctx context.Context, org, repo string, prNum int) (bool, string, error)
CreateIssueComment(ctx context.Context, org, repo string, prNum int, body string) error
CreateLabels(ctx context.Context, org, repo string, prNum int, labels []string) error
CreatePullRequest(ctx context.Context, org, repo, headBranch, baseBranch, title, body string) (prNum int, err error)
DeleteBranch(ctx context.Context, org, repo, headBranch string) error
GetPullRequestTitleAndChangedFilepaths(ctx context.Context, org, repo string, prNum int) (string, []string, error)
HealthCheck() error
UpdatePullRequestBody(ctx context.Context, org, repo string, prNum int, body string) error
}
type GitHubApiClientImpl struct {
tokenSource oauth2.TokenSource
}
func NewGitHubApiClientImpl(token string) GitHubApiClient {
src := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
return &GitHubApiClientImpl{src}
}
//
// Exposed methods
//
func (g *GitHubApiClientImpl) CheckPrIsForInfraAndCreatedByRenovate(ctx context.Context, org, repo string, prNum int) (bool, string, error) {
logger := log.FromContext(ctx)
client := githubv4.NewClient(oauth2.NewClient(ctx, g.tokenSource))
expectedNumOfUpdatedFiles := 2
labelLimit := 10
var query struct {
Repository struct {
PullRequest struct {
HeadRefName githubv4.String
ChangedFiles githubv4.Int
Files struct {
Edges []struct {
Node struct {
Path githubv4.String
}
}
} `graphql:"files(first:$filesFirst)"`
Labels struct {
Edges []struct {
Node struct {
Name githubv4.String
}
}
} `graphql:"labels(first:$labelsFirst)"`
} `graphql:"pullRequest(number:$number)"`
} `graphql:"repository(owner:$repositoryOwner,name:$repositoryName)"`
}
queryVars := map[string]interface{}{
"repositoryOwner": githubv4.String(org),
"repositoryName": githubv4.String(repo),
"number": githubv4.Int(prNum),
"filesFirst": githubv4.Int(expectedNumOfUpdatedFiles),
"labelsFirst": githubv4.Int(labelLimit),
}
if err := client.Query(ctx, &query, queryVars); err != nil {
return false, "", xerrors.Errorf("%w", err)
}
// if changeFiles == `expectedNumOfUpdatedFiles`
if int(query.Repository.PullRequest.ChangedFiles) != expectedNumOfUpdatedFiles {
logger.Info(fmt.Sprintf("changeFiles != %d", expectedNumOfUpdatedFiles))
return false, "", nil
}
// if path of changed file contains "/development/" or "/production/"
fpath := string(query.Repository.PullRequest.Files.Edges[0].Node.Path)
if !(strings.Contains(fpath, "/development/") || strings.Contains(fpath, "/production/")) {
logger.Info(`path of changed file does contain neither "/development/" "/production/"`)
return false, "", nil
}
// if pr labels contains "dependencies"
actualLabels := []string{}
for _, edge := range query.Repository.PullRequest.Labels.Edges {
actualLabels = append(actualLabels, string(edge.Node.Name))
}
if !utils.Contains(actualLabels, "dependencies") {
logger.Info(`PR is not labeled "dependencies" Label`)
return false, "", nil
}
return true, string(query.Repository.PullRequest.HeadRefName), nil
}
func (g *GitHubApiClientImpl) CreateIssueComment(ctx context.Context, org, repo string, prNum int, body string) error {
client := githubv4.NewClient(oauth2.NewClient(ctx, g.tokenSource))
prId, err := g.getPullRequestId(ctx, org, repo, prNum)
if err != nil {
return xerrors.Errorf("getPullRequestId failed: %w", err)
}
var mutationAddComment struct {
AddComment struct {
Subject struct {
ID githubv4.ID
}
} `graphql:"addComment(input:$input)"`
}
if err := client.Mutate(ctx, &mutationAddComment, githubv4.AddCommentInput{
SubjectID: prId,
Body: githubv4.String(body),
}, nil); err != nil {
return xerrors.Errorf("%w", err)
}
return nil
}
func (g *GitHubApiClientImpl) CreateLabels(ctx context.Context, org, repo string, prNum int, labels []string) error {
client := githubv4.NewClient(oauth2.NewClient(ctx, g.tokenSource))
prId, err := g.getPullRequestId(ctx, org, repo, prNum)
if err != nil {
return xerrors.Errorf("getPullRequestId failed: %w", err)
}
labelIds := []githubv4.ID{}
for _, label := range labels {
labelId, err := g.getLabelId(ctx, org, repo, label)
if err != nil {
return xerrors.Errorf("getLabelId failed: %w", err)
}
labelIds = append(labelIds, labelId)
}
var mutationLabelPR struct {
UpdatePullRequest struct {
PullRequest struct {
ResourcePath githubv4.URI
}
} `graphql:"updatePullRequest(input:$input)"`
}
if err := client.Mutate(ctx, &mutationLabelPR, githubv4.UpdatePullRequestInput{
PullRequestID: prId,
LabelIDs: &labelIds,
}, nil); err != nil {
return xerrors.Errorf("CreateLabels failed: %w", err)
}
return nil
}
func (g *GitHubApiClientImpl) CreatePullRequest(ctx context.Context, org, repo, headBranch, baseBranch, title, body string) (prNum int, err error) {
client := githubv4.NewClient(oauth2.NewClient(ctx, g.tokenSource))
repoId, err := g.getRepositoryId(ctx, org, repo)
if err != nil {
return 0, xerrors.Errorf("getRepositoryId failed: %w", err)
}
var mutationCreatePR struct {
CreatePullRequest struct {
PullRequest struct {
Number int
}
} `graphql:"createPullRequest(input:$input)"`
}
if err := client.Mutate(ctx, &mutationCreatePR, githubv4.CreatePullRequestInput{
RepositoryID: repoId,
BaseRefName: githubv4.String(baseBranch),
HeadRefName: githubv4.String(headBranch),
Title: githubv4.String(title),
Body: githubv4.NewString(githubv4.String(body)),
}, nil); err != nil {
return 0, err
}
return mutationCreatePR.CreatePullRequest.PullRequest.Number, nil
}
func (g *GitHubApiClientImpl) DeleteBranch(ctx context.Context, org, repo, headBranch string) error {
client := githubv4.NewClient(oauth2.NewClient(ctx, g.tokenSource))
id, err := g.getBranchId(ctx, org, repo, headBranch)
if err != nil {
return xerrors.Errorf("getBranchId failed: %w", err)
}
var mutationDeleteBranch struct {
DeleteRef struct {
ClientMutationId githubv4.String
} `graphql:"deleteRef(input:$input)"`
}
if err := client.Mutate(ctx, &mutationDeleteBranch, githubv4.DeleteRefInput{
RefID: id,
}, nil); err != nil {
return xerrors.Errorf("%w", err)
}
return nil
}
func (g *GitHubApiClientImpl) GetPullRequestTitleAndChangedFilepaths(ctx context.Context, org, repo string, prNum int) (string, []string, error) {
client := githubv4.NewClient(oauth2.NewClient(ctx, g.tokenSource))
pageLimit := 10
var query struct {
Repository struct {
PullRequest struct {
Title githubv4.String
ChangedFiles githubv4.Int
Files struct {
Edges []struct {
Cursor githubv4.String
Node struct {
Path githubv4.String
}
}
} `graphql:"files(first:$first,after:$after)"`
} `graphql:"pullRequest(number:$pullRequestNumber)"`
} `graphql:"repository(owner:$repositoryOwner,name:$repositoryName)"`
}
queryVars := map[string]interface{}{
"repositoryOwner": githubv4.String(org),
"repositoryName": githubv4.String(repo),
"pullRequestNumber": githubv4.Int(prNum),
"first": githubv4.Int(pageLimit),
"after": githubv4.String(""),
}
title := ""
changedFilesNum := 1
changedFiles := []string{}
for i := 0; i*pageLimit < changedFilesNum; i++ {
if err := client.Query(ctx, &query, queryVars); err != nil {
return "", nil, xerrors.Errorf("%w", err)
}
for _, edge := range query.Repository.PullRequest.Files.Edges {
changedFiles = append(changedFiles, string(edge.Node.Path))
}
if len(query.Repository.PullRequest.Files.Edges) == pageLimit {
queryVars["after"] = query.Repository.PullRequest.Files.Edges[pageLimit].Cursor
}
title = string(query.Repository.PullRequest.Title)
changedFilesNum = int(query.Repository.PullRequest.ChangedFiles)
}
return title, changedFiles, nil
}
func (g *GitHubApiClientImpl) HealthCheck() error {
ctx := context.Background()
client := githubv4.NewClient(oauth2.NewClient(ctx, g.tokenSource))
var q struct {
Viewer struct {
Login githubv4.String
}
}
if err := client.Query(ctx, &q, nil); err != nil {
return xerrors.Errorf("%w", err)
}
return nil
}
func (g *GitHubApiClientImpl) UpdatePullRequestBody(ctx context.Context, org, repo string, prNum int, body string) error {
client := githubv4.NewClient(oauth2.NewClient(ctx, g.tokenSource))
prId, err := g.getPullRequestId(ctx, org, repo, prNum)
if err != nil {
return xerrors.Errorf("getRepositoryId failed: %w", err)
}
var mutation struct {
UpdatePullRequest struct {
PullRequest struct {
Number int
}
} `graphql:"updatePullRequest(input:$input)"`
}
if err := client.Mutate(ctx, &mutation, githubv4.UpdatePullRequestInput{
PullRequestID: prId,
Body: githubv4.NewString(githubv4.String(body)),
}, nil); err != nil {
return err
}
return nil
}
//
// Unexposed methods
//
func (g *GitHubApiClientImpl) getBranchId(ctx context.Context, org, repo, branch string) (githubv4.ID, error) {
client := githubv4.NewClient(oauth2.NewClient(ctx, g.tokenSource))
var queryGetBranchID struct {
Repository struct {
Ref struct {
ID githubv4.ID
} `graphql:"ref(qualifiedName:$qualifiedName)"`
} `graphql:"repository(owner:$repositoryOwner,name:$repositoryName)"`
}
if err := client.Query(ctx, &queryGetBranchID, map[string]interface{}{
"repositoryOwner": githubv4.String(org),
"repositoryName": githubv4.String(repo),
"qualifiedName": githubv4.String(branch),
}); err != nil {
return nil, xerrors.Errorf("%w", err)
}
return queryGetBranchID.Repository.Ref.ID, nil
}
func (g *GitHubApiClientImpl) getLabelId(ctx context.Context, org, repo, label string) (githubv4.ID, error) {
client := githubv4.NewClient(oauth2.NewClient(ctx, g.tokenSource))
var queryGetLabel struct {
Repository struct {
Label struct {
ID githubv4.ID
} `graphql:"label(name:$labelName)"`
} `graphql:"repository(owner:$repositoryOwner,name:$repositoryName)"`
}
if err := client.Query(ctx, &queryGetLabel, map[string]interface{}{
"repositoryOwner": githubv4.String(org),
"repositoryName": githubv4.String(repo),
"labelName": githubv4.String(label),
}); err != nil {
return nil, xerrors.Errorf("%w", err)
}
if queryGetLabel.Repository.Label.ID == nil {
return nil, xerrors.Errorf("no such label: %s", label)
}
return queryGetLabel.Repository.Label.ID, nil
}
func (g *GitHubApiClientImpl) getPullRequestId(ctx context.Context, org, repo string, prNum int) (githubv4.ID, error) {
client := githubv4.NewClient(oauth2.NewClient(ctx, g.tokenSource))
var queryGetPullRequest struct {
Repository struct {
PullRequest struct {
ID githubv4.ID
} `graphql:"pullRequest(number:$pullRequestNumber)"`
} `graphql:"repository(owner:$repositoryOwner,name:$repositoryName)"`
}
if err := client.Query(ctx, &queryGetPullRequest, map[string]interface{}{
"repositoryOwner": githubv4.String(org),
"repositoryName": githubv4.String(repo),
"pullRequestNumber": githubv4.Int(prNum),
}); err != nil {
return 0, xerrors.Errorf("%w", err)
}
return queryGetPullRequest.Repository.PullRequest.ID, nil
}
func (g *GitHubApiClientImpl) getRepositoryId(ctx context.Context, org, repo string) (githubv4.ID, error) {
client := githubv4.NewClient(oauth2.NewClient(ctx, g.tokenSource))
var queryGetRepository struct {
Repository struct {
ID githubv4.String
} `graphql:"repository(owner:$repositoryOwner,name:$repositoryName)"`
}
if err := client.Query(ctx, &queryGetRepository, map[string]interface{}{
"repositoryOwner": githubv4.String(org),
"repositoryName": githubv4.String(repo),
}); err != nil {
return 0, xerrors.Errorf("%w", err)
}
return queryGetRepository.Repository.ID, nil
}