-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathgopherbot.go
1888 lines (1766 loc) · 55.5 KB
/
gopherbot.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The gopherbot command runs Go's gopherbot role account on
// GitHub and Gerrit.
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode"
"cloud.google.com/go/compute/metadata"
"github.com/google/go-github/github"
"go4.org/strutil"
"golang.org/x/build/devapp/owners"
"golang.org/x/build/gerrit"
"golang.org/x/build/maintner"
"golang.org/x/build/maintner/godata"
"golang.org/x/oauth2"
)
var (
dryRun = flag.Bool("dry-run", false, "just report what would've been done, without changing anything")
daemon = flag.Bool("daemon", false, "run in daemon mode")
githubTokenFile = flag.String("github-token-file", filepath.Join(os.Getenv("HOME"), "keys", "github-gobot"), `File to load Github token from. File should be of form <username>:<token>`)
// go here: https://go-review.googlesource.com/settings#HTTPCredentials
// click "Obtain Password"
// The next page will have a .gitcookies file - look for the part that has
// "git-youremail@yourcompany.com=password". Copy and paste that to the
// token file with a colon in between the email and password.
gerritTokenFile = flag.String("gerrit-token-file", filepath.Join(os.Getenv("HOME"), "keys", "gerrit-gobot"), `File to load Gerrit token from. File should be of form <git-email>:<token>`)
onlyRun = flag.String("only-run", "", "if non-empty, the name of a task to run. Mostly for debugging, but tasks (like 'kicktrain') may choose to only run in explicit mode")
)
// GitHub Label IDs for the golang/go repo.
const (
needsDecisionID = 373401956
needsFixID = 373399998
needsInvestigationID = 373402289
)
// Label names (that are used in multiple places).
const (
frozenDueToAge = "FrozenDueToAge"
)
// GitHub Milestone numbers for the golang/go repo.
var (
proposal = milestone{30, "Proposal"}
unreleased = milestone{22, "Unreleased"}
unplanned = milestone{6, "Unplanned"}
gccgo = milestone{23, "Gccgo"}
vgo = milestone{71, "vgo"}
)
type milestone struct {
Number int
Name string
}
func getGithubToken() (string, error) {
if metadata.OnGCE() {
for _, key := range []string{"gopherbot-github-token", "maintner-github-token"} {
token, err := metadata.ProjectAttributeValue(key)
if token != "" && err == nil {
return token, nil
}
}
}
slurp, err := ioutil.ReadFile(*githubTokenFile)
if err != nil {
return "", err
}
f := strings.SplitN(strings.TrimSpace(string(slurp)), ":", 2)
if len(f) != 2 || f[0] == "" || f[1] == "" {
return "", fmt.Errorf("Expected token %q to be of form <username>:<token>", slurp)
}
return f[1], nil
}
func getGerritAuth() (username string, password string, err error) {
var slurp string
if metadata.OnGCE() {
for _, key := range []string{"gopherbot-gerrit-token", "maintner-gerrit-token", "gobot-password"} {
slurp, err = metadata.ProjectAttributeValue(key)
if slurp != "" && err == nil {
break
}
}
}
if len(slurp) == 0 {
var slurpBytes []byte
slurpBytes, err = ioutil.ReadFile(*gerritTokenFile)
if err != nil {
return "", "", err
}
slurp = string(slurpBytes)
}
f := strings.SplitN(strings.TrimSpace(slurp), ":", 2)
if len(f) == 1 {
// assume the whole thing is the token
return "git-gobot.golang.org", f[0], nil
}
if len(f) != 2 || f[0] == "" || f[1] == "" {
return "", "", fmt.Errorf("Expected Gerrit token %q to be of form <git-email>:<token>", slurp)
}
return f[0], f[1], nil
}
func getGithubClient() (*github.Client, error) {
token, err := getGithubToken()
if err != nil {
if *dryRun {
return github.NewClient(http.DefaultClient), nil
}
return nil, err
}
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
tc := oauth2.NewClient(context.Background(), ts)
return github.NewClient(tc), nil
}
func getGerritClient() (*gerrit.Client, error) {
username, token, err := getGerritAuth()
if err != nil {
if *dryRun {
c := gerrit.NewClient("https://go-review.googlesource.com", gerrit.NoAuth)
return c, nil
}
return nil, err
}
c := gerrit.NewClient("https://go-review.googlesource.com", gerrit.BasicAuth(username, token))
return c, nil
}
func init() {
flag.Usage = func() {
os.Stderr.WriteString("gopherbot runs Go's gopherbot role account on GitHub and Gerrit.\n\n")
flag.PrintDefaults()
}
}
type gerritChange struct {
project string
num int32
}
func (c gerritChange) ID() string {
// https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#change-id
return fmt.Sprintf("%s~%d", c.project, c.num)
}
func (c gerritChange) String() string {
return c.ID()
}
func main() {
flag.Parse()
ghc, err := getGithubClient()
if err != nil {
log.Fatal(err)
}
gerritc, err := getGerritClient()
if err != nil {
log.Fatal(err)
}
bot := &gopherbot{
ghc: ghc,
gerrit: gerritc,
deletedChanges: map[gerritChange]bool{
{"crypto", 35958}: true,
},
}
bot.initCorpus()
ctx := context.Background()
for {
t0 := time.Now()
err := bot.doTasks(ctx)
if err != nil {
log.Print(err)
}
botDur := time.Since(t0)
log.Printf("gopherbot ran in %v", botDur)
if !*daemon {
if err != nil {
os.Exit(1)
}
return
}
if err != nil {
log.Printf("sleeping 30s after previous error.")
time.Sleep(30 * time.Second)
}
for {
t0 := time.Now()
err := bot.corpus.Update(ctx)
if err != nil {
if err == maintner.ErrSplit {
log.Print("Corpus out of sync. Re-fetching corpus.")
bot.initCorpus()
} else {
log.Printf("corpus.Update: %v; sleeping 15s", err)
time.Sleep(15 * time.Second)
continue
}
}
log.Printf("got corpus update after %v", time.Since(t0))
break
}
lastTask = ""
}
}
type gopherbot struct {
ghc *github.Client
gerrit *gerrit.Client
corpus *maintner.Corpus
gorepo *maintner.GitHubRepo
knownContributors map[string]bool
// Until golang.org/issue/22635 is fixed, keep a map of changes that were deleted
// to prevent calls to Gerrit that will always 404.
deletedChanges map[gerritChange]bool
releases struct {
sync.Mutex
lastUpdate time.Time
major []string // last two releases and the next upcoming release, like: "1.9", "1.10", "1.11"
}
}
var tasks = []struct {
name string
fn func(*gopherbot, context.Context) error
}{
{"kicktrain", (*gopherbot).getOffKickTrain},
{"unwait-release", (*gopherbot).unwaitRelease},
{"freeze old issues", (*gopherbot).freezeOldIssues},
{"label proposals", (*gopherbot).labelProposals},
{"set subrepo milestones", (*gopherbot).setSubrepoMilestones},
{"set misc milestones", (*gopherbot).setMiscMilestones},
{"label build issues", (*gopherbot).labelBuildIssues},
{"label mobile issues", (*gopherbot).labelMobileIssues},
{"label documentation issues", (*gopherbot).labelDocumentationIssues},
{"close stale WaitingForInfo", (*gopherbot).closeStaleWaitingForInfo},
{"cl2issue", (*gopherbot).cl2issue},
{"update needs", (*gopherbot).updateNeeds},
{"congratulate new contributors", (*gopherbot).congratulateNewContributors},
{"un-wait CLs", (*gopherbot).unwaitCLs},
{"open cherry pick issues", (*gopherbot).openCherryPickIssues},
{"apply minor release milestones", (*gopherbot).setMinorMilestones},
{"close cherry pick issues", (*gopherbot).closeCherryPickIssues},
{"apply labels from comments", (*gopherbot).applyLabelsFromComments},
{"assign reviewers to CLs", (*gopherbot).assignReviewersToCLs},
}
func (b *gopherbot) initCorpus() {
ctx := context.Background()
corpus, err := godata.Get(ctx)
if err != nil {
log.Fatalf("godata.Get: %v", err)
}
repo := corpus.GitHub().Repo("golang", "go")
if repo == nil {
log.Fatal("Failed to find Go repo in Corpus.")
}
b.corpus = corpus
b.gorepo = repo
}
func (b *gopherbot) doTasks(ctx context.Context) error {
for _, task := range tasks {
if *onlyRun != "" && task.name != *onlyRun {
continue
}
if err := task.fn(b, ctx); err != nil {
log.Printf("%s: %v", task.name, err)
return err
}
}
return nil
}
func (b *gopherbot) addLabel(ctx context.Context, gi *maintner.GitHubIssue, label string) error {
return b.addLabels(ctx, gi, []string{label})
}
func (b *gopherbot) addLabels(ctx context.Context, gi *maintner.GitHubIssue, labels []string) error {
var toAdd []string
for _, label := range labels {
if gi.HasLabel(label) {
log.Printf("Issue %d already has label %q; no need to send request to add it", gi.Number, label)
continue
}
printIssue("label-"+label, gi)
toAdd = append(toAdd, label)
}
if *dryRun || len(toAdd) == 0 {
return nil
}
return addLabelsToIssue(ctx, b.ghc.Issues, int(gi.Number), toAdd)
}
// addLabelsToIssue adds labels to the issue in golang/go with the given issueNum.
// TODO: Proper stubs via interfaces.
var addLabelsToIssue = func(ctx context.Context, issues *github.IssuesService, issueNum int, labels []string) error {
_, _, err := issues.AddLabelsToIssue(ctx, "golang", "go", issueNum, labels)
return err
}
// removeLabel removes the label from the given issue in golang/go.
func (b *gopherbot) removeLabel(ctx context.Context, gi *maintner.GitHubIssue, label string) error {
return b.removeLabels(ctx, gi, []string{label})
}
func (b *gopherbot) removeLabels(ctx context.Context, gi *maintner.GitHubIssue, labels []string) error {
var removeLabels bool
for _, l := range labels {
if !gi.HasLabel(l) {
log.Printf("Issue %d (in maintner) does not have label %q; no need to send request to remove it", gi.Number, l)
continue
}
printIssue("label-"+l, gi)
removeLabels = true
}
if *dryRun || !removeLabels {
return nil
}
ghLabels, err := labelsForIssue(ctx, b.ghc.Issues, int(gi.Number))
if err != nil {
return err
}
toRemove := make(map[string]bool)
for _, l := range labels {
toRemove[l] = true
}
for _, l := range ghLabels {
if toRemove[l] {
if err := removeLabelFromIssue(ctx, b.ghc.Issues, int(gi.Number), l); err != nil {
log.Printf("Could not remove label %q from issue %d: %v", l, gi.Number, err)
continue
}
}
}
return nil
}
// labelsForIssue returns all labels for the given issue in the golang/go repo.
// TODO: Proper stubs via interfaces.
var labelsForIssue = func(ctx context.Context, issues *github.IssuesService, issueNum int) ([]string, error) {
ghLabels, _, err := issues.ListLabelsByIssue(ctx, "golang", "go", issueNum, &github.ListOptions{PerPage: 100})
if err != nil {
return nil, fmt.Errorf("could not list labels for golang/go#%d: %v", issueNum, err)
}
var labels []string
for _, l := range ghLabels {
labels = append(labels, l.GetName())
}
return labels, nil
}
// removeLabelForIssue removes the given label from golang/go with the given issueNum.
// If the issue did not have the label already (or the label didn't exist), return nil.
// TODO: Proper stubs via interfaces.
var removeLabelFromIssue = func(ctx context.Context, issues *github.IssuesService, issueNum int, label string) error {
_, err := issues.RemoveLabelForIssue(ctx, "golang", "go", issueNum, label)
if ge, ok := err.(*github.ErrorResponse); ok && ge.Response != nil && ge.Response.StatusCode == http.StatusNotFound {
return nil
}
return err
}
func (b *gopherbot) setMilestone(ctx context.Context, gi *maintner.GitHubIssue, m milestone) error {
printIssue("milestone-"+m.Name, gi)
if *dryRun {
return nil
}
_, _, err := b.ghc.Issues.Edit(ctx, "golang", "go", int(gi.Number), &github.IssueRequest{
Milestone: github.Int(m.Number),
})
return err
}
func (b *gopherbot) addGitHubComment(ctx context.Context, org, repo string, issueNum int32, msg string) error {
gr := b.corpus.GitHub().Repo(org, repo)
if gr == nil {
return fmt.Errorf("unknown github repo %s/%s", org, repo)
}
var since time.Time
if gi := gr.Issue(issueNum); gi != nil {
dup := false
gi.ForeachComment(func(c *maintner.GitHubComment) error {
since = c.Updated
// TODO: check for gopherbot as author? check for exact match?
// This seems fine for now.
if strings.Contains(c.Body, msg) {
dup = true
return errStopIteration
}
return nil
})
if dup {
// Comment's already been posted. Nothing to do.
return nil
}
}
// See if there is a dup comment from when gopherbot last got
// its data from maintner.
ics, _, err := b.ghc.Issues.ListComments(ctx, org, repo, int(issueNum), &github.IssueListCommentsOptions{
Since: since,
ListOptions: github.ListOptions{PerPage: 1000},
})
if err != nil {
return err
}
for _, ic := range ics {
if strings.Contains(ic.GetBody(), msg) {
// Dup.
return nil
}
}
if *dryRun {
log.Printf("[dry-run] would add comment to github.com/%s/%s/issues/%d: %v", org, repo, issueNum, msg)
return nil
}
_, _, err = b.ghc.Issues.CreateComment(ctx, org, repo, int(issueNum), &github.IssueComment{
Body: github.String(msg),
})
return err
}
// createGitHubIssue returns the number of the created issue, or 4242 in dry-run mode.
// baseEvent is the timestamp of the event causing this action, and is used for de-duplication.
func (b *gopherbot) createGitHubIssue(ctx context.Context, title, msg string, labels []string, baseEvent time.Time) (int, error) {
var dup int
b.gorepo.ForeachIssue(func(gi *maintner.GitHubIssue) error {
// TODO: check for gopherbot as author? check for exact match?
// This seems fine for now.
if gi.Title == title {
dup = int(gi.Number)
return errStopIteration
}
return nil
})
if dup != 0 {
// Issue's already been posted. Nothing to do.
return dup, nil
}
// See if there is a dup issue from when gopherbot last got its data from maintner.
is, _, err := b.ghc.Issues.ListByRepo(ctx, "golang", "go", &github.IssueListByRepoOptions{
State: "all",
ListOptions: github.ListOptions{PerPage: 100},
Since: baseEvent,
})
if err != nil {
return 0, err
}
for _, i := range is {
if i.GetTitle() == title {
// Dup.
return i.GetNumber(), nil
}
}
if *dryRun {
log.Printf("[dry-run] would create issue with title %s and labels %v\n%s", title, labels, msg)
return 4242, nil
}
i, _, err := b.ghc.Issues.Create(ctx, "golang", "go", &github.IssueRequest{
Title: github.String(title),
Body: github.String(msg),
Labels: &labels,
})
return i.GetNumber(), err
}
func (b *gopherbot) closeGitHubIssue(ctx context.Context, number int32) error {
if *dryRun {
log.Printf("[dry-run] would close golang.org/issue/%v", number)
return nil
}
_, _, err := b.ghc.Issues.Edit(ctx, "golang", "go", int(number), &github.IssueRequest{State: github.String("closed")})
return err
}
type gerritCommentOpts struct {
OldPhrases []string
Version string // if empty, latest version is used
}
var emptyGerritCommentOpts gerritCommentOpts
// addGerritComment adds the given comment to the CL specified by the changeID
// and the patch set identified by the version.
//
// As an idempotence check, before adding the comment the comment and the list
// of oldPhrases are checked against the CL to ensure that no phrase in the list
// has already been added to the list as a comment.
func (b *gopherbot) addGerritComment(ctx context.Context, changeID, comment string, opts *gerritCommentOpts) error {
if b == nil {
panic("nil gopherbot")
}
if *dryRun {
log.Printf("[dry-run] would add comment to golang.org/cl/%s: %v", changeID, comment)
return nil
}
if opts == nil {
opts = &emptyGerritCommentOpts
}
// One final staleness check before sending a message: get the list
// of comments from the API and check whether any of them match.
info, err := b.gerrit.GetChange(ctx, changeID, gerrit.QueryChangesOpt{
Fields: []string{"MESSAGES", "CURRENT_REVISION"},
})
if err != nil {
return err
}
for _, msg := range info.Messages {
if strings.Contains(msg.Message, comment) {
return nil // Our comment is already there
}
for j := range opts.OldPhrases {
// Message looks something like "Patch set X:\n\n(our text)"
if strings.Contains(msg.Message, opts.OldPhrases[j]) {
return nil // Our comment is already there
}
}
}
var rev string
if opts.Version != "" {
rev = opts.Version
} else {
rev = info.CurrentRevision
}
return b.gerrit.SetReview(ctx, changeID, rev, gerrit.ReviewInput{
Message: comment,
})
}
// Move any issue to "Unplanned" if it looks like it keeps getting kicked along between releases.
func (b *gopherbot) getOffKickTrain(ctx context.Context) error {
// We only run this task if it was explicitly requested via
// the --only-run flag.
if *onlyRun == "" {
return nil
}
type match struct {
url string
title string
gi *maintner.GitHubIssue
}
var matches []match
b.gorepo.ForeachIssue(func(gi *maintner.GitHubIssue) error {
if gi.PullRequest || gi.Closed || gi.NotExist {
return nil
}
curMilestone := gi.Milestone.Title
if !strings.HasPrefix(curMilestone, "Go1.") || strings.Count(curMilestone, ".") != 1 {
return nil
}
if gi.HasLabel("release-blocker") || gi.HasLabel("Security") {
return nil
}
if len(gi.Assignees) > 0 {
return nil
}
was := map[string]bool{}
gi.ForeachEvent(func(e *maintner.GitHubIssueEvent) error {
if e.Type == "milestoned" {
switch e.Milestone {
case "Unreleased", "Unplanned", "Proposal":
return nil
}
if strings.Count(e.Milestone, ".") > 1 {
return nil
}
ms := strings.TrimSuffix(e.Milestone, "Maybe")
ms = strings.TrimSuffix(ms, "Early")
was[ms] = true
}
return nil
})
if len(was) > 2 {
var mss []string
for ms := range was {
mss = append(mss, ms)
}
sort.Slice(mss, func(i, j int) bool {
if len(mss[i]) == len(mss[j]) {
return mss[i] < mss[j]
}
return len(mss[i]) < len(mss[j])
})
matches = append(matches, match{
url: fmt.Sprintf("https://golang.org/issue/%d", gi.Number),
title: fmt.Sprintf("%s - %v", gi.Title, mss),
gi: gi,
})
}
return nil
})
sort.Slice(matches, func(i, j int) bool {
return matches[i].title < matches[j].title
})
fmt.Printf("%d issues:\n", len(matches))
for _, m := range matches {
fmt.Printf("%-30s - %s\n", m.url, m.title)
if !*dryRun {
if err := b.setMilestone(ctx, m.gi, unplanned); err != nil {
return err
}
}
}
return nil
}
// unwaitRelease changes any Gerrit CL with hashtag "wait-release"
// into "ex-wait-release". This is run manually (with --only-run)
// at the opening of a release cycle.
func (b *gopherbot) unwaitRelease(ctx context.Context) error {
// We only run this task if it was explicitly requested via
// the --only-run flag.
if *onlyRun == "" {
return nil
}
cis, err := b.gerrit.QueryChanges(ctx, "hashtag:wait-release status:open")
if err != nil {
return nil
}
for _, ci := range cis {
if *dryRun {
log.Printf("[dry run] would remove hashtag 'wait-release' from CL %d", ci.ChangeNumber)
continue
}
_, err := b.gerrit.SetHashtags(ctx, ci.ID, gerrit.HashtagsInput{
Add: []string{"ex-wait-release"},
Remove: []string{"wait-release"},
})
if err != nil {
log.Printf("https://golang.org/cl/%d: modifying hash tags: %v", ci.ChangeNumber, err)
return err
}
log.Printf("https://golang.org/cl/%d: removed wait-release", ci.ChangeNumber)
}
return nil
}
// freezeOldIssues locks any issue that's old and closed.
// (Otherwise people find ancient bugs via searches and start asking questions
// into a void and it's sad for everybody.)
// This method doesn't need to explicitly avoid edit wars with humans because
// it bails out if the issue was edited recently. A human unlocking an issue
// causes the updated time to bump, which means the bot wouldn't try to lock it
// again for another year.
func (b *gopherbot) freezeOldIssues(ctx context.Context) error {
tooOld := time.Now().Add(-365 * 24 * time.Hour)
return b.gorepo.ForeachIssue(func(gi *maintner.GitHubIssue) error {
if !gi.Closed || gi.PullRequest || gi.Locked {
return nil
}
if gi.Updated.After(tooOld) {
return nil
}
printIssue("freeze", gi)
if *dryRun {
return nil
}
_, err := b.ghc.Issues.Lock(ctx, "golang", "go", int(gi.Number), nil)
if err != nil {
return err
}
return b.addLabel(ctx, gi, frozenDueToAge)
})
}
// labelProposals adds the "Proposal" label and "Proposal" milestone
// to open issues with title beginning with "Proposal:". It tries not
// to get into an edit war with a human.
func (b *gopherbot) labelProposals(ctx context.Context) error {
return b.gorepo.ForeachIssue(func(gi *maintner.GitHubIssue) error {
if gi.Closed || gi.PullRequest {
return nil
}
if !strings.HasPrefix(gi.Title, "proposal:") && !strings.HasPrefix(gi.Title, "Proposal:") {
return nil
}
// Add Milestone if missing:
if gi.Milestone.IsNone() && !gi.HasEvent("milestoned") && !gi.HasEvent("demilestoned") {
if err := b.setMilestone(ctx, gi, proposal); err != nil {
return err
}
}
// Add Proposal label if missing:
if !gi.HasLabel("Proposal") && !gi.HasEvent("unlabeled") {
if err := b.addLabel(ctx, gi, "Proposal"); err != nil {
return err
}
}
return nil
})
}
func (b *gopherbot) setSubrepoMilestones(ctx context.Context) error {
return b.gorepo.ForeachIssue(func(gi *maintner.GitHubIssue) error {
if gi.Closed || gi.PullRequest || !gi.Milestone.IsNone() || gi.HasEvent("demilestoned") || gi.HasEvent("milestoned") {
return nil
}
if !strings.HasPrefix(gi.Title, "x/") {
return nil
}
pkg := gi.Title
if colon := strings.IndexByte(pkg, ':'); colon >= 0 {
pkg = pkg[:colon]
}
if sp := strings.IndexByte(pkg, ' '); sp >= 0 {
pkg = pkg[:sp]
}
switch pkg {
case "",
"x/arch",
"x/crypto/chacha20poly1305",
"x/crypto/curve25519",
"x/crypto/poly1305",
"x/net/http2",
"x/net/idna",
"x/net/lif",
"x/net/proxy",
"x/net/route",
"x/text/unicode/norm",
"x/text/width":
// These get vendored in. Don't mess with them.
return nil
case "x/vgo":
// Handled by setMiscMilestones
return nil
}
return b.setMilestone(ctx, gi, unreleased)
})
}
func (b *gopherbot) setMiscMilestones(ctx context.Context) error {
return b.gorepo.ForeachIssue(func(gi *maintner.GitHubIssue) error {
if gi.Closed || gi.PullRequest || !gi.Milestone.IsNone() || gi.HasEvent("demilestoned") || gi.HasEvent("milestoned") {
return nil
}
if strings.Contains(gi.Title, "gccgo") { // TODO: better gccgo bug report heuristic?
return b.setMilestone(ctx, gi, gccgo)
}
if strings.HasPrefix(gi.Title, "x/vgo") {
return b.setMilestone(ctx, gi, vgo)
}
return nil
})
}
func (b *gopherbot) labelBuildIssues(ctx context.Context) error {
return b.gorepo.ForeachIssue(func(gi *maintner.GitHubIssue) error {
if gi.Closed || gi.PullRequest || !strings.HasPrefix(gi.Title, "x/build") || gi.HasLabel("Builders") || gi.HasEvent("unlabeled") {
return nil
}
return b.addLabel(ctx, gi, "Builders")
})
}
func (b *gopherbot) labelMobileIssues(ctx context.Context) error {
return b.gorepo.ForeachIssue(func(gi *maintner.GitHubIssue) error {
if gi.Closed || gi.PullRequest || !strings.HasPrefix(gi.Title, "x/mobile") || gi.HasLabel("mobile") || gi.HasEvent("unlabeled") {
return nil
}
return b.addLabel(ctx, gi, "mobile")
})
}
func (b *gopherbot) labelDocumentationIssues(ctx context.Context) error {
return b.gorepo.ForeachIssue(func(gi *maintner.GitHubIssue) error {
if gi.Closed || gi.PullRequest || !isDocumentationTitle(gi.Title) || gi.HasLabel("Documentation") || gi.HasEvent("unlabeled") {
return nil
}
return b.addLabel(ctx, gi, "Documentation")
})
}
func (b *gopherbot) closeStaleWaitingForInfo(ctx context.Context) error {
const waitingForInfo = "WaitingForInfo"
now := time.Now()
return b.gorepo.ForeachIssue(func(gi *maintner.GitHubIssue) error {
if gi.Closed || gi.PullRequest || !gi.HasLabel("WaitingForInfo") {
return nil
}
var waitStart time.Time
gi.ForeachEvent(func(e *maintner.GitHubIssueEvent) error {
if e.Type == "reopened" {
// Ignore any previous WaitingForInfo label if it's reopend.
waitStart = time.Time{}
return nil
}
if e.Label == waitingForInfo {
switch e.Type {
case "unlabeled":
waitStart = time.Time{}
case "labeled":
waitStart = e.Created
}
return nil
}
return nil
})
if waitStart.IsZero() {
return nil
}
deadline := waitStart.AddDate(0, 1, 0) // 1 month
if now.Before(deadline) {
return nil
}
var lastOPComment time.Time
gi.ForeachComment(func(c *maintner.GitHubComment) error {
if c.User.ID == gi.User.ID {
lastOPComment = c.Created
}
return nil
})
if lastOPComment.After(waitStart) {
return nil
}
printIssue("close-stale-waiting-for-info", gi)
// TODO: write a task that reopens issues if the OP speaks up.
if err := b.addGitHubComment(ctx, "golang", "go", gi.Number,
"Timed out in state WaitingForInfo. Closing.\n\n(I am just a bot, though. Please speak up if this is a mistake or you have the requested information.)"); err != nil {
return err
}
return b.closeGitHubIssue(ctx, gi.Number)
})
}
// cl2issue writes "Change https://golang.org/issue/NNNN mentions this issue"\
// and the change summary on GitHub when a new Gerrit change references a GitHub issue.
func (b *gopherbot) cl2issue(ctx context.Context) error {
monthAgo := time.Now().Add(-30 * 24 * time.Hour)
return b.corpus.Gerrit().ForeachProjectUnsorted(func(gp *maintner.GerritProject) error {
if gp.Server() != "go.googlesource.com" {
return nil
}
return gp.ForeachCLUnsorted(func(cl *maintner.GerritCL) error {
if cl.Meta.Commit.AuthorTime.Before(monthAgo) {
// If the CL was last updated over a
// month ago, assume (as an
// optimization) that gopherbot
// already processed this issue.
return nil
}
for _, ref := range cl.GitHubIssueRefs {
if id := ref.Repo.ID(); id.Owner != "golang" || id.Repo != "go" {
continue
}
gi := ref.Repo.Issue(ref.Number)
if gi == nil || gi.PullRequest || gi.HasLabel(frozenDueToAge) {
continue
}
hasComment := false
substr := fmt.Sprintf("%d mentions this issue", cl.Number)
gi.ForeachComment(func(c *maintner.GitHubComment) error {
if strings.Contains(c.Body, substr) {
hasComment = true
return errStopIteration
}
return nil
})
if !hasComment {
printIssue("cl2issue", gi)
msg := fmt.Sprintf("Change https://golang.org/cl/%d mentions this issue: `%s`", cl.Number, cl.Commit.Summary())
if err := b.addGitHubComment(ctx, "golang", "go", gi.Number, msg); err != nil {
return err
}
}
}
return nil
})
})
}
// canonicalLabelName returns "needsfix" for "needs-fix" or "NeedsFix"
// in prep for future label renaming.
func canonicalLabelName(s string) string {
return strings.Replace(strings.ToLower(s), "-", "", -1)
}
// If an issue has multiple "needs" labels, remove all but the most recent.
// These were originally called NeedsFix, NeedsDecision, and NeedsInvestigation,
// but are being renamed to "needs-foo".
func (b *gopherbot) updateNeeds(ctx context.Context) error {
return b.gorepo.ForeachIssue(func(gi *maintner.GitHubIssue) error {
if gi.Closed || gi.PullRequest {
return nil
}
var numNeeds int
if gi.Labels[needsDecisionID] != nil {
numNeeds++
}
if gi.Labels[needsFixID] != nil {
numNeeds++
}
if gi.Labels[needsInvestigationID] != nil {
numNeeds++
}
if numNeeds <= 1 {
return nil
}
labels := map[string]int{} // lowercase no-hyphen "needsfix" -> position
var pos, maxPos int
gi.ForeachEvent(func(e *maintner.GitHubIssueEvent) error {
var add bool
switch e.Type {
case "labeled":
add = true
case "unlabeled":
default:
return nil
}
if !strings.HasPrefix(e.Label, "Needs") && !strings.HasPrefix(e.Label, "needs-") {
return nil
}
key := canonicalLabelName(e.Label)
pos++
if add {
labels[key] = pos
maxPos = pos
} else {
delete(labels, key)
}
return nil
})
if len(labels) <= 1 {
return nil
}
// Remove any label that's not the newest (added in
// last position).
for _, lab := range gi.Labels {
key := canonicalLabelName(lab.Name)
if !strings.HasPrefix(key, "needs") || labels[key] == maxPos {
continue
}
printIssue("updateneeds", gi)
fmt.Printf("\t... removing label %q\n", lab.Name)
if err := b.removeLabel(ctx, gi, lab.Name); err != nil {
return err
}
}
return nil
})
}
// If any of the messages in this array have been posted on a CL, don't post
// again. If you amend the message even slightly, please prepend the new message
// to this list, to avoid re-spamming people.
//
// The first message is the "current" message.
var congratulatoryMessages = []string{
// TODO: provide more helpful info? Amend, don't add 2nd commit, link to a
// review guide?
//
// also TODO: make this a template? May want to provide more dynamic
// information in the future. Would make it tougher to search and see if
// a comment has been previously posted.
`Congratulations on opening your first change. Thank you for your contribution!