-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathgopherbot.go
2880 lines (2687 loc) · 90.7 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.
//
// General documentation is at https://go.dev/wiki/gopherbot.
// Consult the tasks slice in gopherbot.go for an up-to-date
// list of all gopherbot tasks.
package main
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode"
"cloud.google.com/go/compute/metadata"
"github.com/google/go-github/v48/github"
"github.com/shurcooL/githubv4"
"go4.org/strutil"
"golang.org/x/build/devapp/owners"
"golang.org/x/build/gerrit"
"golang.org/x/build/internal/foreach"
"golang.org/x/build/internal/gophers"
"golang.org/x/build/internal/secret"
"golang.org/x/build/maintner"
"golang.org/x/build/maintner/godata"
"golang.org/x/build/maintner/maintnerd/apipb"
"golang.org/x/exp/slices"
"golang.org/x/oauth2"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
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
// "[email protected]=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")
)
func init() {
flag.Usage = func() {
output := flag.CommandLine.Output()
fmt.Fprintf(output, "gopherbot runs Go's gopherbot role account on GitHub and Gerrit.\n\n")
flag.PrintDefaults()
fmt.Fprintln(output, "")
fmt.Fprintln(output, "Tasks (can be used for the --only-run flag):")
for _, t := range tasks {
fmt.Fprintf(output, " %q\n", t.name)
}
}
}
const (
gopherbotGitHubID = 8566911
)
const (
gobotGerritID = "5976"
gerritbotGerritID = "12446"
kokoroGerritID = "37747"
goLUCIGerritID = "60063"
triciumGerritID = "62045"
)
// GitHub Label IDs for the golang/go repo.
const (
needsDecisionID = 373401956
needsFixID = 373399998
needsInvestigationID = 373402289
earlyInCycleID = 626114143
)
// 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"}
vulnUnplanned = milestone{288, "vuln/unplanned"}
)
// GitHub Milestone numbers for the golang/vscode-go repo.
var vscodeUntriaged = milestone{26, "Untriaged"}
type milestone struct {
Number int
Name string
}
func getGitHubToken(ctx context.Context, sc *secret.Client) (string, error) {
if metadata.OnGCE() && sc != nil {
ctxSc, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
token, err := sc.Retrieve(ctxSc, secret.NameMaintnerGitHubToken)
if err == nil && token != "" {
return token, nil
}
}
slurp, err := os.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(ctx context.Context, sc *secret.Client) (username string, password string, err error) {
if metadata.OnGCE() && sc != nil {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
token, err := sc.Retrieve(ctx, secret.NameGobotPassword)
if err != nil {
return "", "", err
}
return "git-gobot.golang.org", token, nil
}
var slurpBytes []byte
slurpBytes, err = os.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 getGitHubClients(ctx context.Context, sc *secret.Client) (*github.Client, *githubv4.Client, error) {
token, err := getGitHubToken(ctx, sc)
if err != nil {
if *dryRun {
// Note: GitHub API v4 requires requests to be authenticated, which isn't implemented here.
return github.NewClient(http.DefaultClient), githubv4.NewClient(http.DefaultClient), nil
}
return nil, nil, err
}
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
tc := oauth2.NewClient(context.Background(), ts)
return github.NewClient(tc), githubv4.NewClient(tc), nil
}
func getGerritClient(ctx context.Context, sc *secret.Client) (*gerrit.Client, error) {
username, token, err := getGerritAuth(ctx, sc)
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 getMaintnerClient(ctx context.Context) (apipb.MaintnerServiceClient, error) {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
mServer := "maintner.golang.org:443"
cc, err := grpc.DialContext(ctx, mServer,
grpc.WithBlock(),
grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{NextProtos: []string{"h2"}})))
if err != nil {
return nil, err
}
return apipb.NewMaintnerServiceClient(cc), nil
}
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()
}
type githubIssue struct {
repo maintner.GitHubRepoID
num int32
}
func main() {
flag.Parse()
var sc *secret.Client
if metadata.OnGCE() {
sc = secret.MustNewClient()
}
ctx := context.Background()
ghV3, ghV4, err := getGitHubClients(ctx, sc)
if err != nil {
log.Fatal(err)
}
gerrit, err := getGerritClient(ctx, sc)
if err != nil {
log.Fatal(err)
}
mc, err := getMaintnerClient(ctx)
if err != nil {
log.Fatal(err)
}
var goRepo = maintner.GitHubRepoID{Owner: "golang", Repo: "go"}
var vscode = maintner.GitHubRepoID{Owner: "golang", Repo: "vscode-go"}
bot := &gopherbot{
ghc: ghV3,
ghV4: ghV4,
gerrit: gerrit,
mc: mc,
is: ghV3.Issues,
deletedChanges: map[gerritChange]bool{
{"crypto", 35958}: true,
{"scratch", 71730}: true,
{"scratch", 71850}: true,
{"scratch", 72090}: true,
{"scratch", 72091}: true,
{"scratch", 72110}: true,
{"scratch", 72131}: true,
},
deletedIssues: map[githubIssue]bool{
{goRepo, 13084}: true,
{goRepo, 23772}: true,
{goRepo, 27223}: true,
{goRepo, 28522}: true,
{goRepo, 29309}: true,
{goRepo, 32047}: true,
{goRepo, 32048}: true,
{goRepo, 32469}: true,
{goRepo, 32706}: true,
{goRepo, 32737}: true,
{goRepo, 33315}: true,
{goRepo, 33316}: true,
{goRepo, 33592}: true,
{goRepo, 33593}: true,
{goRepo, 33697}: true,
{goRepo, 33785}: true,
{goRepo, 34296}: true,
{goRepo, 34476}: true,
{goRepo, 34766}: true,
{goRepo, 34780}: true,
{goRepo, 34786}: true,
{goRepo, 34821}: true,
{goRepo, 35493}: true,
{goRepo, 35649}: true,
{goRepo, 36322}: true,
{goRepo, 36323}: true,
{goRepo, 36324}: true,
{goRepo, 36342}: true,
{goRepo, 36343}: true,
{goRepo, 36406}: true,
{goRepo, 36517}: true,
{goRepo, 36829}: true,
{goRepo, 36885}: true,
{goRepo, 36933}: true,
{goRepo, 36939}: true,
{goRepo, 36941}: true,
{goRepo, 36947}: true,
{goRepo, 36962}: true,
{goRepo, 36963}: true,
{goRepo, 37516}: true,
{goRepo, 37522}: true,
{goRepo, 37582}: true,
{goRepo, 37896}: true,
{goRepo, 38132}: true,
{goRepo, 38241}: true,
{goRepo, 38483}: true,
{goRepo, 38560}: true,
{goRepo, 38840}: true,
{goRepo, 39112}: true,
{goRepo, 39141}: true,
{goRepo, 39229}: true,
{goRepo, 39234}: true,
{goRepo, 39335}: true,
{goRepo, 39401}: true,
{goRepo, 39453}: true,
{goRepo, 39522}: true,
{goRepo, 39718}: true,
{goRepo, 40400}: true,
{goRepo, 40593}: true,
{goRepo, 40600}: true,
{goRepo, 41211}: true,
{goRepo, 41268}: true, // transferred to https://github.com/golang/tour/issues/1042
{goRepo, 41336}: true,
{goRepo, 41649}: true,
{goRepo, 41650}: true,
{goRepo, 41655}: true,
{goRepo, 41675}: true,
{goRepo, 41676}: true,
{goRepo, 41678}: true,
{goRepo, 41679}: true,
{goRepo, 41714}: true,
{goRepo, 42309}: true,
{goRepo, 43102}: true,
{goRepo, 43169}: true,
{goRepo, 43231}: true,
{goRepo, 43330}: true,
{goRepo, 43409}: true,
{goRepo, 43410}: true,
{goRepo, 43411}: true,
{goRepo, 43433}: true,
{goRepo, 43613}: true,
{goRepo, 43751}: true,
{goRepo, 44124}: true,
{goRepo, 44185}: true,
{goRepo, 44566}: true,
{goRepo, 44652}: true,
{goRepo, 44711}: true,
{goRepo, 44768}: true,
{goRepo, 44769}: true,
{goRepo, 44771}: true,
{goRepo, 44773}: true,
{goRepo, 44871}: true,
{goRepo, 45018}: true,
{goRepo, 45082}: true,
{goRepo, 45201}: true,
{goRepo, 45202}: true,
{goRepo, 47140}: true,
{goRepo, 62987}: true,
{goRepo, 67913}: true,
{vscode, 298}: true,
{vscode, 524}: true,
{vscode, 650}: true,
{vscode, 741}: true,
{vscode, 773}: true,
{vscode, 959}: true,
{vscode, 1402}: true,
{vscode, 2260}: true, // transferred to https://go.dev/issue/53080
{vscode, 2548}: true,
{vscode, 2781}: true, // transferred to https://go.dev/issue/60435
},
}
for n := int32(55359); n <= 55828; n++ {
bot.deletedIssues[githubIssue{goRepo, n}] = true
}
bot.initCorpus()
for {
t0 := time.Now()
taskErrors := bot.doTasks(ctx)
for _, err := range taskErrors {
log.Print(err)
}
botDur := time.Since(t0)
log.Printf("gopherbot ran in %v", botDur)
if !*daemon {
if len(taskErrors) > 0 {
os.Exit(1)
}
return
}
if len(taskErrors) > 0 {
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
ghV4 *githubv4.Client
gerrit *gerrit.Client
mc apipb.MaintnerServiceClient
corpus *maintner.Corpus
gorepo *maintner.GitHubRepo
is issuesService
knownContributors map[string]bool
// Until golang.org/issue/22635 is fixed, keep a map of changes and issues
// that were deleted to prevent calls to Gerrit or GitHub that will always 404.
deletedChanges map[gerritChange]bool
deletedIssues map[githubIssue]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".
nextMinor map[string]string // Key is a major release like "1.9", value is its next minor release like "1.9.7".
}
}
var tasks = []struct {
name string
fn func(*gopherbot, context.Context) error
}{
// Tasks that are specific to the golang/go repo.
{"kicktrain", (*gopherbot).getOffKickTrain},
{"label access issues", (*gopherbot).labelAccessIssues},
{"label build issues", (*gopherbot).labelBuildIssues},
{"label compiler/runtime issues", (*gopherbot).labelCompilerRuntimeIssues},
{"label mobile issues", (*gopherbot).labelMobileIssues},
{"label tools issues", (*gopherbot).labelToolsIssues},
{"label website issues", (*gopherbot).labelWebsiteIssues},
{"label pkgsite issues", (*gopherbot).labelPkgsiteIssues},
{"label proxy.golang.org issues", (*gopherbot).labelProxyIssues},
{"label vulncheck or vulndb issues", (*gopherbot).labelVulnIssues},
{"label proposals", (*gopherbot).labelProposals},
{"handle gopls issues", (*gopherbot).handleGoplsIssues},
{"handle telemetry issues", (*gopherbot).handleTelemetryIssues},
{"open cherry pick issues", (*gopherbot).openCherryPickIssues},
{"close cherry pick issues", (*gopherbot).closeCherryPickIssues},
{"close luci-config issues", (*gopherbot).closeLUCIConfigIssues},
{"set subrepo milestones", (*gopherbot).setSubrepoMilestones},
{"set misc milestones", (*gopherbot).setMiscMilestones},
{"apply minor release milestones", (*gopherbot).setMinorMilestones},
{"update needs", (*gopherbot).updateNeeds},
// Tasks that can be applied to many repos.
{"freeze old issues", (*gopherbot).freezeOldIssues},
{"label documentation issues", (*gopherbot).labelDocumentationIssues},
{"close stale WaitingForInfo", (*gopherbot).closeStaleWaitingForInfo},
{"apply labels from comments", (*gopherbot).applyLabelsFromComments},
// Gerrit tasks are applied to all projects by default.
{"abandon scratch reviews", (*gopherbot).abandonScratchReviews},
{"assign reviewers to CLs", (*gopherbot).assignReviewersToCLs},
{"auto-submit CLs", (*gopherbot).autoSubmitCLs},
// Tasks that are specific to the golang/vscode-go repo.
{"set vscode-go milestones", (*gopherbot).setVSCodeGoMilestones},
{"access", (*gopherbot).whoNeedsAccess},
{"cl2issue", (*gopherbot).cl2issue},
{"congratulate new contributors", (*gopherbot).congratulateNewContributors},
{"un-wait CLs", (*gopherbot).unwaitCLs},
{"convert wait-release topic to hashtag", (*gopherbot).topicToHashtag},
}
// gardenIssues reports whether GopherBot should perform general issue
// gardening tasks for the repo.
func gardenIssues(repo *maintner.GitHubRepo) bool {
if repo.ID().Owner != "golang" {
return false
}
switch repo.ID().Repo {
case "go", "vscode-go", "vulndb", "oscar":
return true
}
return false
}
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
}
// doTasks performs tasks in sequence. It doesn't stop if
// if encounters an error, but reports errors at the end.
func (b *gopherbot) doTasks(ctx context.Context) []error {
var errs []error
for _, task := range tasks {
if *onlyRun != "" && task.name != *onlyRun {
continue
}
err := task.fn(b, ctx)
if err != nil {
errs = append(errs, fmt.Errorf("%s: %v", task.name, err))
}
}
return errs
}
// issuesService represents portions of github.IssuesService that we want to override in tests.
type issuesService interface {
ListLabelsByIssue(ctx context.Context, owner, repo string, number int, opt *github.ListOptions) ([]*github.Label, *github.Response, error)
AddLabelsToIssue(ctx context.Context, owner, repo string, number int, labels []string) ([]*github.Label, *github.Response, error)
RemoveLabelForIssue(ctx context.Context, owner, repo string, number int, label string) (*github.Response, error)
}
func (b *gopherbot) addLabel(ctx context.Context, repoID maintner.GitHubRepoID, gi *maintner.GitHubIssue, label string) error {
return b.addLabels(ctx, repoID, gi, []string{label})
}
func (b *gopherbot) addLabels(ctx context.Context, repoID maintner.GitHubRepoID, 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, repoID, gi)
toAdd = append(toAdd, label)
}
if *dryRun || len(toAdd) == 0 {
return nil
}
_, resp, err := b.is.AddLabelsToIssue(ctx, repoID.Owner, repoID.Repo, int(gi.Number), toAdd)
if err != nil && resp != nil && (resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusGone) {
// TODO(golang/go#40640) - This issue was transferred or otherwise is gone. We should permanently skip it. This
// is a temporary fix to keep gopherbot working.
log.Printf("addLabels: Issue %v#%v returned %s when trying to add labels. Skipping. See golang/go#40640.", repoID, gi.Number, resp.Status)
b.deletedIssues[githubIssue{repoID, gi.Number}] = true
return nil
}
return err
}
// removeLabel removes the label from the given issue in the given repo.
func (b *gopherbot) removeLabel(ctx context.Context, repoID maintner.GitHubRepoID, gi *maintner.GitHubIssue, label string) error {
return b.removeLabels(ctx, repoID, gi, []string{label})
}
func (b *gopherbot) removeLabels(ctx context.Context, repoID maintner.GitHubRepoID, 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, repoID, gi)
removeLabels = true
}
if *dryRun || !removeLabels {
return nil
}
ghLabels, err := labelsForIssue(ctx, repoID, b.is, 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, repoID, b.is, 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 given repo.
func labelsForIssue(ctx context.Context, repoID maintner.GitHubRepoID, issues issuesService, issueNum int) ([]string, error) {
ghLabels, _, err := issues.ListLabelsByIssue(ctx, repoID.Owner, repoID.Repo, issueNum, &github.ListOptions{PerPage: 100})
if err != nil {
return nil, fmt.Errorf("could not list labels for %s#%d: %v", repoID, issueNum, err)
}
var labels []string
for _, l := range ghLabels {
labels = append(labels, l.GetName())
}
return labels, nil
}
// removeLabelFromIssue removes the given label from the given repo with the
// given issueNum. If the issue did not have the label already (or the label
// didn't exist), return nil.
func removeLabelFromIssue(ctx context.Context, repoID maintner.GitHubRepoID, issues issuesService, issueNum int, label string) error {
_, err := issues.RemoveLabelForIssue(ctx, repoID.Owner, repoID.Repo, 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, repoID maintner.GitHubRepoID, gi *maintner.GitHubIssue, m milestone) error {
printIssue("milestone-"+m.Name, repoID, gi)
if *dryRun {
return nil
}
_, resp, err := b.ghc.Issues.Edit(ctx, repoID.Owner, repoID.Repo, int(gi.Number), &github.IssueRequest{
Milestone: github.Int(m.Number),
})
if err != nil && resp != nil && (resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusGone) {
// An issue can become gone on GitHub without maintner realizing it. See go.dev/issue/30184.
log.Printf("setMilestone: Issue %v#%v returned %s when trying to set milestone. Skipping. See go.dev/issue/30184.", repoID, gi.Number, resp.Status)
b.deletedIssues[githubIssue{repoID, gi.Number}] = true
return nil
}
return err
}
func (b *gopherbot) addGitHubComment(ctx context.Context, repo *maintner.GitHubRepo, issueNum int32, msg string) error {
var since time.Time
if gi := repo.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.
opt := &github.IssueListCommentsOptions{ListOptions: github.ListOptions{PerPage: 1000}}
if !since.IsZero() {
opt.Since = &since
}
ics, resp, err := b.ghc.Issues.ListComments(ctx, repo.ID().Owner, repo.ID().Repo, int(issueNum), opt)
if err != nil {
// TODO(golang/go#40640) - This issue was transferred or otherwise is gone. We should permanently skip it. This
// is a temporary fix to keep gopherbot working.
if resp != nil && resp.StatusCode == http.StatusNotFound {
log.Printf("addGitHubComment: Issue %v#%v returned a 404 when trying to load comments. Skipping. See golang/go#40640.", repo.ID(), issueNum)
b.deletedIssues[githubIssue{repo.ID(), issueNum}] = true
return 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/issues/%d: %v", repo.ID(), issueNum, msg)
return nil
}
_, resp, createError := b.ghc.Issues.CreateComment(ctx, repo.ID().Owner, repo.ID().Repo, int(issueNum), &github.IssueComment{
Body: github.String(msg),
})
if createError != nil && resp != nil && resp.StatusCode == http.StatusUnprocessableEntity {
// While maintner's tracking of deleted issues is incomplete (see go.dev/issue/30184),
// we sometimes see a deleted issue whose /comments endpoint returns 200 OK with an
// empty list, so the error check from ListComments doesn't catch it. (The deleted
// issue 55403 is an example of such a case.) So check again with the Get endpoint,
// which seems to return 404 more reliably in such cases at least as of 2022-10-11.
if _, resp, err := b.ghc.Issues.Get(ctx, repo.ID().Owner, repo.ID().Repo, int(issueNum)); err != nil &&
resp != nil && resp.StatusCode == http.StatusNotFound {
log.Printf("addGitHubComment: Issue %v#%v returned a 404 after posting comment failed with 422. Skipping. See go.dev/issue/30184.", repo.ID(), issueNum)
b.deletedIssues[githubIssue{repo.ID(), issueNum}] = true
return nil
}
}
return createError
}
// 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
}
// issueCloseReason is a reason given when closing an issue on GitHub.
// See https://docs.github.com/en/issues/tracking-your-work-with-issues/closing-an-issue.
type issueCloseReason *string
var (
completed issueCloseReason = github.String("completed") // Done, closed, fixed, resolved.
notPlanned issueCloseReason = github.String("not_planned") // Won't fix, can't repro, duplicate, stale.
)
// closeGitHubIssue closes a GitHub issue.
// reason specifies why it's being closed. (GitHub's default reason on 2023-06-12 is "completed".)
func (b *gopherbot) closeGitHubIssue(ctx context.Context, repoID maintner.GitHubRepoID, number int32, reason issueCloseReason) error {
if *dryRun {
var suffix string
if reason != nil {
suffix = " as " + *reason
}
log.Printf("[dry-run] would close go.dev/issue/%v%s", number, suffix)
return nil
}
_, _, err := b.ghc.Issues.Edit(ctx, repoID.Owner, repoID.Repo, int(number), &github.IssueRequest{
State: github.String("closed"),
StateReason: reason,
})
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 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.foreachIssue(b.gorepo, open, func(gi *maintner.GitHubIssue) error {
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://go.dev/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, b.gorepo.ID(), m.gi, unplanned); err != nil {
return err
}
}
}
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.corpus.GitHub().ForeachRepo(func(repo *maintner.GitHubRepo) error {
if !gardenIssues(repo) {
return nil
}
if !repoHasLabel(repo, frozenDueToAge) {
return nil
}
return b.foreachIssue(repo, closed, func(gi *maintner.GitHubIssue) error {
if gi.Locked || gi.Updated.After(tooOld) {
return nil
}
printIssue("freeze", repo.ID(), gi)
if *dryRun {
return nil
}
_, err := b.ghc.Issues.Lock(ctx, repo.ID().Owner, repo.ID().Repo, int(gi.Number), nil)
if ge, ok := err.(*github.ErrorResponse); ok && ge.Response.StatusCode == http.StatusNotFound {
// An issue can become 404 on GitHub due to being deleted or transferred. See go.dev/issue/30182.
b.deletedIssues[githubIssue{repo.ID(), gi.Number}] = true
return nil
} else if err != nil {
return err
}
return b.addLabel(ctx, repo.ID(), 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.foreachIssue(b.gorepo, open, func(gi *maintner.GitHubIssue) error {
if !strings.HasPrefix(gi.Title, "proposal:") && !strings.HasPrefix(gi.Title, "Proposal:") {
return nil
}
// Add Proposal label if missing:
if !gi.HasLabel("Proposal") && !gi.HasEvent("unlabeled") {
if err := b.addLabel(ctx, b.gorepo.ID(), gi, "Proposal"); err != nil {
return err
}
}
// Add Milestone if missing:
if gi.Milestone.IsNone() && !gi.HasEvent("milestoned") && !gi.HasEvent("demilestoned") {
if err := b.setMilestone(ctx, b.gorepo.ID(), gi, proposal); err != nil {
return err
}
}
// Remove NeedsDecision label if exists, but not for Go 2 issues:
if !isGo2Issue(gi) && gi.HasLabel("NeedsDecision") && !gopherbotRemovedLabel(gi, "NeedsDecision") {
if err := b.removeLabel(ctx, b.gorepo.ID(), gi, "NeedsDecision"); err != nil {
return err
}
}
return nil
})
}
// gopherbotRemovedLabel reports whether gopherbot has
// previously removed label in the GitHub issue gi.
//
// Note that until golang.org/issue/28226 is resolved,
// there's a brief delay before maintner catches up on
// GitHub issue events and learns that it has happened.
func gopherbotRemovedLabel(gi *maintner.GitHubIssue, label string) bool {
var hasRemoved bool