/
githubContent.go
68 lines (59 loc) · 1.98 KB
/
githubContent.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
package githubContent
import (
"context"
"fmt"
"github.com/danbudris/vulnerabilityProcessor/pkg/git"
"golang.org/x/oauth2"
"strings"
"time"
"github.com/google/go-github/v45/github"
githubHelper "github.com/danbudris/vulnerabilityProcessor/pkg/github"
"github.com/danbudris/vulnerabilityProcessor/pkg/logger"
"github.com/danbudris/vulnerabilityProcessor/pkg/retier"
)
type Opts struct {
Owner string
File string
Repo string
}
func GetGithubRepositoryFileContent(ctx context.Context, retrier *retier.Retrier, opts *Opts) ([]byte, error){
token, err := git.GetGithubToken()
if err != nil {
return []byte{}, fmt.Errorf("creating pull request: %v", err)
}
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
tc := oauth2.NewClient(ctx, ts)
g := github.NewClient(tc)
var resp *github.Response
var f *github.RepositoryContent
var c string
logger.Info("Getting Github repository contents", "repository", opts.Repo, "path", opts.File, "owner", opts.Owner)
err = retrier.Retry(func() error {
o := &github.RepositoryContentGetOptions{
Ref: "main",
}
f, _, resp, err = g.Repositories.GetContents(ctx, opts.Owner, opts.Repo, opts.File, o)
if err != nil {
return fmt.Errorf("getting repository content: %v", err)
}
if resp.StatusCode == githubHelper.SecondaryRateLimitStatusCode {
if strings.Contains(err.Error(), githubHelper.SecondaryRateLimitResponse) {
return fmt.Errorf("rate limited while attempting to get github repository content: %v", err)
}
}
if err != nil {
return fmt.Errorf("getting Github repository content: %v; resp: %v", err, resp)
}
return nil
})
if err != nil {
return []byte{}, fmt.Errorf("getting github repository content: %v", err)
}
logger.V(4).Info("sleeping after fetching repository content to avoid secondary rate limiting by Github content API")
time.Sleep(time.Second * 1)
c, err = f.GetContent()
if err != nil {
return nil, fmt.Errorf("decoding repository content: %v", err)
}
return []byte(c), nil
}