forked from golang/build
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgit.go
573 lines (528 loc) · 14.2 KB
/
git.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
// 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 (
"bufio"
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"log"
"os/exec"
"sort"
"strconv"
"strings"
"time"
"golang.org/x/build/internal/foreach"
"golang.org/x/build/maintner/maintpb"
)
// GitHash is a git commit in binary form (NOT hex form).
// They are currently always 20 bytes long. (for SHA-1 refs)
// That may change in the future.
type GitHash string
func (h GitHash) String() string { return fmt.Sprintf("%x", string(h)) }
// requires c.mu be held for writing
func (c *Corpus) gitHashFromHexStr(s string) GitHash {
if len(s) != 40 {
panic(fmt.Sprintf("bogus git hash %q", s))
}
var buf [40]byte
copy(buf[:], s)
_, err := hex.Decode(buf[:20], buf[:]) // aliasing is safe
if err != nil {
panic(fmt.Sprintf("bogus git hash %q: %v", s, err))
}
return GitHash(c.strb(buf[:20]))
}
// requires c.mu be held for writing
func (c *Corpus) gitHashFromHex(s []byte) GitHash {
if len(s) != 40 {
panic(fmt.Sprintf("bogus git hash %q", s))
}
var buf [20]byte
_, err := hex.Decode(buf[:], s)
if err != nil {
panic(fmt.Sprintf("bogus git hash %q: %v", s, err))
}
return GitHash(c.strb(buf[:20]))
}
// placeholderCommitter is a sentinel value for GitCommit.Committer to
// mean that the GitCommit is a placeholder. It's used for commits we
// know should exist (because they're referenced as parents) but we
// haven't yet seen in the log.
var placeholderCommitter = new(GitPerson)
// GitCommit represents a single commit in a git repository.
type GitCommit struct {
Hash GitHash
Tree GitHash
Parents []*GitCommit
Author *GitPerson
AuthorTime time.Time
Committer *GitPerson
Reviewer *GitPerson
CommitTime time.Time
Msg string // Commit message subject and body
Files []*maintpb.GitDiffTreeFile
GerritMeta *GerritMeta // non-nil if it's a Gerrit NoteDB meta commit
}
func (gc *GitCommit) String() string {
if gc == nil {
return "<nil *GitCommit>"
}
return fmt.Sprintf("{GitCommit %s}", gc.Hash)
}
// HasAncestor reports whether gc contains the provided ancestor
// commit in gc's history.
func (gc *GitCommit) HasAncestor(ancestor *GitCommit) bool {
return gc.hasAncestor(ancestor, make(map[*GitCommit]bool))
}
func (gc *GitCommit) hasAncestor(ancestor *GitCommit, checked map[*GitCommit]bool) bool {
if v, ok := checked[gc]; ok {
return v
}
checked[gc] = false
for _, pc := range gc.Parents {
if pc == nil {
panic("nil parent")
}
if pc.Committer == placeholderCommitter {
log.Printf("WARNING: hasAncestor(%q, %q) found parent %q with placeholder parent", gc.Hash, ancestor.Hash, pc.Hash)
}
if pc.Hash == ancestor.Hash || pc.hasAncestor(ancestor, checked) {
checked[gc] = true
return true
}
}
return false
}
// Summary returns the first line of the commit message.
func (gc *GitCommit) Summary() string {
s := gc.Msg
if i := strings.IndexByte(s, '\n'); i != -1 {
s = s[:i]
}
s = strings.TrimSpace(s)
return s
}
// SameDiffStat reports whether gc has the same diff stat numbers as b.
// If either is unknown, false is returned.
func (gc *GitCommit) SameDiffStat(b *GitCommit) bool {
if len(gc.Files) != len(b.Files) {
return false
}
for i, af := range gc.Files {
bf := b.Files[i]
if af == nil || bf == nil {
return false
}
if *af != *bf {
return false
}
}
return true
}
// GitPerson is a person in a git commit.
type GitPerson struct {
Str string // "Foo Bar <[email protected]>"
}
// Email returns the GitPerson's email address only, without the name
// or angle brackets.
func (p *GitPerson) Email() string {
lt := strings.IndexByte(p.Str, '<')
gt := strings.IndexByte(p.Str, '>')
if lt < 0 || gt < lt {
return ""
}
return p.Str[lt+1 : gt]
}
func (p *GitPerson) Name() string {
i := strings.IndexByte(p.Str, '<')
if i < 0 {
return p.Str
}
return strings.TrimSpace(p.Str[:i])
}
// String implements fmt.Stringer.
func (p *GitPerson) String() string { return p.Str }
// requires c.mu be held for writing.
func (c *Corpus) enqueueCommitLocked(h GitHash) {
if _, ok := c.gitCommit[h]; ok {
return
}
if c.gitCommitTodo == nil {
c.gitCommitTodo = map[GitHash]bool{}
}
c.gitCommitTodo[h] = true
}
// syncGitCommits polls for git commits in a directory.
func (c *Corpus) syncGitCommits(ctx context.Context, conf polledGitCommits, loop bool) error {
cmd := exec.CommandContext(ctx, "git", "show-ref", "refs/remotes/origin/master")
cmd.Dir = conf.dir
out, err := cmd.Output()
if err != nil {
log.Fatal(err)
}
outs := strings.TrimSpace(string(out))
if outs == "" {
return fmt.Errorf("no remote found for refs/remotes/origin/master")
}
ref := strings.Fields(outs)[0]
c.mu.Lock()
refHash := c.gitHashFromHexStr(ref)
c.enqueueCommitLocked(refHash)
c.mu.Unlock()
idle := false
for {
hash := c.gitCommitToIndex()
if hash == "" {
if !loop {
return nil
}
if !idle {
log.Printf("All git commits index for %v; idle.", conf.repo)
idle = true
}
time.Sleep(5 * time.Second)
continue
}
if err := c.indexCommit(conf, hash); err != nil {
log.Printf("Error indexing %v: %v", hash, err)
select {
case <-ctx.Done():
return ctx.Err()
// TODO: temporary vs permanent failure? reschedule? fail hard?
// For now just loop with a sleep.
case <-time.After(5 * time.Second):
}
}
}
}
// returns nil if no work.
func (c *Corpus) gitCommitToIndex() GitHash {
c.mu.RLock()
defer c.mu.RUnlock()
for hash := range c.gitCommitTodo {
if _, ok := c.gitCommit[hash]; !ok {
return hash
}
log.Printf("Warning: git commit %v in todo map, but already known; ignoring", hash)
}
return ""
}
var (
nlnl = []byte("\n\n")
parentSpace = []byte("parent ")
authorSpace = []byte("author ")
committerSpace = []byte("committer ")
treeSpace = []byte("tree ")
golangHgSpace = []byte("golang-hg ")
gpgSigSpace = []byte("gpgsig ")
encodingSpace = []byte("encoding ")
space = []byte(" ")
)
func parseCommitFromGit(dir string, hash GitHash) (*maintpb.GitCommit, error) {
cmd := exec.Command("git", "cat-file", "commit", hash.String())
cmd.Dir = dir
catFile, err := cmd.Output()
if err != nil {
return nil, fmt.Errorf("git cat-file -p %v: %v", hash, err)
}
cmd = exec.Command("git", "diff-tree", "--numstat", hash.String())
cmd.Dir = dir
diffTreeOut, err := cmd.Output()
if err != nil {
return nil, fmt.Errorf("git diff-tree --numstat %v: %v", hash, err)
}
diffTree := &maintpb.GitDiffTree{}
bs := bufio.NewScanner(bytes.NewReader(diffTreeOut))
lineNum := 0
for bs.Scan() {
line := strings.TrimSpace(bs.Text())
lineNum++
if lineNum == 1 && line == hash.String() {
continue
}
f := strings.Fields(line)
// A line is like: <added> WS+ <deleted> WS+ <filename>
// Where <added> or <deleted> can be '-' to mean binary.
// The filename could contain spaces.
// 49 8 maintner/maintner.go
// Or:
// 49 8 some/name with spaces.txt
if len(f) < 3 {
continue
}
binary := f[0] == "-" || f[1] == "-"
added, _ := strconv.ParseInt(f[0], 10, 64)
deleted, _ := strconv.ParseInt(f[1], 10, 64)
file := strings.TrimPrefix(line, f[0])
file = strings.TrimSpace(file)
file = strings.TrimPrefix(file, f[1])
file = strings.TrimSpace(file)
diffTree.File = append(diffTree.File, &maintpb.GitDiffTreeFile{
File: file,
Added: added,
Deleted: deleted,
Binary: binary,
})
}
if err := bs.Err(); err != nil {
return nil, err
}
commit := &maintpb.GitCommit{
Raw: catFile,
DiffTree: diffTree,
}
switch len(hash) {
case 20:
commit.Sha1 = hash.String()
default:
return nil, fmt.Errorf("unsupported git hash %q", hash.String())
}
return commit, nil
}
func (c *Corpus) indexCommit(conf polledGitCommits, hash GitHash) error {
if conf.repo == nil {
panic("bogus config; nil repo")
}
commit, err := parseCommitFromGit(conf.dir, hash)
if err != nil {
return err
}
m := &maintpb.Mutation{
Git: &maintpb.GitMutation{
Repo: conf.repo,
Commit: commit,
},
}
c.addMutation(m)
return nil
}
// c.mu is held for writing.
func (c *Corpus) processGitMutation(m *maintpb.GitMutation) {
commit := m.Commit
if commit == nil {
return
}
// TODO: care about m.Repo?
c.processGitCommit(commit)
}
// c.mu is held for writing.
func (c *Corpus) processGitCommit(commit *maintpb.GitCommit) (*GitCommit, error) {
if c.gitCommit == nil {
c.gitCommit = map[GitHash]*GitCommit{}
}
if len(commit.Sha1) != 40 {
return nil, fmt.Errorf("bogus git sha1 %q", commit.Sha1)
}
hash := c.gitHashFromHexStr(commit.Sha1)
catFile := commit.Raw
i := bytes.Index(catFile, nlnl)
if i == 0 {
return nil, fmt.Errorf("commit %v lacks double newline", hash)
}
hdr, msg := catFile[:i], catFile[i+2:]
gc := &GitCommit{
Hash: hash,
Parents: make([]*GitCommit, 0, bytes.Count(hdr, parentSpace)),
Msg: c.strb(msg),
}
// The commit message contains the reviewer email address. Sample commit message:
// Update patch set 1
//
// Patch Set 1: Code-Review+2
//
// Patch-set: 1
// Reviewer: Ian Lance Taylor <5206@62eb7196-b449-3ce5-99f1-c037f21e1705>
// Label: Code-Review=+2
if reviewer := lineValue(c.strb(msg), "Reviewer: "); reviewer != "" {
gc.Reviewer = &GitPerson{Str: reviewer}
}
if commit.DiffTree != nil {
gc.Files = commit.DiffTree.File
}
for _, f := range gc.Files {
f.File = c.str(f.File) // intern the string
}
sort.Slice(gc.Files, func(i, j int) bool { return gc.Files[i].File < gc.Files[j].File })
parents := 0
err := foreach.Line(hdr, func(ln []byte) error {
if bytes.HasPrefix(ln, parentSpace) {
parents++
parentHash := c.gitHashFromHex(ln[len(parentSpace):])
parent := c.gitCommit[parentHash]
if parent == nil {
// Install a placeholder to be filled in later.
parent = &GitCommit{
Hash: parentHash,
Committer: placeholderCommitter,
}
c.gitCommit[parentHash] = parent
}
gc.Parents = append(gc.Parents, parent)
c.enqueueCommitLocked(parentHash)
return nil
}
if bytes.HasPrefix(ln, authorSpace) {
p, t, err := c.parsePerson(ln[len(authorSpace):])
if err != nil {
return fmt.Errorf("unrecognized author line %q: %v", ln, err)
}
gc.Author = p
gc.AuthorTime = t
return nil
}
if bytes.HasPrefix(ln, committerSpace) {
p, t, err := c.parsePerson(ln[len(committerSpace):])
if err != nil {
return fmt.Errorf("unrecognized committer line %q: %v", ln, err)
}
gc.Committer = p
gc.CommitTime = t
return nil
}
if bytes.HasPrefix(ln, treeSpace) {
gc.Tree = c.gitHashFromHex(ln[len(treeSpace):])
return nil
}
if bytes.HasPrefix(ln, golangHgSpace) {
if c.gitOfHg == nil {
c.gitOfHg = map[string]GitHash{}
}
c.gitOfHg[string(ln[len(golangHgSpace):])] = hash
return nil
}
if bytes.HasPrefix(ln, gpgSigSpace) || bytes.HasPrefix(ln, space) {
// Jessie Frazelle is a unique butterfly.
return nil
}
if bytes.HasPrefix(ln, encodingSpace) {
// Also ignore this. In practice this has only
// been seen to declare that a commit's
// metadata is utf-8 when the author name has
// non-ASCII.
return nil
}
log.Printf("in commit %s, unrecognized line %q", hash, ln)
return nil
})
if err != nil {
log.Printf("Unparseable commit %q: %v", hash, err)
return nil, fmt.Errorf("Unparseable commit %q: %v", hash, err)
}
if ph, ok := c.gitCommit[hash]; ok {
// Update placeholder.
*ph = *gc
} else {
c.gitCommit[hash] = gc
}
if c.gitCommitTodo != nil {
delete(c.gitCommitTodo, hash)
}
if c.verbose {
now := time.Now()
if now.After(c.lastGitCount.Add(time.Second)) {
c.lastGitCount = now
log.Printf("Num git commits = %v", len(c.gitCommit))
}
}
return gc, nil
}
// parsePerson parses an "author" or "committer" value from "git cat-file -p COMMIT"
// The values are like:
// Foo Bar <[email protected]> 1488624439 +0900
// c.mu must be held for writing.
func (c *Corpus) parsePerson(v []byte) (*GitPerson, time.Time, error) {
v = bytes.TrimSpace(v)
lastSpace := bytes.LastIndexByte(v, ' ')
if lastSpace < 0 {
return nil, time.Time{}, errors.New("failed to match person")
}
tz := v[lastSpace+1:] // "+0800"
v = v[:lastSpace] // now v is "Foo Bar <[email protected]> 1488624439"
lastSpace = bytes.LastIndexByte(v, ' ')
if lastSpace < 0 {
return nil, time.Time{}, errors.New("failed to match person")
}
unixTime := v[lastSpace+1:]
nameEmail := v[:lastSpace] // now v is "Foo Bar <[email protected]>"
ut, err := strconv.ParseInt(string(unixTime), 10, 64)
if err != nil {
return nil, time.Time{}, err
}
t := time.Unix(ut, 0).In(c.gitLocation(tz))
p, ok := c.gitPeople[string(nameEmail)]
if !ok {
p = &GitPerson{Str: string(nameEmail)}
if c.gitPeople == nil {
c.gitPeople = map[string]*GitPerson{}
}
c.gitPeople[p.Str] = p
}
return p, t, nil
}
// GitCommit returns the provided git commit, or nil if it's unknown.
func (c *Corpus) GitCommit(hash string) *GitCommit {
if len(hash) != 40 {
// TODO: support prefix lookups. build a trie. But
// for now just avoid panicking in gitHashFromHexStr.
return nil
}
var buf [20]byte
_, err := decodeHexStr(buf[:], hash)
if err != nil {
return nil
}
return c.gitCommit[GitHash(buf[:])]
}
// v is like '[+-]hhmm'
// c.mu must be held for writing.
func (c *Corpus) gitLocation(v []byte) *time.Location {
if loc, ok := c.zoneCache[string(v)]; ok {
return loc
}
s := string(v)
h, _ := strconv.Atoi(s[1:3])
m, _ := strconv.Atoi(s[3:5])
east := 1
if v[0] == '-' {
east = -1
}
loc := time.FixedZone(s, east*(h*3600+m*60))
if c.zoneCache == nil {
c.zoneCache = map[string]*time.Location{}
}
c.zoneCache[s] = loc
return loc
}
func decodeHexStr(dst []byte, src string) (int, error) {
if len(src)%2 == 1 {
return 0, hex.ErrLength
}
for i := 0; i < len(src)/2; i++ {
a, ok := fromHexChar(src[i*2])
if !ok {
return 0, hex.InvalidByteError(src[i*2])
}
b, ok := fromHexChar(src[i*2+1])
if !ok {
return 0, hex.InvalidByteError(src[i*2+1])
}
dst[i] = (a << 4) | b
}
return len(src) / 2, nil
}
// fromHexChar converts a hex character into its value and a success flag.
func fromHexChar(c byte) (byte, bool) {
switch {
case '0' <= c && c <= '9':
return c - '0', true
case 'a' <= c && c <= 'f':
return c - 'a' + 10, true
case 'A' <= c && c <= 'F':
return c - 'A' + 10, true
}
return 0, false
}