/
issueManager.go
92 lines (81 loc) · 2.44 KB
/
issueManager.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
package issueManager
import (
"context"
"fmt"
"github.com/danbudris/vulnerabilityProcessor/pkg/retier"
"github.com/google/go-github/v45/github"
"golang.org/x/oauth2"
"strings"
"time"
"github.com/danbudris/vulnerabilityProcessor/pkg/git"
githubHelper "github.com/danbudris/vulnerabilityProcessor/pkg/github"
"github.com/danbudris/vulnerabilityProcessor/pkg/logger"
)
var client *github.Client
type IssueManager struct {
sourceOwner string
sourceRepo string
retrier *retier.Retrier
}
type Opts struct {
SourceOwner string
SourceRepo string
}
func New(r *retier.Retrier, opts *Opts) *IssueManager {
return &IssueManager{
sourceOwner: opts.SourceOwner,
sourceRepo: opts.SourceRepo,
retrier: r,
}
}
type CreateIssueOpts struct {
Title *string
Body *string
Labels *[]string
Assignee *string
State *string
}
func (p *IssueManager) CreateIssue(ctx context.Context, opts *CreateIssueOpts) (*github.Issue, error) {
token, err := git.GetGithubToken()
if err != nil {
return nil, fmt.Errorf("creating Github issue: %v", err)
}
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
tc := oauth2.NewClient(ctx, ts)
client = github.NewClient(tc)
i := &github.IssueRequest{
Title: opts.Title,
Body: opts.Body,
Labels: opts.Labels,
Assignee: opts.Assignee,
State: opts.State,
}
var issue *github.Issue
var resp *github.Response
err = p.retrier.Retry(func() error {
issue, resp, err = client.Issues.Create(ctx, p.sourceOwner, p.sourceRepo, i)
if resp.StatusCode == githubHelper.SecondaryRateLimitStatusCode {
var b []byte
_, err := resp.Body.Read(b)
if err != nil {
return fmt.Errorf("reading Github response body: %v", err)
}
if strings.Contains(string(b), githubHelper.SecondaryRateLimitResponse) {
logger.V(4).Info("rate limited while attempting to create github issue")
return fmt.Errorf("rate limited while attempting to create github issues: %v", err)
}
}
if err != nil {
return fmt.Errorf("creating Github issue: %v; resp: %v", err, resp)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("creating github issue: %v", err)
}
logger.V(4).Info("create issue response", "response", resp.Response.StatusCode)
logger.V(1).Info("Github issue created", "issue URL", issue.GetHTMLURL())
logger.V(4).Info("sleeping after Issue creation to avoid secondary rate limiting by Github content API")
time.Sleep(time.Second * 1)
return issue, nil
}