forked from kubernetes-retired/contrib
-
Notifications
You must be signed in to change notification settings - Fork 1
/
close-stale-pr.go
331 lines (275 loc) · 8.72 KB
/
close-stale-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
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/*
Copyright 2016 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"
"regexp"
"time"
"k8s.io/contrib/mungegithub/features"
"k8s.io/contrib/mungegithub/github"
"k8s.io/contrib/mungegithub/mungers/mungerutil"
"github.com/golang/glog"
githubapi "github.com/google/go-github/github"
"github.com/spf13/cobra"
)
const (
day = time.Hour * 24
keepOpenLabel = "keep-open"
stalePullRequest = 90 * day // Close the PR if no human interaction for `stalePullRequest`
startWarning = 60 * day
remindWarning = 30 * day
closingComment = `This PR hasn't been active in %s. Closing this PR. Please reopen if you would like to work towards merging this change, if/when the PR is ready for the next round of review.
%s
You can add 'keep-open' label to prevent this from happening again, or add a comment to keep it open another 90 days`
warningComment = `This PR hasn't been active in %s. It will be closed in %s (%s).
%s
You can add 'keep-open' label to prevent this from happening, or add a comment to keep it open another 90 days`
)
var (
closingCommentRE = regexp.MustCompile(`This PR hasn't been active in \d+ days?\..*label to prevent this from happening again`)
warningCommentRE = regexp.MustCompile(`This PR hasn't been active in \d+ days?\..*be closed in \d+ days?`)
)
// CloseStalePR will ask the Bot to close any PullRequest that didn't
// have any human interactions in `stalePullRequest` duration.
//
// This is done by checking both review and issue comments, and by
// ignoring comments done with a bot name. We also consider re-open on the PR.
type CloseStalePR struct{}
func init() {
s := CloseStalePR{}
RegisterMungerOrDie(s)
RegisterStaleComments(s)
}
// Name is the name usable in --pr-mungers
func (CloseStalePR) Name() string { return "close-stale-pr" }
// RequiredFeatures is a slice of 'features' that must be provided
func (CloseStalePR) RequiredFeatures() []string { return []string{} }
// Initialize will initialize the munger
func (CloseStalePR) Initialize(config *github.Config, features *features.Features) error {
return nil
}
// EachLoop is called at the start of every munge loop
func (CloseStalePR) EachLoop() error { return nil }
// AddFlags will add any request flags to the cobra `cmd`
func (CloseStalePR) AddFlags(cmd *cobra.Command, config *github.Config) {}
func findLastHumanPullRequestUpdate(obj *github.MungeObject) (*time.Time, error) {
pr, err := obj.GetPR()
if err != nil {
return nil, err
}
comments, err := obj.ListReviewComments()
if err != nil {
return nil, err
}
lastHuman := pr.CreatedAt
for i := range comments {
comment := comments[i]
if comment.User == nil || comment.User.Login == nil || comment.CreatedAt == nil || comment.Body == nil {
continue
}
if *comment.User.Login == botName || *comment.User.Login == jenkinsBotName {
continue
}
if lastHuman.Before(*comment.UpdatedAt) {
lastHuman = comment.UpdatedAt
}
}
return lastHuman, nil
}
func findLastHumanIssueUpdate(obj *github.MungeObject) (*time.Time, error) {
lastHuman := obj.Issue.CreatedAt
comments, err := obj.ListComments()
if err != nil {
return nil, err
}
for i := range comments {
comment := comments[i]
if !validComment(comment) {
continue
}
if mergeBotComment(comment) || jenkinsBotComment(comment) {
continue
}
if lastHuman.Before(*comment.UpdatedAt) {
lastHuman = comment.UpdatedAt
}
}
return lastHuman, nil
}
func findLastInterestingEventUpdate(obj *github.MungeObject) (*time.Time, error) {
lastInteresting := obj.Issue.CreatedAt
events, err := obj.GetEvents()
if err != nil {
return nil, err
}
for i := range events {
event := events[i]
if event.Event == nil || *event.Event != "reopened" {
continue
}
if lastInteresting.Before(*event.CreatedAt) {
lastInteresting = event.CreatedAt
}
}
return lastInteresting, nil
}
func findLastModificationTime(obj *github.MungeObject) (*time.Time, error) {
lastHumanIssue, err := findLastHumanIssueUpdate(obj)
if err != nil {
return nil, err
}
lastHumanPR, err := findLastHumanPullRequestUpdate(obj)
if err != nil {
return nil, err
}
lastInterestingEvent, err := findLastInterestingEventUpdate(obj)
if err != nil {
return nil, err
}
lastModif := lastHumanPR
if lastHumanIssue.After(*lastModif) {
lastModif = lastHumanIssue
}
if lastInterestingEvent.After(*lastModif) {
lastModif = lastInterestingEvent
}
return lastModif, nil
}
// Find the last warning comment that the bot has posted.
// It can return an empty comment if it fails to find one, even if there are no errors.
func findLatestWarningComment(obj *github.MungeObject) (*githubapi.IssueComment, error) {
var lastFoundComment *githubapi.IssueComment
comments, err := obj.ListComments()
if err != nil {
return nil, err
}
for i := range comments {
comment := comments[i]
if !validComment(comment) {
continue
}
if !mergeBotComment(comment) {
continue
}
if !warningCommentRE.MatchString(*comment.Body) {
continue
}
if lastFoundComment == nil || lastFoundComment.CreatedAt.Before(*comment.UpdatedAt) {
if lastFoundComment != nil {
obj.DeleteComment(lastFoundComment)
}
lastFoundComment = comment
}
}
return lastFoundComment, nil
}
func durationToDays(duration time.Duration) string {
days := duration / day
dayString := "days"
if days == 1 || days == -1 {
dayString = "day"
}
return fmt.Sprintf("%d %s", days, dayString)
}
func closePullRequest(obj *github.MungeObject, inactiveFor time.Duration) {
mention := mungerutil.GetIssueUsers(obj.Issue).AllUsers().Mention().Join()
if mention != "" {
mention = "cc " + mention + "\n"
}
comment, err := findLatestWarningComment(obj)
if err != nil {
glog.Error("Failed to findLatestWarningComment: ", err)
return
}
if comment != nil {
obj.DeleteComment(comment)
}
obj.WriteComment(fmt.Sprintf(closingComment, durationToDays(inactiveFor), mention))
obj.ClosePR()
}
func postWarningComment(obj *github.MungeObject, inactiveFor time.Duration, closeIn time.Duration) {
mention := mungerutil.GetIssueUsers(obj.Issue).AllUsers().Mention().Join()
if mention != "" {
mention = "cc " + mention + "\n"
}
closeDate := time.Now().Add(closeIn).Format("Jan 2, 2006")
obj.WriteComment(fmt.Sprintf(
warningComment,
durationToDays(inactiveFor),
durationToDays(closeIn),
closeDate,
mention,
))
}
func checkAndWarn(obj *github.MungeObject, inactiveFor time.Duration, closeIn time.Duration) {
if closeIn < day {
// We are going to close the PR in less than a day. Too late to warn
return
}
comment, err := findLatestWarningComment(obj)
if err != nil {
glog.Error("Failed to findLatestWarningComment: ", err)
return
}
if comment == nil {
// We don't already have the comment. Post it
postWarningComment(obj, inactiveFor, closeIn)
} else if time.Since(*comment.UpdatedAt) > remindWarning {
// It's time to warn again
obj.DeleteComment(comment)
postWarningComment(obj, inactiveFor, closeIn)
} else {
// We already have a warning, and it's not expired. Do nothing
}
}
// Munge is the workhorse that will actually close the PRs
func (CloseStalePR) Munge(obj *github.MungeObject) {
if !obj.IsPR() {
return
}
if obj.HasLabel(keepOpenLabel) {
return
}
lastModif, err := findLastModificationTime(obj)
if err != nil {
glog.Errorf("Failed to find last modification: %v", err)
return
}
closeIn := -time.Since(lastModif.Add(stalePullRequest))
inactiveFor := time.Since(*lastModif)
if closeIn <= 0 {
closePullRequest(obj, inactiveFor)
} else if closeIn <= startWarning {
checkAndWarn(obj, inactiveFor, closeIn)
} else {
// Pull-request is active. Remove previous potential warning
// Ignore potential errors, we just want to remove old comments ...
comment, _ := findLatestWarningComment(obj)
if comment != nil {
obj.DeleteComment(comment)
}
}
}
func (CloseStalePR) isStaleComment(obj *github.MungeObject, comment *githubapi.IssueComment) bool {
if !mergeBotComment(comment) {
return false
}
if !closingCommentRE.MatchString(*comment.Body) {
return false
}
return true
}
// StaleComments returns a slice of stale comments
func (s CloseStalePR) StaleComments(obj *github.MungeObject, comments []*githubapi.IssueComment) []*githubapi.IssueComment {
return forEachCommentTest(obj, comments, s.isStaleComment)
}