/
github.go
325 lines (290 loc) · 7.81 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
/*
Copyright AppsCode Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package lib
import (
"context"
"fmt"
"net/http"
"os"
"strings"
"github.com/appscodelabs/release-automaton/api"
"github.com/google/go-github/v32/github"
"golang.org/x/oauth2"
"k8s.io/apimachinery/pkg/util/sets"
)
func NewGitHubClient() *github.Client {
token, found := os.LookupEnv(api.GitHubTokenKey)
if !found {
panic(api.GitHubTokenKey + " env var is not set")
}
// Create the http client.
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(context.TODO(), ts)
return github.NewClient(tc)
}
func ListLabelsByIssue(ctx context.Context, gh *github.Client, owner, repo string, number int) (sets.String, error) {
opt := &github.ListOptions{
PerPage: 100,
}
result := sets.NewString()
for {
labels, resp, err := gh.Issues.ListLabelsByIssue(ctx, owner, repo, number, opt)
if err != nil {
break
}
for _, entry := range labels {
result.Insert(entry.GetName())
}
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
return result, nil
}
func ListRelease(ctx context.Context, gh *github.Client, owner, repo string) ([]*github.RepositoryRelease, error) {
opt := &github.ListOptions{
PerPage: 100,
}
var result []*github.RepositoryRelease
for {
releases, resp, err := gh.Repositories.ListReleases(ctx, owner, repo, opt)
if err != nil {
break
}
result = append(result, releases...)
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
return result, nil
}
func ListReviews(ctx context.Context, gh *github.Client, owner, repo string, number int) ([]*github.PullRequestReview, error) {
opt := &github.ListOptions{
PerPage: 100,
}
var result []*github.PullRequestReview
for {
reviews, resp, err := gh.PullRequests.ListReviews(ctx, owner, repo, number, opt)
if err != nil {
break
}
result = append(result, reviews...)
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
return result, nil
}
func ListPullRequestComment(ctx context.Context, gh *github.Client, owner, repo string, number int) ([]*github.PullRequestComment, error) {
opt := &github.PullRequestListCommentsOptions{
Sort: "created",
Direction: "asc",
ListOptions: github.ListOptions{
PerPage: 100,
},
}
var result []*github.PullRequestComment
for {
comments, resp, err := gh.PullRequests.ListComments(ctx, owner, repo, number, opt)
if err != nil {
break
}
result = append(result, comments...)
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
return result, nil
}
func ListComments(ctx context.Context, gh *github.Client, owner, repo string, number int) ([]*github.IssueComment, error) {
opt := &github.IssueListCommentsOptions{
Sort: github.String("created"),
Direction: github.String("asc"),
ListOptions: github.ListOptions{
PerPage: 100,
},
}
var result []*github.IssueComment
for {
comments, resp, err := gh.Issues.ListComments(ctx, owner, repo, number, opt)
if err != nil {
break
}
result = append(result, comments...)
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
return result, nil
}
// https://developer.github.com/v3/pulls/reviews/#create-a-review-for-a-pull-request
func PRApproved(gh *github.Client, owner string, repo string, prNumber int) bool {
reviews, err := ListReviews(context.TODO(), gh, owner, repo, prNumber)
if err != nil {
panic(err)
}
for _, review := range reviews {
if review.GetState() == "REQUEST_CHANGES" {
return false
}
}
for _, review := range reviews {
if review.GetState() == "APPROVED" {
return true
}
}
return false
}
func CreatePR(gh *github.Client, owner string, repo string, req *github.NewPullRequest, labels ...string) (*github.PullRequest, error) {
labelSet := sets.NewString(labels...)
var result *github.PullRequest
head := req.GetHead()
if !strings.ContainsRune(head, ':') {
head = owner + ":" + req.GetHead()
}
prs, _, err := gh.PullRequests.List(context.TODO(), owner, repo, &github.PullRequestListOptions{
State: "open",
Head: head,
Base: req.GetBase(),
ListOptions: github.ListOptions{
PerPage: 1,
},
})
if err != nil {
return nil, err
}
if len(prs) == 0 {
result, _, err = gh.PullRequests.Create(context.TODO(), owner, repo, req)
// "A pull request already Exists" error should NEVER happen since we already checked for existence
if err != nil {
return nil, err
}
//if e2, ok := err.(*github.ErrorResponse); ok {
// var matched bool
// for _, entry := range e2.Errors {
// if strings.HasPrefix(entry.Message, "A pull request already Exists") {
// matched = true
// break
// }
// }
// if !matched {
// return nil, err
// }
// // else ignore error because pr already Exists
// // else should NEVER happen since we already checked for existence
//} else if err != nil {
// return nil, err
//}
} else {
result = prs[0]
for _, label := range result.Labels {
labelSet.Delete(label.GetName())
}
}
if labelSet.Len() > 0 {
_, _, err := gh.Issues.AddLabelsToIssue(context.TODO(), owner, repo, result.GetNumber(), labelSet.UnsortedList())
if err != nil {
return nil, err
}
}
return result, err
}
func ClosePR(gh *github.Client, owner string, repo string, head, base string) (*github.PullRequest, error) {
if !strings.ContainsRune(head, ':') {
head = owner + ":" + head
}
prs, _, err := gh.PullRequests.List(context.TODO(), owner, repo, &github.PullRequestListOptions{
State: "open",
Head: head,
Base: base,
ListOptions: github.ListOptions{
PerPage: 1,
},
})
if err != nil {
return nil, err
}
if len(prs) == 1 {
pr, _, err := gh.PullRequests.Edit(context.TODO(), owner, repo, prs[0].GetNumber(), &github.PullRequest{
State: github.String("closed"),
})
return pr, err
}
return nil, fmt.Errorf("pr not found")
}
func LabelPR(gh *github.Client, owner string, repo, head, base string, labels ...string) error {
labelSet := sets.NewString(labels...)
var result *github.PullRequest
if !strings.ContainsRune(head, ':') {
head = owner + ":" + head
}
prs, _, err := gh.PullRequests.List(context.TODO(), owner, repo, &github.PullRequestListOptions{
State: "open",
Head: head,
Base: base,
ListOptions: github.ListOptions{
PerPage: 1,
},
})
if err != nil {
return err
}
if len(prs) == 0 {
return fmt.Errorf("no open pr found")
}
result = prs[0]
for _, label := range result.Labels {
labelSet.Delete(label.GetName())
}
if labelSet.Len() > 0 {
_, _, err := gh.Issues.AddLabelsToIssue(context.TODO(), owner, repo, result.GetNumber(), labelSet.UnsortedList())
if err != nil {
return err
}
}
return nil
}
func RemoveLabel(gh *github.Client, owner string, repo string, number int, label string) error {
_, err := gh.Issues.RemoveLabelForIssue(context.TODO(), owner, repo, number, label)
if ge, ok := err.(*github.ErrorResponse); ok {
if ge.Response.StatusCode == http.StatusNotFound {
return nil
}
}
return err
}
func ListTags2(ctx context.Context, gh *github.Client, owner, repo string) ([]*github.RepositoryTag, error) {
opt := &github.ListOptions{
PerPage: 100,
}
var result []*github.RepositoryTag
for {
reviews, resp, err := gh.Repositories.ListTags(ctx, owner, repo, opt)
if err != nil {
break
}
result = append(result, reviews...)
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
return result, nil
}