/
pr.go
176 lines (155 loc) · 5.41 KB
/
pr.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
package review
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"os"
"strings"
"time"
"github.com/google/go-github/v44/github"
)
// GithubPREvent is a struct for GitHub Pull Request Event.
// ref: https://docs.github.com/ja/webhooks/webhook-events-and-payloads#pull_request
// example: https://github.com/pingdotgg/sample_hooks/blob/main/github_pr_opened.json
type GithubPREvent struct {
Action string `json:"action"`
Number int `json:"number"`
PullRequest *github.PullRequest `json:"pull_request"`
Repository *github.Repository `json:"repository"`
Owner string `json:"owner"`
RepoName string `json:"repo_name"`
}
func (r *reviewService) GetGithubPREvent() (*GithubPREvent, error) {
file, err := os.Open(r.opt.GithubEventPath)
if err != nil {
return nil, fmt.Errorf("failed to open file: path=%s, err=%w", r.opt.GithubEventPath, err)
}
defer file.Close()
var event GithubPREvent
decoder := json.NewDecoder(file)
err = decoder.Decode(&event)
if err != nil {
return nil, fmt.Errorf("failed to decode json: err=%w", err)
}
if event.Repository == nil || event.Repository.FullName == nil {
return nil, fmt.Errorf("invalid repository: %v", event.Repository)
}
fullName := *event.Repository.FullName
if !strings.Contains(fullName, "/") {
return nil, fmt.Errorf("invalid repository name: %s", fullName)
}
event.Owner = strings.Split(fullName, "/")[0]
event.RepoName = strings.Split(fullName, "/")[1]
return &event, nil
}
const (
NO_REVIEW_COMMENT = "セキュリティレビューを実施しました。\n特に問題は見つかりませんでした👏\n\n_By RISKEN review_"
)
func (r *reviewService) PullRequestComment(ctx context.Context, pr *GithubPREvent, scanResults []*ScanResult) error {
// No Review Comment
if len(scanResults) == 0 {
comments, err := r.getAllIssueComments(ctx, pr.Owner, pr.RepoName, pr.Number)
if err != nil {
return fmt.Errorf("failed to get all issue comments: err=%w", err)
}
if existsSimilarIssueComment(comments, "特に問題は見つかりませんでした") {
r.logger.WarnContext(ctx, "already exists similar issue comment")
return nil
}
comment := &github.IssueComment{
Body: github.String(NO_REVIEW_COMMENT),
}
_, _, err = r.githubClient.Issues.CreateComment(ctx, pr.Owner, pr.RepoName, pr.Number, comment)
if err != nil {
return fmt.Errorf("failed to create comment: err=%w", err)
}
return nil
}
// Review Comment
comments, err := r.getAllPRComments(ctx, pr.Owner, pr.RepoName, pr.Number)
if err != nil {
return fmt.Errorf("failed to get all comments: err=%w", err)
}
for _, result := range scanResults {
if existsSimilarPRComment(comments, result.ScanID) {
r.logger.WarnContext(ctx, "already exists similar comment", slog.String("file", result.File), slog.Int("line", result.Line), slog.String("ID", result.ScanID))
continue
}
comment := &github.PullRequestComment{
Body: github.String(generatePRReviewComment(result)),
CommitID: github.String(*pr.PullRequest.Head.SHA),
Path: github.String(result.File),
Line: github.Int(result.Line),
}
_, _, err := r.githubClient.PullRequests.CreateComment(ctx, pr.Owner, pr.RepoName, pr.Number, comment)
if err != nil {
r.logger.WarnContext(ctx, "failed to create comment", slog.String("file", result.File), slog.Int("line", result.Line), slog.String("err", err.Error()))
continue
}
}
return nil
}
func (r *reviewService) getAllIssueComments(ctx context.Context, owner, repo string, issueNumber int) ([]*github.IssueComment, error) {
var allComments []*github.IssueComment
opts := &github.IssueListCommentsOptions{ListOptions: github.ListOptions{PerPage: 100}} // ページごとのアイテム数を設定
for {
comments, resp, err := r.githubClient.Issues.ListComments(ctx, owner, repo, issueNumber, opts)
if err != nil {
return nil, err
}
allComments = append(allComments, comments...)
if resp.NextPage == 0 {
break
}
opts.Page = resp.NextPage
}
return allComments, nil
}
func (r *reviewService) getAllPRComments(ctx context.Context, owner, repo string, prNumber int) ([]*github.PullRequestComment, error) {
var allComments []*github.PullRequestComment
opts := &github.PullRequestListCommentsOptions{ListOptions: github.ListOptions{PerPage: 100}}
for {
comments, resp, err := r.githubClient.PullRequests.ListComments(ctx, owner, repo, prNumber, opts)
if err != nil {
return nil, err
}
allComments = append(allComments, comments...)
if resp.NextPage == 0 {
break
}
opts.Page = resp.NextPage
time.Sleep(500 * time.Millisecond)
}
return allComments, nil
}
func existsSimilarPRComment(comments []*github.PullRequestComment, key string) bool {
for _, c := range comments {
if strings.Contains(*c.Body, key) {
return true
}
}
return false
}
func existsSimilarIssueComment(comments []*github.IssueComment, key string) bool {
for _, c := range comments {
if strings.Contains(*c.Body, key) {
return true
}
}
return false
}
const (
RISKEN_COMMENT_TEMPLATE = `
#### RISKENで確認
より詳細な情報や生成AIによる解説はRISKENコンソール上で確認できます。
- %s`
)
func generatePRReviewComment(result *ScanResult) string {
reviewComment := result.ReviewComment
if result.RiskenURL != "" {
reviewComment += fmt.Sprintf(RISKEN_COMMENT_TEMPLATE, result.RiskenURL)
}
reviewComment += "\n\n_By RISKEN review_"
return reviewComment
}