forked from kubernetes-retired/contrib
/
size.go
283 lines (245 loc) · 6.78 KB
/
size.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
/*
Copyright 2015 The Kubernetes 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 mungers
import (
"fmt"
"path"
"regexp"
"strings"
"k8s.io/contrib/mungegithub/features"
"k8s.io/contrib/mungegithub/github"
"k8s.io/kubernetes/pkg/util/sets"
"github.com/golang/glog"
githubapi "github.com/google/go-github/github"
"github.com/spf13/cobra"
)
const (
labelSizePrefix = "size/"
)
var (
sizeRE = regexp.MustCompile("Labelling this PR as " + labelSizePrefix + "(XS|S|M|L|XL|XXL)")
)
// SizeMunger will update a label on a PR based on how many lines are changed.
// It will exclude certain files in it's calculations based on the config
// file provided in --generated-files-config
type SizeMunger struct {
GeneratedFilesFile string
genFilePaths sets.String
genFilePrefixes sets.String
genFileNames sets.String
genPathPrefixes sets.String
}
func init() {
s := &SizeMunger{}
RegisterMungerOrDie(s)
RegisterStaleComments(s)
}
// Name is the name usable in --pr-mungers
func (SizeMunger) Name() string { return "size" }
// RequiredFeatures is a slice of 'features' that must be provided
func (SizeMunger) RequiredFeatures() []string { return []string{} }
// Initialize will initialize the munger
func (s *SizeMunger) Initialize(config *github.Config, features *features.Features) error {
glog.Infof("generated-files-config: %#v\n", s.GeneratedFilesFile)
return nil
}
// EachLoop is called at the start of every munge loop
func (SizeMunger) EachLoop() error { return nil }
// AddFlags will add any request flags to the cobra `cmd`
func (s *SizeMunger) AddFlags(cmd *cobra.Command, config *github.Config) {
cmd.Flags().StringVar(&s.GeneratedFilesFile, "generated-files-config", "", "file in the repo containing the generated file rules")
}
// getGeneratedFiles returns a list of all automatically generated files in the repo. These include
// docs, deep_copy, and conversions
//
// It would be 'better' to call this for every commit but that takes
// a whole lot of time for almost always the same information, and if
// our results are slightly wrong, who cares? Instead look for the
// generated files once and if someone changed what files are generated
// we'll size slightly wrong. No biggie.
func (s *SizeMunger) getGeneratedFiles(obj *github.MungeObject) {
if s.genFilePaths != nil {
return
}
if s.genFilePrefixes != nil {
return
}
if s.genFileNames != nil {
return
}
if s.genPathPrefixes != nil {
return
}
// Don't write into s yet, since this might fail, and these are indicators
// to not repeat this function.
paths := sets.NewString()
filePrefixes := sets.NewString()
fileNames := sets.NewString()
pathPrefixes := sets.NewString()
file := s.GeneratedFilesFile
if len(file) == 0 {
glog.Infof("No --generated-files-config= supplied, applying no labels")
return
}
contents, err := obj.GetFileContents(file, "")
if err != nil {
glog.Errorf("Failed to read generated-files-config %q: %v", file, err)
}
lines := strings.Split(contents, "\n")
for i, line := range lines {
line := strings.TrimSpace(line)
if strings.HasPrefix(line, "#") || line == "" {
continue
}
fields := strings.Fields(line)
if len(fields) != 2 {
glog.Errorf("Invalid line %d in generated docs config %s: %q", i, file, line)
continue
}
key := fields[0]
val := fields[1]
if key == "prefix" || key == "path-prefix" {
pathPrefixes.Insert(val)
} else if key == "file-prefix" {
filePrefixes.Insert(val)
} else if key == "file-name" {
fileNames.Insert(val)
} else if key == "path" {
paths.Insert(val)
} else if key == "paths-from-repo" {
docs, err := obj.GetFileContents(val, "")
if err != nil {
continue
}
docSlice := strings.Split(docs, "\n")
paths.Insert(docSlice...)
} else {
glog.Errorf("Invalid line %d in generated docs config, unknown key: %s, %q", i, key, line)
continue
}
}
// Save the results so we don't repeat this function.
s.genFilePaths = paths
s.genFilePrefixes = filePrefixes
s.genFileNames = fileNames
s.genPathPrefixes = pathPrefixes
return
}
// Munge is the workhorse the will actually make updates to the PR
func (s *SizeMunger) Munge(obj *github.MungeObject) {
if !obj.IsPR() {
return
}
issue := obj.Issue
s.getGeneratedFiles(obj)
files, err := obj.ListFiles()
if err != nil {
return
}
adds := 0
dels := 0
for _, f := range files {
skip := false
for p := range s.genPathPrefixes {
if strings.HasPrefix(*f.Filename, p) {
skip = true
break
}
}
if skip {
continue
}
if s.genFilePaths.Has(*f.Filename) {
continue
}
_, filename := path.Split(*f.Filename)
if hasPrefix(filename, s.genFilePrefixes) {
continue
}
if s.genFileNames.Has(filename) {
continue
}
if f.Additions != nil {
adds += *f.Additions
}
if f.Deletions != nil {
dels += *f.Deletions
}
}
newSize := calculateSize(adds, dels)
newLabel := labelSizePrefix + newSize
existing := github.GetLabelsWithPrefix(issue.Labels, labelSizePrefix)
needsUpdate := true
for _, l := range existing {
if l == newLabel {
needsUpdate = false
continue
}
obj.RemoveLabel(l)
}
if needsUpdate {
obj.AddLabels([]string{newLabel})
body := fmt.Sprintf("Labelling this PR as %s", newLabel)
obj.WriteComment(body)
}
}
func hasPrefix(filename string, filePrefixes sets.String) bool {
for pfx := range filePrefixes {
if strings.HasPrefix(filename, pfx) {
return true
}
}
return false
}
const (
sizeXS = "XS"
sizeS = "S"
sizeM = "M"
sizeL = "L"
sizeXL = "XL"
sizeXXL = "XXL"
)
func calculateSize(adds, dels int) string {
lines := adds + dels
// This is a totally arbitrary heuristic and is open for tweaking.
if lines < 10 {
return sizeXS
}
if lines < 30 {
return sizeS
}
if lines < 100 {
return sizeM
}
if lines < 500 {
return sizeL
}
if lines < 1000 {
return sizeXL
}
return sizeXXL
}
func (s *SizeMunger) isStaleComment(obj *github.MungeObject, comment *githubapi.IssueComment) bool {
if !mergeBotComment(comment) {
return false
}
stale := sizeRE.MatchString(*comment.Body)
if stale {
glog.V(6).Infof("Found stale SizeMunger comment")
}
return stale
}
// StaleComments returns a slice of stale comments
func (s *SizeMunger) StaleComments(obj *github.MungeObject, comments []*githubapi.IssueComment) []*githubapi.IssueComment {
return forEachCommentTest(obj, comments, s.isStaleComment)
}