-
Notifications
You must be signed in to change notification settings - Fork 4
/
source_github.go
224 lines (188 loc) · 5.98 KB
/
source_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
package source
import (
"context"
"encoding/base64"
"fmt"
"regexp"
"strings"
"sync"
"github.com/bmatcuk/doublestar/v4"
kitlog "github.com/go-kit/kit/log"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/google/go-github/v52/github"
"github.com/pkg/errors"
"golang.org/x/oauth2"
"golang.org/x/sync/errgroup"
)
type SourceGitHub struct {
Repos []string `json:"repos"`
Files []string `json:"files"`
Token Credential `json:"token"`
}
func (s SourceGitHub) Validate() error {
return validation.ValidateStruct(&s,
validation.Field(&s.Repos, validation.Each(
validation.Match(regexp.MustCompile("^[^/]/.+$")).
Error("repos must be of the form owner/repo, or owner/* for matching all repos under that organization"),
)),
)
}
func (s SourceGitHub) String() string {
return fmt.Sprintf("github (repos=%s files=%s)", s.Repos, s.Files)
}
func (s SourceGitHub) Load(ctx context.Context, logger kitlog.Logger) ([]*SourceEntry, error) {
client := github.NewClient(oauth2.NewClient(ctx, oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: string(s.Token)},
)))
type Target struct {
Owner string // e.g. incident-io
Repo string // e.g. catalog-importer
Ref string // e.g. main or master
Matches []*github.TreeEntry
}
// Use this whenever we're modifying structures that are race unsafe.
var mu sync.Mutex
synchronise := func(do func()) {
defer mu.Unlock()
mu.Lock()
do()
}
// Expand any repo wildcards so we have a full list of repos for each owner we want to
// scan.
targets := []*Target{}
addTarget := func(logger kitlog.Logger, repo *github.Repository) {
synchronise(func() {
target := &Target{
Owner: repo.Owner.GetLogin(),
Repo: repo.GetName(),
Ref: repo.GetDefaultBranch(),
}
logger.Log("msg", "found GitHub repo",
"owner", target.Owner, "repo", target.Repo, "ref", target.Ref)
targets = append(targets, target)
})
}
{
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(10)
for _, providedRepo := range s.Repos {
components := strings.SplitN(providedRepo, "/", 2)
if len(components) != 2 {
return nil, fmt.Errorf("invalid format for repo must be owner/repo but got '%s'", providedRepo)
}
g.Go(func() error {
owner, repoNameOrWildcard := components[0], components[1]
// We've found an owner/* repo, so we must find all the repos under this organisation.
if repoNameOrWildcard == "*" {
logger.Log("msg", "found repo wildcard, resolving repo list", "owner", owner)
opts := &github.RepositoryListByOrgOptions{
ListOptions: github.ListOptions{PerPage: 100},
}
for {
logger.Log("msg", "paging for repos...")
page, resp, err := client.Repositories.ListByOrg(ctx, owner, opts)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("listing GitHub repos for organization '%s'", owner))
}
for _, repo := range page {
addTarget(logger, repo)
}
if resp.NextPage == 0 {
break
}
opts.Page = resp.NextPage
}
} else {
// The repo is specified, so we just need to resolve it so we can fetch the
// default branch.
resolved, _, err := client.Repositories.Get(ctx, owner, repoNameOrWildcard)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("accessing '%s/%s'", owner, repoNameOrWildcard))
}
addTarget(logger, resolved)
}
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
}
{
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(10)
for idx := range targets {
target := targets[idx]
g.Go(func() error {
logger.Log("msg", "listing GitHub tree",
"owner", target.Owner, "repo", target.Repo, "ref", target.Ref)
tree, _, err := client.Git.GetTree(ctx, target.Owner, target.Repo, target.Ref, true)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("getting tree for '%s/%s' at ref %s", target.Owner, target.Repo, target.Ref))
}
for _, pattern := range s.Files {
for _, treeEntry := range tree.Entries {
if treeEntry.GetType() != "blob" {
continue // we're only interested in files
}
match, err := doublestar.Match(pattern, treeEntry.GetPath())
if err != nil {
return errors.Wrap(err, "matching file pattern")
}
if match {
synchronise(func() {
target.Matches = append(target.Matches, treeEntry)
})
}
}
}
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
}
entries := []*SourceEntry{}
{
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(10)
for idx := range targets {
target := targets[idx]
for jdx := range target.Matches {
match := target.Matches[jdx]
g.Go(func() error {
blob, _, err := client.Git.GetBlob(ctx, target.Owner, target.Repo, match.GetSHA())
if err != nil {
return errors.Wrap(err,
fmt.Sprintf("getting blob for '%s' from repo '%s/%s' at SHA %s", match.GetPath(), target.Owner, target.Repo, target.Ref))
}
if blob.GetEncoding() != "base64" {
logger.Log("msg", "found matching GitHub file but incorrect encoding meant it wasn't processed",
"owner", target.Owner, "repo", target.Repo, "ref", target.Ref, "path", match.GetPath())
return nil
}
data, err := base64.StdEncoding.DecodeString(blob.GetContent())
if err != nil {
return errors.Wrap(err,
fmt.Sprintf("decoding base64 blob for '%s' from repo '%s/%s' at SHA %s", match.GetPath(), target.Owner, target.Repo, target.Ref))
}
synchronise(func() {
logger.Log("msg", "found matching GitHub file",
"owner", target.Owner, "repo", target.Repo, "ref", target.Ref, "path", match.GetPath())
entries = append(entries, &SourceEntry{
Origin: fmt.Sprintf("github (repo=%s/%s path=%s)", target.Owner, target.Repo, match.GetPath()),
Filename: match.GetPath(),
Content: []byte(data),
})
})
return nil
})
}
}
if err := g.Wait(); err != nil {
return nil, err
}
}
return entries, nil
}