-
Notifications
You must be signed in to change notification settings - Fork 21
/
github.go
270 lines (235 loc) · 7.24 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
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
/*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"github.com/sirupsen/logrus"
)
var prr = regexp.MustCompile(`^Merge pull request(?: #([0-9]+))? from (\S+)$`)
type githubChangeProcessor struct {
repo string
linkName string
cache Cache
refreshCache bool
}
func githubChange(repo, linkName string, cache Cache, refreshCache bool) changeProcessor {
return &githubChangeProcessor{
repo: repo,
linkName: linkName,
cache: cache,
refreshCache: refreshCache,
}
}
func (p *githubChangeProcessor) process(c *change) error {
if matches := prr.FindSubmatch([]byte(c.Description)); len(matches) == 3 {
if len(matches[1]) > 0 {
pr, err := strconv.ParseInt(string(matches[1]), 10, 64)
if err != nil {
return err
}
info, err := p.getPRInfo(p.repo, pr)
if err != nil {
return err
}
p.prChange(c, info, pr)
} else if strings.HasPrefix(string(matches[2]), "GHSA-") {
ghsa := string(matches[2])
info, err := p.getAdvisoryInfo(p.repo, ghsa)
if err != nil {
return err
}
p.advisoryChange(c, info, ghsa)
} else {
logrus.Debugf("Nothing matched: %q", c.Description)
}
c.IsMerge = true
} else if strings.HasPrefix(c.Description, "Merge") {
logrus.WithField("matches", matches).Debugf("Not matched: %q", c.Description)
}
if c.Formatted == "" {
full, err := git("rev-parse", c.Commit)
if err != nil {
return err
}
commit := strings.TrimSpace(string(full))
c.Title = c.Description
c.Link = fmt.Sprintf("https://github.com/%s/commit/%s", p.repo, commit)
c.Formatted = fmt.Sprintf("[`%s`](%s) %s", c.Commit, c.Link, c.Description)
}
return nil
}
func (p *githubChangeProcessor) prChange(c *change, info pullRequestInfo, pr int64) {
for _, l := range info.Labels {
if l.Name == "impact/changelog" {
c.IsHighlight = true
} else if l.Name == "impact/breaking" {
c.IsBreaking = true
} else if l.Name == "impact/deprecation" {
c.IsDeprecation = true
} else if strings.HasPrefix(l.Name, "area/") {
if l.Description != "" {
c.Category = l.Description
} else {
c.Category = l.Name[5:]
}
}
}
c.Title = info.Title
if len(c.Title) > 0 && c.Title[0] == '[' {
idx := strings.IndexByte(c.Title, ']')
if idx > 0 {
c.Title = strings.TrimSpace(c.Title[idx+1:])
}
}
if c.Link == "" {
c.Link = fmt.Sprintf("https://github.com/%s/pull/%d", p.repo, pr)
}
c.Formatted = fmt.Sprintf("%s ([%s#%d](%s))", c.Title, p.linkName, pr, c.Link)
}
type pullRequestLabel struct {
Name string `json:"name"`
Description string `json:"description"`
}
type pullRequestInfo struct {
Title string `json:"title"`
Labels []pullRequestLabel `json:"labels"`
}
// getPRInfo returns the Pull Request info from the github API
//
// See https://docs.github.com/en/rest/pulls/pulls?apiVersion=2022-11-28#get-a-pull-request
func (p *githubChangeProcessor) getPRInfo(repo string, prn int64) (pullRequestInfo, error) {
u := fmt.Sprintf("https://api.github.com/repos/%s/pulls/%d", repo, prn)
key := u + " title labels"
if !p.refreshCache {
if b, ok := p.cache.Get(key); ok {
var info pullRequestInfo
if err := json.Unmarshal(b, &info); err == nil {
return info, nil
}
}
}
req, err := http.NewRequest("GET", u, nil)
if err != nil {
return pullRequestInfo{}, err
}
req.Header.Add("Accept", "application/vnd.github+json")
req.Header.Add("X-GitHub-Api-Version", "2022-11-28")
if user, token := os.Getenv("GITHUB_ACTOR"), os.Getenv("GITHUB_TOKEN"); user != "" && token != "" {
req.SetBasicAuth(user, token)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return pullRequestInfo{}, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
if resp.StatusCode >= 403 {
logrus.Warn("Forbidden response, try setting GITHUB_ACTOR and GITHUB_TOKEN environment variables")
}
return pullRequestInfo{}, fmt.Errorf("unexpected status code %d for %s", resp.StatusCode, u)
}
dec := json.NewDecoder(resp.Body)
var info pullRequestInfo
if err := dec.Decode(&info); err != nil {
return pullRequestInfo{}, err
}
if info.Title == "" {
return pullRequestInfo{}, fmt.Errorf("unexpected empty title for %s", u)
}
cacheB, err := json.Marshal(info)
if err == nil {
p.cache.Put(key, cacheB)
}
return info, nil
}
func (p *githubChangeProcessor) advisoryChange(c *change, info advisoryInfo, ghsa string) {
c.IsSecurity = true
c.Link = info.Link
if c.Link == "" {
c.Link = fmt.Sprintf("https://github.com/%s/security/advisories/%s", p.repo, ghsa)
}
summary := info.Summary
if summary == "" {
summary = "Github Security Advisory"
}
c.Formatted = fmt.Sprintf("%s [%s](%s)", summary, ghsa, c.Link)
cveInfo := []string{}
if info.CVE != "" {
cveInfo = append(cveInfo, info.CVE)
}
if info.Severity != "" {
cveInfo = append(cveInfo, info.Severity)
}
if len(cveInfo) > 0 {
prefix := "[" + strings.Join(cveInfo, ", ") + "] "
c.Formatted = prefix + c.Formatted
}
}
type advisoryInfo struct {
CVE string `json:"cve_id"`
Link string `json:"html_url"`
Summary string `json:"summary"`
Description string `json:"description"`
Severity string `json:"severity"`
}
// getAdvisoryInfo returns github security advisory info
//
// See https://docs.github.com/en/rest/security-advisories/repository-advisories?apiVersion=2022-11-28#get-a-repository-security-advisory
func (p *githubChangeProcessor) getAdvisoryInfo(repo, advisory string) (advisoryInfo, error) {
u := fmt.Sprintf("https://api.github.com/repos/%s/security-advisories/%s", repo, advisory)
key := u + " cve link summary description severity"
if !p.refreshCache {
if b, ok := p.cache.Get(key); ok {
var info advisoryInfo
if err := json.Unmarshal(b, &info); err == nil {
return info, nil
}
}
}
req, err := http.NewRequest("GET", u, nil)
if err != nil {
return advisoryInfo{}, err
}
req.Header.Add("Accept", "application/vnd.github+json")
req.Header.Add("X-GitHub-Api-Version", "2022-11-28")
if user, token := os.Getenv("GITHUB_ACTOR"), os.Getenv("GITHUB_TOKEN"); user != "" && token != "" {
req.SetBasicAuth(user, token)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return advisoryInfo{}, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
if resp.StatusCode >= 403 {
logrus.Warn("Forbidden response, try setting GITHUB_USER and GITHUB_TOKEN environment variables")
}
return advisoryInfo{}, fmt.Errorf("unexpected status code %d for %s", resp.StatusCode, u)
}
dec := json.NewDecoder(resp.Body)
var info advisoryInfo
if err := dec.Decode(&info); err != nil {
return advisoryInfo{}, err
}
cacheB, err := json.Marshal(info)
if err == nil {
p.cache.Put(key, cacheB)
}
return info, nil
}