forked from friendsofgo/pr-size-labeler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
296 lines (252 loc) · 6.82 KB
/
main.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package main
import (
"bytes"
"context"
"encoding/csv"
"fmt"
"os"
"os/exec"
"strconv"
"github.com/bmatcuk/doublestar/v4"
"github.com/google/go-github/v31/github"
"github.com/kelseyhightower/envconfig"
"github.com/posener/goaction"
"github.com/posener/goaction/actionutil"
"github.com/posener/goaction/log"
"gopkg.in/yaml.v3"
)
type (
// Config is the data structure used to define the action settings.
Config struct {
GitHubToken string `envconfig:"GITHUB_TOKEN" required:"true"`
Thresholds Thresholds
ThresholdsYAML string `envconfig:"THRESHOLDS"`
ExcludePaths []string
ExcludePathsYAML string `envconfig:"EXCLUDE_PATHS"`
}
// Size defines a specific thresholds and label to be used.
Size struct {
LessThan int `yaml:"less_than"`
Label string `yaml:"label"`
}
// Thresholds defines a set of thresholds.
Thresholds struct {
XS Size `yaml:"xs"`
S Size `yaml:"s"`
M Size `yaml:"m"`
L Size `yaml:"l"`
FailIfXL bool `yaml:"fail_if_xl"`
MessageIfXL string `yaml:"message_if_xl"`
}
)
func main() {
if !goaction.CI {
log.Warnf("Not in GitHub Action mode, quitting...")
return
}
if goaction.Event != goaction.EventPullRequest {
log.Debugf("Not a pull request action, nothing to do here...")
return
}
config, err := getConfig()
if err != nil {
log.Fatalf("Required configuration is missing: %s", err)
}
event, err := goaction.GetPullRequest()
if err != nil {
log.Fatalf("Error happened while getting event info: %s", err)
}
ctx := context.Background()
gh := actionutil.NewClientWithToken(ctx, config.GitHubToken)
label, isXL, err := GetPrLabel(config, event)
if err != nil {
log.Fatalf("Error happened while getting label: %s", err)
}
log.Printf("Label: %s, isXL: %t", label, isXL)
err = replaceLabels(ctx, gh, config, label)
if err != nil {
log.Fatalf("Error happened while adding label: %s", err)
}
if !isXL {
log.Debugf("Pull request successfully labeled")
return
}
_, _, err = gh.PullRequestsCreateComment(ctx, goaction.PrNum(), &github.PullRequestComment{
Body: github.String(config.Thresholds.MessageIfXL),
})
if err != nil {
log.Fatalf("Error happened while adding comment: %s", err)
}
if config.Thresholds.FailIfXL {
log.Fatalf("PR size is XL, make it shorter, please!")
}
log.Debugf("Pull request successfully labeled")
}
// CalculateModifications calls out to `git diff | diffstat` and parses the output to determine the number of changed lines.
func CalculateModifications(config Config, event *github.PullRequestEvent) int {
output := getDiffstatCSV(event.GetPullRequest().GetBase().GetSHA())
stats := parseDiffstatOutput(output)
applyExclusions := func(stat diffstat) bool {
for _, excludeGlob := range config.ExcludePaths {
if matched, _ := doublestar.Match(excludeGlob, stat.FileName); matched {
log.Printf("Excluded file: %s", stat.FileName)
return false
}
}
return true
}
filtered := filter(applyExclusions, stats)
accumChangedLines := func(size int, file diffstat) int {
return size + file.Modified + file.Deleted + file.Inserted
}
return reduce(accumChangedLines, 0, filtered)
}
func getDiffstatCSV(target string) []byte {
if err := exec.Command("bash", "-c", `git config --global --add safe.directory "$GITHUB_WORKSPACE"`).Run(); err != nil {
log.Fatalf("Error happened while running git config: %s", err)
}
command := exec.Command("bash", "-c", fmt.Sprintf("git diff %s | diffstat -mbqt", target))
command.Stderr = os.Stderr
output, err := command.Output()
if err != nil {
log.Fatalf("Error happened while running diffstat: %s", err)
}
log.Printf("Diffstat output: \n%s\n", string(output))
return output
}
func parseDiffstatOutput(output []byte) []diffstat {
data, err := csv.NewReader(bytes.NewReader(output)).ReadAll()
if err != nil {
log.Fatalf("Error happened while reading diffstat output: %s", err)
}
stats := []diffstat{}
for i, datum := range data {
if i == 0 {
continue
}
stats = append(stats, diffstat{
Inserted: must(strconv.Atoi(datum[0])),
Deleted: must(strconv.Atoi(datum[1])),
Modified: must(strconv.Atoi(datum[2])),
FileName: datum[3],
})
}
return stats
}
func replaceLabels(ctx context.Context, gh *actionutil.Client, config Config, label string) error {
ghLabels, _, err := gh.IssuesListLabelsByIssue(ctx, goaction.PrNum(), nil)
if err != nil {
return err
}
confLabels := config.Thresholds.GetLabels()
for _, ghLabel := range ghLabels {
if contains(confLabels, ghLabel.GetName()) {
_, err = gh.IssuesRemoveLabelForIssue(ctx, goaction.PrNum(), ghLabel.GetName())
if err != nil {
return err
}
}
}
_, _, err = gh.IssuesAddLabelsToIssue(ctx, goaction.PrNum(), []string{label})
return err
}
func getConfig() (Config, error) {
config := Config{
Thresholds: defaultThresholds(),
}
err := envconfig.Process("input", &config)
if err != nil {
return Config{}, err
}
if err := yaml.Unmarshal([]byte(config.ThresholdsYAML), &config.Thresholds); err != nil {
return Config{}, err
}
if err := yaml.Unmarshal([]byte(config.ExcludePathsYAML), &config.ExcludePaths); err != nil {
return Config{}, err
}
return config, err
}
func GetPrLabel(config Config, event *github.PullRequestEvent) (string, bool, error) {
totalChanges := CalculateModifications(config, event)
log.Printf("Total changes: %d lines", totalChanges)
return config.Thresholds.DetermineLabel(totalChanges), totalChanges > config.Thresholds.L.LessThan, nil
}
func (t Thresholds) GetLabels() []string {
return []string{
t.XS.Label,
t.S.Label,
t.M.Label,
t.L.Label,
}
}
func defaultThresholds() Thresholds {
return Thresholds{
XS: Size{
LessThan: 10,
Label: "size/xs",
},
S: Size{
LessThan: 100,
Label: "size/s",
},
M: Size{
LessThan: 500,
Label: "size/m",
},
L: Size{
LessThan: 1000,
Label: "size/l",
},
FailIfXL: false,
MessageIfXL: "This PR is too big. Please, split it.",
}
}
func (t Thresholds) DetermineLabel(size int) string {
switch {
case size < t.XS.LessThan:
return t.XS.Label
case size < t.S.LessThan:
return t.S.Label
case size < t.M.LessThan:
return t.M.Label
case size < t.L.LessThan:
return t.L.Label
default:
return "XL"
}
}
func contains(a []string, x string) bool {
for _, n := range a {
if x == n {
return true
}
}
return false
}
func filter[A any](f func(A) bool, list []A) []A {
res := make([]A, 0, len(list))
for _, v := range list {
if f(v) {
res = append(res, v)
}
}
return res
}
func reduce[T any, R any](accumulator func(agg R, item T) R, initial R, collection []T) R {
for _, item := range collection {
initial = accumulator(initial, item)
}
return initial
}
func must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
type diffstat struct {
Inserted int
Deleted int
Modified int
FileName string
}