-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathgerrit.go
1667 lines (1509 loc) · 46.1 KB
/
gerrit.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.
// Logic to interact with a Gerrit server. Gerrit has an entire Git-based
// protocol for fetching metadata about CL's, reviewers, patch comments, which
// is used here - we don't use the x/build/gerrit client, which hits the API.
// TODO: write about Gerrit's Git API.
package maintner
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"log"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"golang.org/x/build/internal/envutil"
"golang.org/x/build/maintner/maintpb"
)
// Gerrit holds information about a number of Gerrit projects.
type Gerrit struct {
c *Corpus
projects map[string]*GerritProject // keyed by "go.googlesource.com/build"
clsReferencingGithubIssue map[GitHubIssueRef][]*GerritCL
}
func normalizeGerritServer(server string) string {
u, err := url.Parse(server)
if err == nil && u.Host != "" {
server = u.Host
}
if strings.HasSuffix(server, "-review.googlesource.com") {
// special case: the review site is hosted at a different URL than the
// Git checkout URL.
return strings.Replace(server, "-review.googlesource.com", ".googlesource.com", 1)
}
return server
}
// Project returns the specified Gerrit project if it's known, otherwise
// it returns nil. Server is the Gerrit server's hostname, such as
// "go.googlesource.com".
func (g *Gerrit) Project(server, project string) *GerritProject {
server = normalizeGerritServer(server)
return g.projects[server+"/"+project]
}
// c.mu must be held
func (g *Gerrit) getOrCreateProject(gerritProj string) *GerritProject {
proj, ok := g.projects[gerritProj]
if ok {
return proj
}
proj = &GerritProject{
gerrit: g,
proj: gerritProj,
cls: map[int32]*GerritCL{},
remote: map[gerritCLVersion]GitHash{},
ref: map[string]GitHash{},
commit: map[GitHash]*GitCommit{},
need: map[GitHash]bool{},
}
g.projects[gerritProj] = proj
return proj
}
// ForeachProjectUnsorted calls fn for each known Gerrit project.
// Iteration ends if fn returns a non-nil value.
func (g *Gerrit) ForeachProjectUnsorted(fn func(*GerritProject) error) error {
for _, p := range g.projects {
if err := fn(p); err != nil {
return err
}
}
return nil
}
// GerritProject represents a single Gerrit project.
type GerritProject struct {
gerrit *Gerrit
proj string // "go.googlesource.com/net"
cls map[int32]*GerritCL
remote map[gerritCLVersion]GitHash
need map[GitHash]bool
commit map[GitHash]*GitCommit
numLabelChanges int // incremented (too many times) by meta commits with "Label:" updates
dirtyCL map[*GerritCL]struct{}
// ref are the non-change refs with keys like "HEAD",
// "refs/heads/master", "refs/tags/v0.8.0", etc.
//
// Notably, this excludes the "refs/changes/*" refs matched by
// rxChangeRef. Those are in the remote map.
ref map[string]GitHash
}
// Ref returns a non-change ref, such as "HEAD", "refs/heads/master",
// or "refs/tags/v0.8.0",
// Change refs of the form "refs/changes/*" are not supported.
// The returned hash is the zero value (an empty string) if the ref
// does not exist.
func (gp *GerritProject) Ref(ref string) GitHash {
return gp.ref[ref]
}
func (gp *GerritProject) gitDir() string {
return filepath.Join(gp.gerrit.c.getDataDir(), url.PathEscape(gp.proj))
}
// NumLabelChanges is an inaccurate count the number of times vote labels have
// changed in this project. This number is monotonically increasing.
// This is not guaranteed to be accurate; it definitely overcounts, but it
// at least increments when changes are made.
// It will not undercount.
func (gp *GerritProject) NumLabelChanges() int {
// TODO: rename this method.
return gp.numLabelChanges
}
// ServerSlashProject returns the server and project together, such as
// "go.googlesource.com/build".
func (gp *GerritProject) ServerSlashProject() string { return gp.proj }
// Server returns the Gerrit server, such as "go.googlesource.com".
func (gp *GerritProject) Server() string {
if i := strings.IndexByte(gp.proj, '/'); i != -1 {
return gp.proj[:i]
}
return ""
}
// Project returns the Gerrit project on the server, such as "go" or "crypto".
func (gp *GerritProject) Project() string {
if i := strings.IndexByte(gp.proj, '/'); i != -1 {
return gp.proj[i+1:]
}
return ""
}
// ForeachNonChangeRef calls fn for each git ref on the server that is
// not a change (code review) ref. In general, these correspond to
// submitted changes.
// fn is called serially with sorted ref names.
// Iteration stops with the first non-nil error returned by fn.
func (gp *GerritProject) ForeachNonChangeRef(fn func(ref string, hash GitHash) error) error {
refs := make([]string, 0, len(gp.ref))
for ref := range gp.ref {
refs = append(refs, ref)
}
sort.Strings(refs)
for _, ref := range refs {
if err := fn(ref, gp.ref[ref]); err != nil {
return err
}
}
return nil
}
// ForeachOpenCL calls fn for each open CL in the repo.
//
// If fn returns an error, iteration ends and ForeachOpenCL returns
// with that error.
//
// The fn function is called serially, with increasingly numbered
// CLs.
func (gp *GerritProject) ForeachOpenCL(fn func(*GerritCL) error) error {
var s []*GerritCL
for _, cl := range gp.cls {
if !cl.complete() || cl.Status != "new" || cl.Private {
continue
}
s = append(s, cl)
}
sort.Slice(s, func(i, j int) bool { return s[i].Number < s[j].Number })
for _, cl := range s {
if err := fn(cl); err != nil {
return err
}
}
return nil
}
// ForeachCLUnsorted calls fn for each CL in the repo, in any order.
//
// If fn returns an error, iteration ends and ForeachCLUnsorted returns with
// that error.
func (gp *GerritProject) ForeachCLUnsorted(fn func(*GerritCL) error) error {
for _, cl := range gp.cls {
if !cl.complete() {
continue
}
if err := fn(cl); err != nil {
return err
}
}
return nil
}
// CL returns the GerritCL with the given number, or nil if it is not present.
//
// CL numbers are shared across all projects on a Gerrit server, so you can get
// nil unless you have the GerritProject containing that CL.
func (gp *GerritProject) CL(number int32) *GerritCL {
if cl := gp.cls[number]; cl != nil && cl.complete() {
return cl
}
return nil
}
// GitCommit returns the provided git commit.
func (gp *GerritProject) GitCommit(hash string) (*GitCommit, error) {
if len(hash) != 40 {
// TODO: support prefix lookups. build a trie. But
// for now just avoid panicking in gitHashFromHexStr.
return nil, fmt.Errorf("git hash %q is not 40 characters", hash)
}
var buf [20]byte
_, err := decodeHexStr(buf[:], hash)
if err != nil {
return nil, fmt.Errorf("git hash %q is not a valid hex string: %w", hash, err)
}
c := gp.commit[GitHash(buf[:])]
if c == nil {
// TODO: return an error that the caller can unpack with errors.Is or
// errors.As to distinguish this case.
return nil, fmt.Errorf("git commit %s not found in project", hash)
}
return c, nil
}
func (gp *GerritProject) logf(format string, args ...interface{}) {
log.Printf("gerrit "+gp.proj+": "+format, args...)
}
// gerritCLVersion is a value type used as a map key to store a CL
// number and a patchset version. Its Version field is overloaded
// to reference the "meta" metadata commit if the Version is 0.
type gerritCLVersion struct {
CLNumber int32
Version int32 // version 0 is used for the "meta" ref.
}
// A GerritCL represents a single change in Gerrit.
type GerritCL struct {
// Project is the project this CL is part of.
Project *GerritProject
// Number is the CL number on the Gerrit server (e.g. 1, 2, 3). Gerrit CL
// numbers are sparse (CL N does not guarantee that CL N-1 exists) and
// Gerrit issues CL's out of order - it may issue CL N, then CL (N - 18),
// then CL (N - 40).
Number int32
// Created is the CL creation time.
Created time.Time
// Version is the number of versions of the patchset for this
// CL seen so far. It starts at 1.
Version int32
// Commit is the git commit of the latest version of this CL.
// Previous versions are available via CommitAtVersion.
// Commit is always non-nil.
Commit *GitCommit
// branch is a cache of the latest "Branch: " value seen from
// MetaCommits' commit message values, stripped of any
// "refs/heads/" prefix. It's usually "master".
branch string
// Meta is the head of the most recent Gerrit "meta" commit
// for this CL. This is guaranteed to be a linear history
// back to a CL-specific root commit for this meta branch.
// Meta will always be non-nil.
Meta *GerritMeta
// Metas contains the history of Meta commits, from the oldest (root)
// to the most recent. The last item in the slice is the same
// value as the GerritCL.Meta field.
// The Metas slice will always contain at least 1 element.
Metas []*GerritMeta
// Status will be "merged", "abandoned", "new", or "draft".
Status string
// Private indicates whether this is a private CL.
// Empirically, it seems that one meta commit of private CLs is
// sometimes visible to everybody, even when the rest of the details
// and later meta commits are not. In general, if you see this
// being set to true, treat this CL as if it doesn't exist.
Private bool
// GitHubIssueRefs are parsed references to GitHub issues.
// Multiple references to the same issue are deduplicated.
GitHubIssueRefs []GitHubIssueRef
// Messages contains all of the messages for this CL, in sorted order.
Messages []*GerritMessage
}
// complete reports whether cl is complete.
// A CL is considered complete if its Meta and Commit fields are non-nil,
// and the Metas slice contains at least 1 element.
func (cl *GerritCL) complete() bool {
return cl.Meta != nil &&
len(cl.Metas) >= 1 &&
cl.Commit != nil
}
// GerritMessage is a Gerrit reply that is attached to the CL as a whole, and
// not to a file or line of a patch set.
//
// Maintner does very little parsing or formatting of a Message body. Messages
// are stored the same way they are stored in the API.
type GerritMessage struct {
// Meta is the commit containing the message.
Meta *GitCommit
// Version is the patch set version this message was sent on.
Version int32
// Message is the raw message contents from Gerrit (a subset
// of the raw git commit message), starting with "Patch Set
// nnnn".
Message string
// Date is when this message was stored (the commit time of
// the git commit).
Date time.Time
// Author returns the author of the commit. This takes the form "Gerrit User
// 13437 <13437@62eb7196-b449-3ce5-99f1-c037f21e1705>", where the number
// before the '@' sign is your Gerrit user ID, and the UUID after the '@' sign
// seems to be the same for all commits for the same Gerrit server, across
// projects.
//
// TODO: Merge the *GitPerson object here and for a person's Git commits
// (which use their real email) via the user ID, so they point to the same
// object.
Author *GitPerson
}
// References reports whether cl includes a commit message reference
// to the provided Github issue ref.
func (cl *GerritCL) References(ref GitHubIssueRef) bool {
for _, eref := range cl.GitHubIssueRefs {
if eref == ref {
return true
}
}
return false
}
// Branch returns the CL's branch, with any "refs/heads/" prefix removed.
func (cl *GerritCL) Branch() string { return cl.branch }
func (cl *GerritCL) updateBranch() {
for i := len(cl.Metas) - 1; i >= 0; i-- {
mc := cl.Metas[i]
branch := lineValue(mc.Commit.Msg, "Branch:")
if branch != "" {
cl.branch = strings.TrimPrefix(branch, "refs/heads/")
return
}
}
}
// lineValueOK extracts a value from an RFC 822-style "key: value" series of lines.
// If all is,
//
// foo: bar
// bar: baz
//
// lineValue(all, "foo:") returns "bar". It trims any whitespace.
// The prefix is case sensitive and must include the colon.
// The ok value reports whether a line with such a prefix is found, even if its
// value is empty. If ok is true, the rest value contains the subsequent lines.
func lineValueOK(all, prefix string) (value, rest string, ok bool) {
orig := all
consumed := 0
for {
i := strings.Index(all, prefix)
if i == -1 {
return "", "", false
}
if i > 0 && all[i-1] != '\n' && all[i-1] != '\r' {
all = all[i+len(prefix):]
consumed += i + len(prefix)
continue
}
val := all[i+len(prefix):]
consumed += i + len(prefix)
if nl := strings.IndexByte(val, '\n'); nl != -1 {
consumed += nl + 1
val = val[:nl+1]
} else {
consumed = len(orig)
}
return strings.TrimSpace(val), orig[consumed:], true
}
}
func lineValue(all, prefix string) string {
value, _, _ := lineValueOK(all, prefix)
return value
}
func lineValueRest(all, prefix string) (value, rest string) {
value, rest, _ = lineValueOK(all, prefix)
return
}
// WorkInProgress reports whether the CL has its Work-in-progress bit set, per
// https://gerrit-review.googlesource.com/Documentation/intro-user.html#wip
func (cl *GerritCL) WorkInProgress() bool {
var wip bool
for _, m := range cl.Metas {
switch lineValue(m.Commit.Msg, "Work-in-progress:") {
case "true":
wip = true
case "false":
wip = false
}
}
return wip
}
// ChangeID returns the Gerrit "Change-Id: Ixxxx" line's Ixxxx
// value from the cl.Msg, if any.
func (cl *GerritCL) ChangeID() string {
id := cl.Footer("Change-Id:")
if strings.HasPrefix(id, "I") && len(id) == 41 {
return id
}
return ""
}
// Footer returns the value of a line of the form <key>: value from
// the CL’s commit message. The key is case-sensitive and must end in
// a colon.
// An empty string is returned if there is no value for key.
func (cl *GerritCL) Footer(key string) string {
if len(key) == 0 || key[len(key)-1] != ':' {
panic("Footer key does not end in colon")
}
// TODO: git footers are treated as multimaps. Account for this.
return lineValue(cl.Commit.Msg, key)
}
// OwnerID returns the ID of the CL’s owner. It will return -1 on error.
func (cl *GerritCL) OwnerID() int {
if !cl.complete() {
return -1
}
// Meta commits caused by the owner of a change have an email of the form
// <user id>@<uuid of gerrit server>.
email := cl.Metas[0].Commit.Author.Email()
idx := strings.Index(email, "@")
if idx == -1 {
return -1
}
id, err := strconv.Atoi(email[:idx])
if err != nil {
return -1
}
return id
}
// Owner returns the author of the first commit to the CL. It returns nil on error.
func (cl *GerritCL) Owner() *GitPerson {
// The owner of a change is a numeric ID that can have more than one email
// associated with it, but the email associated with the very first upload is
// designated as the owner of the change by Gerrit.
hash, ok := cl.Project.remote[gerritCLVersion{CLNumber: cl.Number, Version: 1}]
if !ok {
return nil
}
commit, ok := cl.Project.commit[hash]
if !ok {
return nil
}
return commit.Author
}
// Subject returns the subject of the latest commit message.
// The subject is separated from the body by a blank line.
func (cl *GerritCL) Subject() string {
if i := strings.Index(cl.Commit.Msg, "\n\n"); i >= 0 {
return strings.Replace(cl.Commit.Msg[:i], "\n", " ", -1)
}
return strings.Replace(cl.Commit.Msg, "\n", " ", -1)
}
// CommitAtVersion returns the git commit of the specified version of this CL.
// It returns nil if version is not in the range [1, cl.Version].
func (cl *GerritCL) CommitAtVersion(version int32) *GitCommit {
if version < 1 || version > cl.Version {
return nil
}
hash, ok := cl.Project.remote[gerritCLVersion{CLNumber: cl.Number, Version: version}]
if !ok {
return nil
}
return cl.Project.commit[hash]
}
func (cl *GerritCL) updateGithubIssueRefs() {
gp := cl.Project
gerrit := gp.gerrit
gc := cl.Commit
oldRefs := cl.GitHubIssueRefs
newRefs := gerrit.c.parseGithubRefs(gp.proj, gc.Msg)
cl.GitHubIssueRefs = newRefs
for _, ref := range newRefs {
if !clSliceContains(gerrit.clsReferencingGithubIssue[ref], cl) {
// TODO: make this as small as
// possible? Most will have length
// 1. Care about default capacity of
// 2?
gerrit.clsReferencingGithubIssue[ref] = append(gerrit.clsReferencingGithubIssue[ref], cl)
}
}
for _, ref := range oldRefs {
if !cl.References(ref) {
// TODO: remove ref from gerrit.clsReferencingGithubIssue
// It could be a map of maps I suppose, but not as compact.
// So uses a slice as the second layer, since there will normally
// be one item.
}
}
}
// c.mu must be held
func (c *Corpus) initGerrit() {
if c.gerrit != nil {
return
}
c.gerrit = &Gerrit{
c: c,
projects: map[string]*GerritProject{},
clsReferencingGithubIssue: map[GitHubIssueRef][]*GerritCL{},
}
}
type watchedGerritRepo struct {
project *GerritProject
}
// TrackGerrit registers the Gerrit project with the given project as a project
// to watch and append to the mutation log. Only valid in leader mode.
// The provided string should be of the form "hostname/project", without a scheme
// or trailing slash.
func (c *Corpus) TrackGerrit(gerritProj string) {
if c.mutationLogger == nil {
panic("can't TrackGerrit in non-leader mode")
}
c.mu.Lock()
defer c.mu.Unlock()
if strings.Count(gerritProj, "/") != 1 {
panic(fmt.Sprintf("gerrit project argument %q expected to contain exactly 1 slash", gerritProj))
}
c.initGerrit()
if _, dup := c.gerrit.projects[gerritProj]; dup {
panic("duplicated watched gerrit project " + gerritProj)
}
project := c.gerrit.getOrCreateProject(gerritProj)
if project == nil {
panic("gerrit project not created")
}
c.watchedGerritRepos = append(c.watchedGerritRepos, watchedGerritRepo{
project: project,
})
}
// called with c.mu Locked
func (c *Corpus) processGerritMutation(gm *maintpb.GerritMutation) {
if c.gerrit == nil {
// TODO: option to ignore mutation if user isn't interested.
c.initGerrit()
}
gp, ok := c.gerrit.projects[gm.Project]
if !ok {
// TODO: option to ignore mutation if user isn't interested.
// For now, always process the record.
gp = c.gerrit.getOrCreateProject(gm.Project)
}
gp.processMutation(gm)
}
var statusIndicator = "\nStatus: "
// The Go Gerrit site does not really use the "draft" status much, but if
// you need to test it, create a dummy commit and then run
//
// git push origin HEAD:refs/drafts/master
var statuses = []string{"merged", "abandoned", "draft", "new"}
// getGerritStatus returns a Gerrit status for a commit, or the empty string to
// indicate the commit did not show a status.
//
// getGerritStatus relies on the Gerrit code review convention of amending
// the meta commit to include the current status of the CL. The Gerrit search
// bar allows you to search for changes with the following statuses: "open",
// "reviewed", "closed", "abandoned", "merged", "draft", "pending". The REST API
// returns only "NEW", "DRAFT", "ABANDONED", "MERGED". Gerrit attaches "draft",
// "abandoned", "new", and "merged" statuses to some meta commits; you may have
// to search the current meta commit's parents to find the last good commit.
func getGerritStatus(commit *GitCommit) string {
idx := strings.Index(commit.Msg, statusIndicator)
if idx == -1 {
return ""
}
off := idx + len(statusIndicator)
for _, status := range statuses {
if strings.HasPrefix(commit.Msg[off:], status) {
return status
}
}
return ""
}
var errTooManyParents = errors.New("maintner: too many commit parents")
// foreachCommit walks an entire linear git history, starting at commit itself,
// and iterating over all of its parents. commit must be non-nil.
// f is called for each commit until an error is returned from f, or a commit has no parent.
//
// foreachCommit returns errTooManyParents (and stops processing) if a commit
// has more than one parent.
// An error is returned if a commit has a parent that cannot be found.
//
// Corpus.mu must be held.
func (gp *GerritProject) foreachCommit(commit *GitCommit, f func(*GitCommit) error) error {
c := gp.gerrit.c
for {
if err := f(commit); err != nil {
return err
}
if len(commit.Parents) == 0 {
// No parents, we're at the end of the linear history.
return nil
}
if len(commit.Parents) > 1 {
return errTooManyParents
}
parentHash := commit.Parents[0].Hash // meta tree has no merge commits
commit = c.gitCommit[parentHash]
if commit == nil {
return fmt.Errorf("parent commit %v not found", parentHash)
}
}
}
// getGerritMessage parses a Gerrit comment from the given commit or returns nil
// if there wasn't one.
//
// Corpus.mu must be held.
func (gp *GerritProject) getGerritMessage(commit *GitCommit) *GerritMessage {
const existVerPhrase = "\nPatch Set "
const newVerPhrase = "\nUploaded patch set "
startExist := strings.Index(commit.Msg, existVerPhrase)
startNew := strings.Index(commit.Msg, newVerPhrase)
var start int
var phrase string
switch {
case startExist == -1 && startNew == -1:
return nil
case startExist == -1 || (startNew != -1 && startNew < startExist):
phrase = newVerPhrase
start = startNew
case startNew == -1 || (startExist != -1 && startExist < startNew):
phrase = existVerPhrase
start = startExist
}
numStart := start + len(phrase)
colon := strings.IndexByte(commit.Msg[numStart:], ':')
if colon == -1 {
return nil
}
num := commit.Msg[numStart : numStart+colon]
if strings.Contains(num, "\n") || strings.Contains(num, ".") {
// Spanned lines. Didn't match expected comment form
// we care about (comments with vote changes), like:
//
// Uploaded patch set 5: Some-Vote=+2
//
// For now, treat such meta updates (new uploads only)
// as not comments.
return nil
}
version, err := strconv.ParseInt(num, 10, 32)
if err != nil {
gp.logf("for phrase %q at %d, unexpected patch set number in %s; err: %v, message: %s", phrase, start, commit.Hash, err, commit.Msg)
return nil
}
start++
v := commit.Msg[start:]
l := 0
for {
i := strings.IndexByte(v, '\n')
if i < 0 {
return nil
}
if strings.HasPrefix(v[:i], "Patch-set:") {
// two newlines before the Patch-set message
v = commit.Msg[start : start+l-2]
break
}
v = v[i+1:]
l = l + i + 1
}
return &GerritMessage{
Meta: commit,
Author: commit.Author,
Date: commit.CommitTime,
Message: v,
Version: int32(version),
}
}
func reverseGerritMessages(ss []*GerritMessage) {
for i := len(ss)/2 - 1; i >= 0; i-- {
opp := len(ss) - 1 - i
ss[i], ss[opp] = ss[opp], ss[i]
}
}
func reverseGerritMetas(ss []*GerritMeta) {
for i := len(ss)/2 - 1; i >= 0; i-- {
opp := len(ss) - 1 - i
ss[i], ss[opp] = ss[opp], ss[i]
}
}
// called with c.mu Locked
func (gp *GerritProject) processMutation(gm *maintpb.GerritMutation) {
c := gp.gerrit.c
for _, commitp := range gm.Commits {
gc, err := c.processGitCommit(commitp)
if err != nil {
gp.logf("error processing commit %q: %v", commitp.Sha1, err)
continue
}
gp.commit[gc.Hash] = gc
delete(gp.need, gc.Hash)
for _, p := range gc.Parents {
gp.markNeededCommit(p.Hash)
}
}
for _, refName := range gm.DeletedRefs {
delete(gp.ref, refName)
// TODO: this doesn't delete change refs (from
// gp.remote) yet, mostly because those don't tend to
// ever get deleted and we haven't yet needed it. If
// we ever need it, the mutation generation side would
// also need to be updated.
}
for _, refp := range gm.Refs {
refName := refp.Ref
hash := c.gitHashFromHexStr(refp.Sha1)
m := rxChangeRef.FindStringSubmatch(refName)
if m == nil {
if strings.HasPrefix(refName, "refs/meta/") {
// Some of these slipped in to the data
// before we started ignoring them. So ignore them here.
continue
}
// Misc ref, not a change ref.
if _, ok := c.gitCommit[hash]; !ok {
gp.logf("ERROR: non-change ref %v references unknown hash %v; ignoring", refp, hash)
continue
}
gp.ref[refName] = hash
continue
}
clNum64, err := strconv.ParseInt(m[1], 10, 32)
version, ok := gerritVersionNumber(m[2])
if !ok || err != nil {
continue
}
gc, ok := c.gitCommit[hash]
if !ok {
gp.logf("ERROR: ref %v references unknown hash %v; ignoring", refp, hash)
continue
}
clv := gerritCLVersion{int32(clNum64), version}
gp.remote[clv] = hash
cl := gp.getOrCreateCL(clv.CLNumber)
if clv.Version == 0 { // is a meta commit
cl.Meta = newGerritMeta(gc, cl)
gp.noteDirtyCL(cl) // needs processing at end of sync
} else {
cl.Commit = gc
cl.Version = clv.Version
cl.updateGithubIssueRefs()
}
if c.didInit {
gp.logf("Ref %+v => %v", clv, hash)
}
}
}
// noteDirtyCL notes a CL that needs further processing before the corpus
// is returned to the user.
// cl.Meta must be non-nil.
//
// called with Corpus.mu Locked
func (gp *GerritProject) noteDirtyCL(cl *GerritCL) {
if cl.Meta == nil {
panic("noteDirtyCL given a GerritCL with a nil Meta field")
}
if gp.dirtyCL == nil {
gp.dirtyCL = make(map[*GerritCL]struct{})
}
gp.dirtyCL[cl] = struct{}{}
}
// called with Corpus.mu Locked
func (gp *GerritProject) finishProcessing() {
for cl := range gp.dirtyCL {
// All dirty CLs have non-nil Meta, so it's safe to call finishProcessingCL.
gp.finishProcessingCL(cl)
}
gp.dirtyCL = nil
}
// finishProcessingCL fixes up invariants before the cl can be returned back to the user.
// cl.Meta must be non-nil.
//
// called with Corpus.mu Locked
func (gp *GerritProject) finishProcessingCL(cl *GerritCL) {
c := gp.gerrit.c
mostRecentMetaCommit, ok := c.gitCommit[cl.Meta.Commit.Hash]
if !ok {
log.Printf("WARNING: GerritProject(%q).finishProcessingCL failed to find CL %v hash %s",
gp.ServerSlashProject(), cl.Number, cl.Meta.Commit.Hash)
return
}
foundStatus := ""
// Walk from the newest meta commit backwards, so we store the messages
// in reverse order and then flip the array before setting on the
// GerritCL object.
var backwardMessages []*GerritMessage
var backwardMetas []*GerritMeta
err := gp.foreachCommit(mostRecentMetaCommit, func(gc *GitCommit) error {
if strings.Contains(gc.Msg, "\nLabel: ") {
gp.numLabelChanges++
}
if strings.Contains(gc.Msg, "\nPrivate: true\n") {
cl.Private = true
}
if gc.GerritMeta == nil {
gc.GerritMeta = newGerritMeta(gc, cl)
}
if foundStatus == "" {
foundStatus = getGerritStatus(gc)
}
backwardMetas = append(backwardMetas, gc.GerritMeta)
if message := gp.getGerritMessage(gc); message != nil {
backwardMessages = append(backwardMessages, message)
}
return nil
})
if err != nil {
log.Printf("WARNING: GerritProject(%q).finishProcessingCL failed to walk CL %v meta history: %v",
gp.ServerSlashProject(), cl.Number, err)
return
}
if foundStatus != "" {
cl.Status = foundStatus
} else if cl.Status == "" {
cl.Status = "new"
}
reverseGerritMessages(backwardMessages)
cl.Messages = backwardMessages
reverseGerritMetas(backwardMetas)
cl.Metas = backwardMetas
cl.Created = cl.Metas[0].Commit.CommitTime
cl.updateBranch()
}
// clSliceContains reports whether cls contains cl.
func clSliceContains(cls []*GerritCL, cl *GerritCL) bool {
for _, v := range cls {
if v == cl {
return true
}
}
return false
}
// c.mu must be held
func (gp *GerritProject) markNeededCommit(hash GitHash) {
if _, ok := gp.commit[hash]; ok {
// Already have it.
return
}
gp.need[hash] = true
}
// c.mu must be held
func (gp *GerritProject) getOrCreateCL(num int32) *GerritCL {
cl, ok := gp.cls[num]
if ok {
return cl
}
cl = &GerritCL{
Project: gp,
Number: num,
}
gp.cls[num] = cl
return cl
}
func gerritVersionNumber(s string) (version int32, ok bool) {
if s == "meta" {
return 0, true
}
v, err := strconv.ParseInt(s, 10, 32)
if err != nil {
return 0, false
}
return int32(v), true
}
// rxRemoteRef matches "git ls-remote" lines.
//
// sample row:
// fd1e71f1594ce64941a85428ddef2fbb0ad1023e refs/changes/99/30599/3
//
// Capture values:
//
// $0: whole match
// $1: "fd1e71f1594ce64941a85428ddef2fbb0ad1023e"
// $2: "30599" (CL number)
// $3: "1", "2" (patchset number) or "meta" (a/ special commit
// holding the comments for a commit)
//
// The "99" in the middle covers all CL's that end in "99", so
// refs/changes/99/99/1, refs/changes/99/199/meta.
var rxRemoteRef = regexp.MustCompile(`^([0-9a-f]{40,})\s+refs/changes/[0-9a-f]{2}/([0-9]+)/(.+)$`)
// $1: change num
// $2: version or "meta"
var rxChangeRef = regexp.MustCompile(`^refs/changes/[0-9a-f]{2}/([0-9]+)/(meta|(?:\d+))`)
func (gp *GerritProject) sync(ctx context.Context, loop bool) error {
if err := gp.init(ctx); err != nil {
gp.logf("init: %v", err)
return err
}
activityCh := gp.gerrit.c.activityChan("gerrit:" + gp.proj)
for {
if err := gp.syncOnce(ctx); err != nil {
if ee, ok := err.(*exec.ExitError); ok {
err = fmt.Errorf("%v; stderr=%q", err, ee.Stderr)
}
gp.logf("sync: %v", err)
return err
}
if !loop {
return nil
}
timer := time.NewTimer(5 * time.Minute)
select {
case <-ctx.Done():
timer.Stop()