-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathgithub.go
2622 lines (2409 loc) · 69.4 KB
/
github.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.
package maintner
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"reflect"
"regexp"
"runtime"
"slices"
"sort"
"strconv"
"strings"
"time"
"github.com/google/go-github/v48/github"
"github.com/gregjones/httpcache"
"golang.org/x/build/maintner/maintpb"
"golang.org/x/oauth2"
"golang.org/x/sync/errgroup"
"golang.org/x/time/rate"
"google.golang.org/protobuf/types/known/timestamppb"
)
// xFromCache is the synthetic response header added by the httpcache
// package for responses fulfilled from cache due to a 304 from the server.
const xFromCache = "X-From-Cache"
// GitHubRepoID is a GitHub org & repo, lowercase.
type GitHubRepoID struct {
Owner, Repo string
}
func (id GitHubRepoID) String() string { return id.Owner + "/" + id.Repo }
func (id GitHubRepoID) valid() bool {
if id.Owner == "" || id.Repo == "" {
// TODO: more validation. whatever GitHub requires.
return false
}
return true
}
// GitHub holds data about a GitHub repo.
type GitHub struct {
c *Corpus
users map[int64]*GitHubUser
teams map[int64]*GitHubTeam
repos map[GitHubRepoID]*GitHubRepo
}
// ForeachRepo calls fn serially for each GitHubRepo, stopping if fn
// returns an error. The function is called with lexically increasing
// repo IDs.
func (g *GitHub) ForeachRepo(fn func(*GitHubRepo) error) error {
var ids []GitHubRepoID
for id := range g.repos {
ids = append(ids, id)
}
sort.Slice(ids, func(i, j int) bool {
if ids[i].Owner < ids[j].Owner {
return true
}
return ids[i].Owner == ids[j].Owner && ids[i].Repo < ids[j].Repo
})
for _, id := range ids {
if err := fn(g.repos[id]); err != nil {
return err
}
}
return nil
}
// Repo returns the repo if it's known. Otherwise it returns nil.
func (g *GitHub) Repo(owner, repo string) *GitHubRepo {
return g.repos[GitHubRepoID{owner, repo}]
}
func (g *GitHub) getOrCreateRepo(owner, repo string) *GitHubRepo {
if g == nil {
panic("cannot call methods on nil GitHub")
}
id := GitHubRepoID{owner, repo}
if !id.valid() {
return nil
}
r, ok := g.repos[id]
if ok {
return r
}
r = &GitHubRepo{
github: g,
id: id,
issues: map[int32]*GitHubIssue{},
}
g.repos[id] = r
return r
}
type GitHubRepo struct {
github *GitHub
id GitHubRepoID
issues map[int32]*GitHubIssue // num -> issue
milestones map[int64]*GitHubMilestone
labels map[int64]*GitHubLabel
}
func (gr *GitHubRepo) ID() GitHubRepoID { return gr.id }
// Issue returns the provided issue number, or nil if it's not known.
func (gr *GitHubRepo) Issue(n int32) *GitHubIssue { return gr.issues[n] }
// ForeachLabel calls fn for each label in the repo, in unsorted order.
//
// Iteration ends if fn returns an error, with that error.
func (gr *GitHubRepo) ForeachLabel(fn func(*GitHubLabel) error) error {
for _, lb := range gr.labels {
if err := fn(lb); err != nil {
return err
}
}
return nil
}
// ForeachMilestone calls fn for each milestone in the repo, in unsorted order.
//
// Iteration ends if fn returns an error, with that error.
func (gr *GitHubRepo) ForeachMilestone(fn func(*GitHubMilestone) error) error {
for _, m := range gr.milestones {
if err := fn(m); err != nil {
return err
}
}
return nil
}
// ForeachIssue calls fn for each issue in the repo.
//
// If fn returns an error, iteration ends and ForeachIssue returns
// with that error.
//
// The fn function is called serially, with increasingly numbered
// issues.
func (gr *GitHubRepo) ForeachIssue(fn func(*GitHubIssue) error) error {
s := make([]*GitHubIssue, 0, len(gr.issues))
for _, gi := range gr.issues {
s = append(s, gi)
}
sort.Slice(s, func(i, j int) bool { return s[i].Number < s[j].Number })
for _, gi := range s {
if err := fn(gi); err != nil {
return err
}
}
return nil
}
// ForeachReview calls fn for each review event on the issue
//
// If the issue is not a PullRequest, then it returns early with no error.
//
// If fn returns an error, iteration ends and ForeachReview returns
// with that error.
//
// The fn function is called serially, in chronological order.
func (pr *GitHubIssue) ForeachReview(fn func(*GitHubReview) error) error {
if !pr.PullRequest {
return nil
}
s := make([]*GitHubReview, 0, len(pr.reviews))
for _, rv := range pr.reviews {
s = append(s, rv)
}
sort.Slice(s, func(i, j int) bool { return s[i].Created.Before(s[j].Created) })
for _, rv := range s {
if err := fn(rv); err != nil {
return err
}
}
return nil
}
func (g *GitHubRepo) getOrCreateMilestone(id int64) *GitHubMilestone {
if id == 0 {
panic("zero id")
}
m, ok := g.milestones[id]
if ok {
return m
}
if g.milestones == nil {
g.milestones = map[int64]*GitHubMilestone{}
}
m = &GitHubMilestone{ID: id}
g.milestones[id] = m
return m
}
func (g *GitHubRepo) getOrCreateLabel(id int64) *GitHubLabel {
if id == 0 {
panic("zero id")
}
lb, ok := g.labels[id]
if ok {
return lb
}
if g.labels == nil {
g.labels = map[int64]*GitHubLabel{}
}
lb = &GitHubLabel{ID: id}
g.labels[id] = lb
return lb
}
func (g *GitHubRepo) verbose() bool {
return g.github != nil && g.github.c != nil && g.github.c.verbose
}
// GitHubUser represents a GitHub user.
// It is a subset of https://developer.github.com/v3/users/#get-a-single-user
type GitHubUser struct {
ID int64
Login string
}
// GitHubTeam represents a GitHub team.
// It is a subset of https://developer.github.com/v3/orgs/teams/#get-team
type GitHubTeam struct {
ID int64
// Slug is a URL-friendly representation of the team name.
// It is unique across a GitHub organization.
Slug string
}
// GitHubIssueRef is a reference to an issue (or pull request) number
// in a repo. These are parsed from text making references such as
// "golang/go#1234" or just "#1234" (with an implicit Repo).
type GitHubIssueRef struct {
Repo *GitHubRepo // must be non-nil
Number int32 // GitHubIssue.Number
}
func (r GitHubIssueRef) String() string { return fmt.Sprintf("%s#%d", r.Repo.ID(), r.Number) }
// GitHubIssue represents a GitHub issue.
// This is maintner's in-memory representation. It differs slightly
// from the API's *github.Issue type, notably in the lack of pointers
// for all fields.
// See https://developer.github.com/v3/issues/#get-a-single-issue
type GitHubIssue struct {
ID int64
Number int32
NotExist bool // if true, rest of fields should be ignored.
Closed bool
Locked bool
PullRequest bool // if true, this issue is a Pull Request. All PRs are issues, but not all issues are PRs.
User *GitHubUser
Assignees []*GitHubUser
Created time.Time
Updated time.Time
ClosedAt time.Time
ClosedBy *GitHubUser // TODO(dmitshur): Implement (see golang.org/issue/28745).
Title string
Body string
Milestone *GitHubMilestone // nil for unknown, noMilestone for none
Labels map[int64]*GitHubLabel // label ID => label
commentsUpdatedTil time.Time // max comment modtime seen
commentsSyncedAsOf time.Time // as of server's Date header
comments map[int64]*GitHubComment // by comment.ID
eventMaxTime time.Time // latest time of any event in events map
eventsSyncedAsOf time.Time // as of server's Date header
reviewsSyncedAsOf time.Time // as of server's Date header
events map[int64]*GitHubIssueEvent // by event.ID
reviews map[int64]*GitHubReview // by event.ID
}
// LastModified reports the most recent time that any known metadata was updated.
// In contrast to the Updated field, LastModified includes comments and events.
//
// TODO(bradfitz): this seems to not be working, at least events
// aren't updating it. Investigate.
func (gi *GitHubIssue) LastModified() time.Time {
ret := gi.Updated
if gi.commentsUpdatedTil.After(ret) {
ret = gi.commentsUpdatedTil
}
if gi.eventMaxTime.After(ret) {
ret = gi.eventMaxTime
}
return ret
}
// HasEvent reports whether there's any GitHubIssueEvent in this
// issue's history of the given type.
func (gi *GitHubIssue) HasEvent(eventType string) bool {
for _, e := range gi.events {
if e.Type == eventType {
return true
}
}
return false
}
// ForeachEvent calls fn for each event on the issue.
//
// If fn returns an error, iteration ends and ForeachEvent returns
// with that error.
//
// The fn function is called serially, in order of the event's time.
func (gi *GitHubIssue) ForeachEvent(fn func(*GitHubIssueEvent) error) error {
// TODO: keep these sorted in the corpus
s := make([]*GitHubIssueEvent, 0, len(gi.events))
for _, e := range gi.events {
s = append(s, e)
}
sort.Slice(s, func(i, j int) bool {
ci, cj := s[i].Created, s[j].Created
if ci.Before(cj) {
return true
}
return ci.Equal(cj) && s[i].ID < s[j].ID
})
for _, e := range s {
if err := fn(e); err != nil {
return err
}
}
return nil
}
// ForeachComment calls fn for each event on the issue.
//
// If fn returns an error, iteration ends and ForeachComment returns
// with that error.
//
// The fn function is called serially, in order of the comment's time.
func (gi *GitHubIssue) ForeachComment(fn func(*GitHubComment) error) error {
// TODO: keep these sorted in the corpus
s := make([]*GitHubComment, 0, len(gi.comments))
for _, e := range gi.comments {
s = append(s, e)
}
sort.Slice(s, func(i, j int) bool {
ci, cj := s[i].Created, s[j].Created
if ci.Before(cj) {
return true
}
return ci.Equal(cj) && s[i].ID < s[j].ID
})
for _, e := range s {
if err := fn(e); err != nil {
return err
}
}
return nil
}
// HasLabel reports whether the issue is labeled with the given label.
func (gi *GitHubIssue) HasLabel(label string) bool {
for _, lb := range gi.Labels {
if lb.Name == label {
return true
}
}
return false
}
// HasLabelID returns whether the issue has a label with the given ID.
func (gi *GitHubIssue) HasLabelID(id int64) bool {
_, ok := gi.Labels[id]
return ok
}
func (gi *GitHubIssue) getCreatedAt() time.Time {
if gi == nil {
return time.Time{}
}
return gi.Created
}
func (gi *GitHubIssue) getUpdatedAt() time.Time {
if gi == nil {
return time.Time{}
}
return gi.Updated
}
func (gi *GitHubIssue) getClosedAt() time.Time {
if gi == nil {
return time.Time{}
}
return gi.ClosedAt
}
// noMilestone is a sentinel value to explicitly mean no milestone.
var noMilestone = new(GitHubMilestone)
type GitHubLabel struct {
ID int64
Name string
// TODO: color?
}
// GenMutationDiff generates a diff from in-memory state 'a' (which
// may be nil) to the current (non-nil) state b from GitHub. It
// returns nil if there's no difference.
func (a *GitHubLabel) GenMutationDiff(b *github.Label) *maintpb.GithubLabel {
id := int64(b.GetID())
if a != nil && a.ID == id && a.Name == b.GetName() {
// No change.
return nil
}
return &maintpb.GithubLabel{Id: id, Name: b.GetName()}
}
func (lb *GitHubLabel) processMutation(mut maintpb.GithubLabel) {
if lb.ID == 0 {
panic("bogus label ID 0")
}
if lb.ID != mut.Id {
panic(fmt.Sprintf("label ID = %v != mutation ID = %v", lb.ID, mut.Id))
}
if mut.Name != "" {
lb.Name = mut.Name
}
}
type GitHubMilestone struct {
ID int64
Title string
Number int32
Closed bool
}
// IsNone reports whether ms represents the sentinel "no milestone" milestone.
func (ms *GitHubMilestone) IsNone() bool { return ms == noMilestone }
// IsUnknown reports whether ms is nil, which represents the unknown
// state. Milestones should never be in this state, though.
func (ms *GitHubMilestone) IsUnknown() bool { return ms == nil }
// emptyMilestone is a non-nil *githubMilestone with zero values for
// all fields.
var emptyMilestone = new(GitHubMilestone)
// GenMutationDiff generates a diff from in-memory state 'a' (which
// may be nil) to the current (non-nil) state b from GitHub. It
// returns nil if there's no difference.
func (a *GitHubMilestone) GenMutationDiff(b *github.Milestone) *maintpb.GithubMilestone {
var ret *maintpb.GithubMilestone // lazily inited by diff
diff := func() *maintpb.GithubMilestone {
if ret == nil {
ret = &maintpb.GithubMilestone{Id: int64(b.GetID())}
}
return ret
}
if a == nil {
a = emptyMilestone
}
if a.Title != b.GetTitle() {
diff().Title = b.GetTitle()
}
if a.Number != int32(b.GetNumber()) {
diff().Number = int64(b.GetNumber())
}
if closed := b.GetState() == "closed"; a.Closed != closed {
diff().Closed = &maintpb.BoolChange{Val: closed}
}
return ret
}
func (ms *GitHubMilestone) processMutation(mut maintpb.GithubMilestone) {
if ms.ID == 0 {
panic("bogus milestone ID 0")
}
if ms.ID != mut.Id {
panic(fmt.Sprintf("milestone ID = %v != mutation ID = %v", ms.ID, mut.Id))
}
if mut.Title != "" {
ms.Title = mut.Title
}
if mut.Number != 0 {
ms.Number = int32(mut.Number)
}
if mut.Closed != nil {
ms.Closed = mut.Closed.Val
}
}
// GitHubReview represents a review on a Pull Request.
// For more details, see https://developer.github.com/v3/pulls/reviews/
type GitHubReview struct {
ID int64
Actor *GitHubUser
Body string
State string // COMMENTED, APPROVED, CHANGES_REQUESTED
CommitID string
ActorAssociation string // CONTRIBUTOR
Created time.Time
OtherJSON string
}
// Proto converts GitHubReview to a protobuf
func (e *GitHubReview) Proto() *maintpb.GithubReview {
p := &maintpb.GithubReview{
Id: e.ID,
Body: e.Body,
State: e.State,
CommitId: e.CommitID,
ActorAssociation: e.ActorAssociation,
}
if e.OtherJSON != "" {
p.OtherJson = []byte(e.OtherJSON)
}
if !e.Created.IsZero() {
p.Created = timestamppb.New(e.Created)
}
if e.Actor != nil {
p.ActorId = e.Actor.ID
}
return p
}
// r.github.c.mu must be held.
func (r *GitHubRepo) newGithubReview(p *maintpb.GithubReview) *GitHubReview {
g := r.github
e := &GitHubReview{
ID: p.Id,
Actor: g.getOrCreateUserID(p.ActorId),
ActorAssociation: p.ActorAssociation,
CommitID: p.CommitId,
Body: p.Body,
State: p.State,
}
if p.Created != nil {
e.Created = p.Created.AsTime()
}
if len(p.OtherJson) > 0 {
// TODO: parse it and see if we've since learned how
// to deal with it?
if r.verbose() {
log.Printf("newGithubReview: unknown JSON in log: %s", p.OtherJson)
}
e.OtherJSON = string(p.OtherJson)
}
return e
}
type GitHubComment struct {
ID int64
User *GitHubUser
Created time.Time
Updated time.Time
Body string
}
// GitHubDismissedReviewEvent is the contents of a dismissed review event. For more
// details, see https://developer.github.com/v3/issues/events/.
type GitHubDismissedReviewEvent struct {
ReviewID int64
State string // commented, approved, changes_requested
DismissalMessage string
}
type GitHubIssueEvent struct {
// TODO: this struct is a little wide. change it to an interface
// instead? Maybe later, if memory profiling suggests it would help.
// ID is the ID of the event.
ID int64
// Type is one of:
// * labeled, unlabeled
// * milestoned, demilestoned
// * assigned, unassigned
// * locked, unlocked
// * closed
// * referenced
// * renamed
// * reopened
// * comment_deleted
// * head_ref_restored
// * base_ref_changed
// * subscribed
// * mentioned
// * review_requested, review_request_removed, review_dismissed
Type string
// OtherJSON optionally contains a JSON object of GitHub's API
// response for any fields maintner was unable to extract at
// the time. It is empty if maintner supported all the fields
// when the mutation was created.
OtherJSON string
Created time.Time
Actor *GitHubUser
Label string // for type: "unlabeled", "labeled"
Assignee *GitHubUser // for type: "assigned", "unassigned"
Assigner *GitHubUser // for type: "assigned", "unassigned"
Milestone string // for type: "milestoned", "demilestoned"
From, To string // for type: "renamed"
CommitID, CommitURL string // for type: "closed", "referenced" ... ?
Reviewer *GitHubUser
TeamReviewer *GitHubTeam
ReviewRequester *GitHubUser
DismissedReview *GitHubDismissedReviewEvent
}
func (e *GitHubIssueEvent) Proto() *maintpb.GithubIssueEvent {
p := &maintpb.GithubIssueEvent{
Id: e.ID,
EventType: e.Type,
RenameFrom: e.From,
RenameTo: e.To,
}
if e.OtherJSON != "" {
p.OtherJson = []byte(e.OtherJSON)
}
if !e.Created.IsZero() {
p.Created = timestamppb.New(e.Created)
}
if e.Actor != nil {
p.ActorId = e.Actor.ID
}
if e.Assignee != nil {
p.AssigneeId = e.Assignee.ID
}
if e.Assigner != nil {
p.AssignerId = e.Assigner.ID
}
if e.Label != "" {
p.Label = &maintpb.GithubLabel{Name: e.Label}
}
if e.Milestone != "" {
p.Milestone = &maintpb.GithubMilestone{Title: e.Milestone}
}
if e.CommitID != "" {
c := &maintpb.GithubCommit{CommitId: e.CommitID}
if m := rxGithubCommitURL.FindStringSubmatch(e.CommitURL); m != nil {
c.Owner = m[1]
c.Repo = m[2]
}
p.Commit = c
}
if e.Reviewer != nil {
p.ReviewerId = e.Reviewer.ID
}
if e.TeamReviewer != nil {
p.TeamReviewer = &maintpb.GithubTeam{
Id: e.TeamReviewer.ID,
Slug: e.TeamReviewer.Slug,
}
}
if e.ReviewRequester != nil {
p.ReviewRequesterId = e.ReviewRequester.ID
}
if e.DismissedReview != nil {
p.DismissedReview = &maintpb.GithubDismissedReviewEvent{
ReviewId: e.DismissedReview.ReviewID,
State: e.DismissedReview.State,
DismissalMessage: e.DismissedReview.DismissalMessage,
}
}
return p
}
var rxGithubCommitURL = regexp.MustCompile(`^https://api\.github\.com/repos/([^/]+)/([^/]+)/commits/`)
// r.github.c.mu must be held.
func (r *GitHubRepo) newGithubEvent(p *maintpb.GithubIssueEvent) *GitHubIssueEvent {
g := r.github
e := &GitHubIssueEvent{
ID: p.Id,
Type: p.EventType,
Actor: g.getOrCreateUserID(p.ActorId),
Assignee: g.getOrCreateUserID(p.AssigneeId),
Assigner: g.getOrCreateUserID(p.AssignerId),
Reviewer: g.getOrCreateUserID(p.ReviewerId),
TeamReviewer: g.getTeam(p.TeamReviewer),
ReviewRequester: g.getOrCreateUserID(p.ReviewRequesterId),
From: p.RenameFrom,
To: p.RenameTo,
}
if p.Created != nil {
e.Created = p.Created.AsTime()
}
if len(p.OtherJson) > 0 {
// TODO: parse it and see if we've since learned how
// to deal with it?
if r.verbose() {
log.Printf("newGithubEvent: unknown JSON in log: %s", p.OtherJson)
}
e.OtherJSON = string(p.OtherJson)
}
if p.Label != nil {
e.Label = g.c.str(p.Label.Name)
}
if p.Milestone != nil {
e.Milestone = g.c.str(p.Milestone.Title)
}
if c := p.Commit; c != nil {
e.CommitID = c.CommitId
if c.Owner != "" && c.Repo != "" {
// TODO: this field is dumb. break it down.
e.CommitURL = "https://api.github.com/repos/" + c.Owner + "/" + c.Repo + "/commits/" + c.CommitId
}
}
if d := p.DismissedReview; d != nil {
e.DismissedReview = &GitHubDismissedReviewEvent{
ReviewID: d.ReviewId,
State: d.State,
DismissalMessage: d.DismissalMessage,
}
}
return e
}
// (requires corpus be locked for reads)
func (gi *GitHubIssue) commentsSynced() bool {
if gi.NotExist {
// Issue doesn't exist, so can't sync its non-issues,
// so consider it done.
return true
}
return gi.commentsSyncedAsOf.After(gi.Updated)
}
// (requires corpus be locked for reads)
func (gi *GitHubIssue) eventsSynced() bool {
if gi.NotExist {
// Issue doesn't exist, so can't sync its non-issues,
// so consider it done.
return true
}
return gi.eventsSyncedAsOf.After(gi.Updated)
}
// (requires corpus be locked for reads)
func (gi *GitHubIssue) reviewsSynced() bool {
if gi.NotExist {
// Issue doesn't exist, so can't sync its non-issues,
// so consider it done.
return true
}
return gi.reviewsSyncedAsOf.After(gi.Updated)
}
func (c *Corpus) initGithub() {
if c.github != nil {
return
}
c.github = &GitHub{
c: c,
repos: map[GitHubRepoID]*GitHubRepo{},
}
}
// SetGitHubLimiter sets a limiter that controls the rate of requests made
// to GitHub APIs. If nil, requests are not limited. Only valid in leader mode.
// The limiter must only be set before Sync or SyncLoop is called.
func (c *Corpus) SetGitHubLimiter(l *rate.Limiter) {
c.githubLimiter = l
}
// TrackGitHub registers the named GitHub repo as a repo to
// watch and append to the mutation log. Only valid in leader mode.
// The token is the auth token to use to make API calls.
func (c *Corpus) TrackGitHub(owner, repo, token string) {
if c.mutationLogger == nil {
panic("can't TrackGitHub in non-leader mode")
}
c.mu.Lock()
defer c.mu.Unlock()
c.initGithub()
gr := c.github.getOrCreateRepo(owner, repo)
if gr == nil {
log.Fatalf("invalid github owner/repo %q/%q", owner, repo)
}
c.watchedGithubRepos = append(c.watchedGithubRepos, watchedGithubRepo{
gr: gr,
token: token,
})
}
type watchedGithubRepo struct {
gr *GitHubRepo
token string
}
// g.c.mu must be held
func (g *GitHub) getUser(pu *maintpb.GithubUser) *GitHubUser {
if pu == nil {
return nil
}
if u := g.users[pu.Id]; u != nil {
if pu.Login != "" && pu.Login != u.Login {
u.Login = pu.Login
}
return u
}
if g.users == nil {
g.users = make(map[int64]*GitHubUser)
}
u := &GitHubUser{
ID: pu.Id,
Login: pu.Login,
}
g.users[pu.Id] = u
return u
}
func (g *GitHub) getOrCreateUserID(id int64) *GitHubUser {
if id == 0 {
return nil
}
if u := g.users[id]; u != nil {
return u
}
if g.users == nil {
g.users = make(map[int64]*GitHubUser)
}
u := &GitHubUser{ID: id}
g.users[id] = u
return u
}
// g.c.mu must be held
func (g *GitHub) getTeam(pt *maintpb.GithubTeam) *GitHubTeam {
if pt == nil {
return nil
}
if g.teams == nil {
g.teams = make(map[int64]*GitHubTeam)
}
t := g.teams[pt.Id]
if t == nil {
t = &GitHubTeam{
ID: pt.Id,
}
g.teams[pt.Id] = t
}
if pt.Slug != "" {
t.Slug = pt.Slug
}
return t
}
// newGithubUserProto creates a GithubUser with the minimum diff between
// existing and g. The return value is nil if there were no changes. existing
// may also be nil.
func newGithubUserProto(existing *GitHubUser, g *github.User) *maintpb.GithubUser {
if g == nil {
return nil
}
id := int64(g.GetID())
if existing == nil {
return &maintpb.GithubUser{
Id: id,
Login: g.GetLogin(),
}
}
hasChanges := false
u := &maintpb.GithubUser{Id: id}
if login := g.GetLogin(); existing.Login != login {
u.Login = login
hasChanges = true
}
// Add more fields here
if hasChanges {
return u
}
return nil
}
// deletedAssignees returns an array of user ID's that are present in existing
// but not present in new.
func deletedAssignees(existing []*GitHubUser, new []*github.User) []int64 {
mp := make(map[int64]bool, len(existing))
for _, u := range new {
id := int64(u.GetID())
mp[id] = true
}
toDelete := []int64{}
for _, u := range existing {
if _, ok := mp[u.ID]; !ok {
toDelete = append(toDelete, u.ID)
}
}
return toDelete
}
// newAssignees returns an array of diffs between existing and new. New users in
// new will be present in the returned array in their entirety. Modified users
// will appear containing only the ID field and changed fields. Unmodified users
// will not appear in the returned array.
func newAssignees(existing []*GitHubUser, new []*github.User) []*maintpb.GithubUser {
mp := make(map[int64]*GitHubUser, len(existing))
for _, u := range existing {
mp[u.ID] = u
}
changes := []*maintpb.GithubUser{}
for _, u := range new {
if existingUser, ok := mp[int64(u.GetID())]; ok {
diffUser := &maintpb.GithubUser{
Id: int64(u.GetID()),
}
hasDiff := false
if login := u.GetLogin(); existingUser.Login != login {
diffUser.Login = login
hasDiff = true
}
// check more User fields for diffs here, as we add them to the proto
if hasDiff {
changes = append(changes, diffUser)
}
} else {
changes = append(changes, &maintpb.GithubUser{
Id: int64(u.GetID()),
Login: u.GetLogin(),
})
}
}
return changes
}
// setAssigneesFromProto returns a new array of assignees according to the
// instructions in new (adds or modifies users in existing), and toDelete
// (deletes them). c.mu must be held.
func (g *GitHub) setAssigneesFromProto(existing []*GitHubUser, new []*maintpb.GithubUser, toDelete []int64) []*GitHubUser {
c := g.c
mp := make(map[int64]*GitHubUser)
for _, u := range existing {
mp[u.ID] = u
}
for _, u := range new {
if existingUser, ok := mp[u.Id]; ok {
if u.Login != "" {
existingUser.Login = u.Login
}
// TODO: add other fields here when we add them for user.
} else {
c.debugf("adding assignee %q", u.Login)
existing = append(existing, g.getUser(u))
}
}
// this is quadratic but the number of assignees is very unlikely to exceed,
// say, 5.
existing = slices.DeleteFunc(existing, func(u *GitHubUser) bool {
return slices.Contains(toDelete, u.ID)
})
return existing
}
// githubIssueDiffer generates a minimal diff (protobuf mutation) to
// get a GitHub Issue from its in-memory state 'a' to the current
// GitHub API state 'b'.
type githubIssueDiffer struct {
gr *GitHubRepo
a *GitHubIssue // may be nil if no current state
b *github.Issue // may NOT be nil
}
// returns nil if no changes.
func (d githubIssueDiffer) Diff() *maintpb.GithubIssueMutation {
var changed bool
m := &maintpb.GithubIssueMutation{
Owner: d.gr.id.Owner,
Repo: d.gr.id.Repo,
Number: int32(d.b.GetNumber()),
PullRequest: d.b.IsPullRequest(),
}
for _, f := range issueDiffMethods {
if f(d, m) {
if d.gr.verbose() {
fname := strings.TrimPrefix(runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name(), "golang.org/x/build/maintner.githubIssueDiffer.")
log.Printf("Issue %d changed: %v", d.b.GetNumber(), fname)
}
changed = true
}
}
if !changed {