-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
github.go
99 lines (92 loc) · 2.16 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
package pull_request
import (
"context"
"fmt"
"os"
"github.com/google/go-github/v35/github"
"golang.org/x/oauth2"
)
type GithubService struct {
client *github.Client
owner string
repo string
labels []string
}
var _ PullRequestService = (*GithubService)(nil)
func NewGithubService(ctx context.Context, token, url, owner, repo string, labels []string) (PullRequestService, error) {
var ts oauth2.TokenSource
// Undocumented environment variable to set a default token, to be used in testing to dodge anonymous rate limits.
if token == "" {
token = os.Getenv("GITHUB_TOKEN")
}
if token != "" {
ts = oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
}
httpClient := oauth2.NewClient(ctx, ts)
var client *github.Client
if url == "" {
client = github.NewClient(httpClient)
} else {
var err error
client, err = github.NewEnterpriseClient(url, url, httpClient)
if err != nil {
return nil, err
}
}
return &GithubService{
client: client,
owner: owner,
repo: repo,
labels: labels,
}, nil
}
func (g *GithubService) List(ctx context.Context) ([]*PullRequest, error) {
opts := &github.PullRequestListOptions{
ListOptions: github.ListOptions{
PerPage: 100,
},
}
pullRequests := []*PullRequest{}
for {
pulls, resp, err := g.client.PullRequests.List(ctx, g.owner, g.repo, opts)
if err != nil {
return nil, fmt.Errorf("error listing pull requests for %s/%s: %v", g.owner, g.repo, err)
}
for _, pull := range pulls {
if !containLabels(g.labels, pull.Labels) {
continue
}
pullRequests = append(pullRequests, &PullRequest{
Number: *pull.Number,
Branch: *pull.Head.Ref,
HeadSHA: *pull.Head.SHA,
})
}
if resp.NextPage == 0 {
break
}
opts.Page = resp.NextPage
}
return pullRequests, nil
}
// containLabels returns true if gotLabels contains expectedLabels
func containLabels(expectedLabels []string, gotLabels []*github.Label) bool {
for _, expected := range expectedLabels {
found := false
for _, got := range gotLabels {
if got.Name == nil {
continue
}
if expected == *got.Name {
found = true
break
}
}
if !found {
return false
}
}
return true
}