This repository has been archived by the owner on Sep 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdatecontrib.go
474 lines (434 loc) · 13 KB
/
updatecontrib.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
// Copyright 2019 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 updateac command updates the CONTRIBUTORS file in the Go repository.
//
// This binary should be run at the top of GOROOT.
// It will try to fetch and update a bunch of subrepos in your GOPATH workspace,
// whose location is determined by running go env GOPATH.
package main // import "github.com/gortc/updatecontrib"
import (
"bufio"
"bytes"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"sort"
"strings"
"golang.org/x/text/collate"
"golang.org/x/text/language"
)
// TODO: automatically use Gerrit names like we do with GitHub
func main() {
log.SetFlags(0)
flag.Usage = func() {
fmt.Fprint(os.Stderr, `Usage:
$ cd $(gotip env GOROOT)
$ updateac
`)
flag.PrintDefaults()
}
flag.Parse()
dir, err := os.Getwd()
if err != nil {
panic(err)
}
repos = append(repos, filepath.Base(dir))
all := gitAuthorEmails() // call first (it will reset CONTRIBUTORS)
c := file("CONTRIBUTORS")
var actions, warnings, errors bytes.Buffer
for _, who := range all {
// Skip exact emails that are present in CONTRIBUTORS file.
if c.Contains(&acLine{email: who.email}) {
continue
}
if !validName(who.name) {
ghUser, err := FetchGitHubInfo(who)
if err != nil {
fmt.Fprintf(&errors, "Error fetching GitHub name for %s: %v\n", who.Debug(), err)
continue
}
if ghUser == nil {
fmt.Fprintf(&warnings, "There is no GitHub user associated with %s, skipping\n", who.Debug())
continue
}
if validName(ghUser.Name) {
// Use the GitHub name since it looks valid.
fmt.Fprintf(&actions, "Used GitHub name %q for %s\n", ghUser.Name, who.Debug())
who.name = ghUser.Name
} else if (ghUser.Name == ghUser.Login || ghUser.Name == "") && who.name == ghUser.Login {
// Special case: if the GitHub name is the same as the GitHub username or empty,
// and who.name is the GitHub username, then use "GitHub User @<username> (<ID>)" form.
fmt.Fprintf(&actions, "Used GitHub User @%s (%d) form for %s\n", ghUser.Login, ghUser.ID, who.Debug())
who.name = fmt.Sprintf("GitHub User @%s (%d)", ghUser.Login, ghUser.ID)
} else {
fmt.Fprintf(&warnings, "Found invalid-looking name %q for GitHub user @%s, skipping %v\n", ghUser.Name, ghUser.Login, who.Debug())
continue
}
}
who.name = strings.TrimSpace(who.name)
if !c.Contains(who) {
c.addLine(who)
fmt.Fprintf(&actions, "Added %s <%s>\n", who.name, who.firstEmail())
} else {
// The name exists, but with a different email. We don't update lines automatically. (TODO)
// We'll need to update "GitHub User" names when they provide a better one.
}
}
if actions.Len() > 0 {
fmt.Println("Actions taken (relative to CONTRIBUTORS at origin/master):")
lines := strings.SplitAfter(actions.String(), "\n")
sort.Strings(lines)
os.Stdout.WriteString(strings.Join(lines, ""))
}
if err = sortACFile("CONTRIBUTORS"); err != nil {
log.Fatalf("Error sorting CONTRIBUTORS file: %v", err)
}
if errors.Len() > 0 {
log.Printf("\nExiting with errors:")
lines := strings.SplitAfter(errors.String(), "\n")
sort.Strings(lines)
os.Stderr.WriteString(strings.Join(lines, ""))
os.Exit(1)
}
if warnings.Len() > 0 {
log.Printf("\nExiting with warnings:")
lines := strings.SplitAfter(warnings.String(), "\n")
sort.Strings(lines)
os.Stderr.WriteString(strings.Join(lines, ""))
}
}
// validName is meant to reject most invalid names with a simple rule, and a whitelist.
func validName(name string) bool {
if valid, ok := validNames[name]; ok {
return valid
}
return strings.Contains(name, " ")
}
type acFile struct {
name string
lines []*acLine
byEmail map[string]*acLine // emailNorm(email) to line
byName map[string]*acLine // nameNorm(name) to line
}
func (f *acFile) Contains(who *acLine) bool {
for _, email := range who.email {
if _, ok := f.byEmail[emailNorm(email)]; ok {
return true
}
}
if who.name != "" {
if _, ok := f.byName[nameNorm(who.name)]; ok {
return true
}
}
return false
}
func emailNorm(e string) string {
return strings.Replace(strings.ToLower(e), ".", "", -1)
}
func nameNorm(e string) string {
return strings.Replace(strings.Replace(strings.ToLower(e), ".", "", -1), ",", "", -1)
}
func (f *acFile) addLine(line *acLine) {
of, err := os.OpenFile(f.name, os.O_WRONLY|os.O_APPEND, 0)
if err != nil {
log.Fatal(err)
}
if _, err := io.WriteString(of, line.String()); err != nil {
log.Fatal(err)
}
if err := of.Close(); err != nil {
log.Fatal(err)
}
f.recordLine(line)
}
func (f *acFile) recordLine(ln *acLine) {
for _, email := range ln.email {
if _, ok := f.byEmail[emailNorm(email)]; !ok {
f.byEmail[emailNorm(email)] = ln
} else {
// TODO: print for debugging, shouldn't happen
}
}
if _, ok := f.byName[nameNorm(ln.name)]; !ok {
f.byName[nameNorm(ln.name)] = ln
} else {
// TODO: print for debugging, shouldn't happen
}
f.lines = append(f.lines, ln)
}
type acLine struct {
name string
email []string
repos map[string]bool
firstRepo string
firstCommit string
}
func (w *acLine) firstEmail() string {
if len(w.email) > 0 {
return w.email[0]
}
return ""
}
func (w *acLine) String() string {
line := w.name
for _, email := range w.email {
line += fmt.Sprintf(" <%s>", email)
}
line += "\n"
return line
}
func (w *acLine) Debug() string {
repos := make([]string, 0, len(w.repos))
for k := range w.repos {
k = path.Base(k)
repos = append(repos, k)
}
githubOrg, githubRepo := githubOrgRepo(w.firstRepo)
email := w.firstEmail()
if len(w.email) > 1 {
email = fmt.Sprint(w.email)
}
sort.Strings(repos)
return fmt.Sprintf("%s <%s> https://github.com/%s/%s/commit/%s %v", w.name, email,
githubOrg, githubRepo, w.firstCommit, repos)
}
var emailRx = regexp.MustCompile(`<[^>]+>`)
func file(name string) *acFile {
f, err := os.Open(name)
if err != nil {
log.Fatal(err)
}
defer f.Close()
s := bufio.NewScanner(f)
acf := &acFile{
name: name,
byName: make(map[string]*acLine),
byEmail: make(map[string]*acLine),
}
for s.Scan() {
t := strings.TrimSpace(s.Text())
if t == "" || t[0] == '#' {
continue
}
ln := new(acLine)
ln.name = strings.TrimSpace(emailRx.ReplaceAllStringFunc(t, func(email string) string {
email = strings.Trim(email, "<>")
ln.email = append(ln.email, email)
return ""
}))
acf.recordLine(ln)
}
if err := s.Err(); err != nil {
log.Fatal(err)
}
return acf
}
// repos is a list of all the repositories that are fetched (if missing),
// updated, and used to find contributors to add to the CONTRIBUTORS file.
// It includes "go", which represents the main Go repository,
// and an import path corresponding to each subrepository root.
var repos = []string{}
// githubOrgRepo takes an import path (from the forms in the repos global variable)
// and returns the GitHub org and repo.
func githubOrgRepo(repo string) (githubOrg, githubRepo string) {
return "gortc", repo
}
func gitAuthorEmails() []*acLine {
var ret []*acLine
seen := map[string]map[string]bool{} // email -> repo -> true
for _, repo := range repos {
log.Printf("Processing repo: %s", repo)
dir := ""
cmd := exec.Command("git", "fetch")
cmd.Dir = dir
//if out, err := cmd.CombinedOutput(); err != nil {
// log.Fatalf("Error updating repo %q: %v, %s", repo, err, out)
//}
// Initialize CONTRIBUTORS file to latest copy from origin/master.
//exec.Command("git", "checkout", "origin/master", "--", "CONTRIBUTORS").Run()
//exec.Command("git", "reset").Run()
cmd = exec.Command("git", "log", "--format=%ae/%h/%an", "origin/master") //, "HEAD@{5 years ago}..HEAD")
cmd.Dir = dir
cmd.Stderr = os.Stderr
out, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
s := bufio.NewScanner(out)
for s.Scan() {
line := s.Text()
f := strings.SplitN(line, "/", 3)
email, commit, name := f[0], f[1], f[2]
if uselessCommit(commit) {
continue
}
for _, phrase := range debugPeople {
if strings.Contains(line, phrase) {
log.Printf("DEBUG(%q): Repo %q, email %q, commit %s, name %q", phrase, repo, email, commit, name)
}
}
if skipEmail[email] {
continue
}
if v, ok := emailFix[email]; ok {
email = v
}
if v, ok := nameFix[name]; ok {
name = v
}
if userRepos, first := seen[email]; !first {
userRepos = map[string]bool{repo: true}
seen[email] = userRepos
ret = append(ret, &acLine{
name: name,
email: []string{email},
repos: userRepos,
firstRepo: repo,
firstCommit: commit,
})
} else {
userRepos[repo] = true
}
}
if err := s.Err(); err != nil {
log.Fatal(err)
}
if err := cmd.Wait(); err != nil {
log.Fatal(err)
}
}
log.Printf("Done processing all repos.")
log.Println()
return ret
}
// goPath returns the output of running go env GOPATH.
func goPath() (string, error) {
out, err := exec.Command("go", "env", "GOPATH").Output()
if err != nil {
return "", err
}
goPath := string(bytes.TrimSpace(out))
if goPath == "" {
return "", fmt.Errorf("no GOPATH")
}
return goPath, nil
}
// sortACFile sorts the named file in place.
func sortACFile(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
sorted, err := sortAC(f)
f.Close()
if err != nil {
return err
}
err = ioutil.WriteFile(path, sorted, 0644)
return err
}
func sortAC(r io.Reader) ([]byte, error) {
bs := bufio.NewScanner(r)
var header []string
var lines []string
for bs.Scan() {
t := bs.Text()
lines = append(lines, t)
if t == "# Please keep the list sorted." {
header = lines
lines = nil
continue
}
}
if err := bs.Err(); err != nil {
return nil, err
}
var out bytes.Buffer
c := collate.New(language.Und, collate.Loose)
c.SortStrings(lines)
for _, l := range header {
fmt.Fprintln(&out, l)
}
for _, l := range lines {
fmt.Fprintln(&out, l)
}
return out.Bytes(), nil
}
func uselessCommit(commit string) bool {
switch commit[:7] {
case "0d51c71":
// I (Brad) forgot to accept a CLA for typo?
// https://github.com/golang/net/commit/0d51c71
return true
case "ad051cf":
// I (Brad) forgot to accept a CLA for typo? 2014.
// https://github.com/golang/oauth2/commit/ad051cf
return true
case "661ac69", "fd68af8", "b036f29":
// Motorola sent but never did CLA so it was reverted.
return true
case "a51e4cc":
// khr <[email protected]> https://github.com/golang/go/commit/a51e4cc9ce
return true
case "198c542":
// adg forgot to check CLA, before the Google CLA bot handled it?
// Load proxy variables from the environment
// https://github.com/golang/gddo/pull/200
return true
case "2cfa4c7":
// nf (adg) forgot to check CLA, before the Google CLA bot handled it?
// https://github.com/golang/gddo/pull/156
return true
case "834a0af":
// garyburd never checked CLA, prior to Google taking over the project (no CLA checks then)
// https://github.com/golang/gddo/pull/105
return true
case "da10956":
// Actually useless contribution, but no CLA on file under either Owner nor Author mail:
// https://code-review.googlesource.com/#/c/2930/
// https://github.com/GoogleCloudPlatform/google-cloud-go/commit/da10956
return true
case "0b6b69c":
// googlebot approved it, but we can't find the record. Small change.
// https://github.com/golang/crypto/pull/35
// https://groups.google.com/a/google.com/d/msg/signcla-users/qpX9Z10YjQI/zjpEBmt_BgAJ
return true
}
return false
}
var skipEmail = map[string]bool{
"[email protected]": true,
// Easter egg commits.
"[email protected]": true,
"research!bwk": true,
"bwk": true,
"[email protected]": true,
}
// TODO(dmitshur): Use golang.org/x/build/internal/gophers package to perform some of
// the name and email fixes, eliminating the need for current entries in nameFix and emailFix.
// nameFix is a map of name -> new name replacements to make.
// For example, "named Gopher": "Named Gopher".
var nameFix = map[string]string{
"Emmanuel T Odeke": "Emmanuel Odeke", // to prevent a duplicate "Emmanuel T Odeke <[email protected]>" entry, since "Emmanuel Odeke <[email protected]> <[email protected]>" already exists
"fREW Schmidt": "Frew Schmidt", // to use a normalized name capitalization, based on seeing it used on Medium and LinkedIn
}
// emailFix is a map of email -> new email replacements to make.
// For example, "[email protected]": "[email protected]".
var emailFix = map[string]string{
"[email protected]": "[email protected]", // to prevent a duplicate "GitHub User @haya14busa (3797062) <[email protected]>" entry, since "Toshiki Shima <[email protected]>" already exists
"[email protected]": "[email protected]", // to prevent a duplicate "Stephen L <[email protected]>" entry, since "Stephen Lu <[email protected]>" already exists
}
var validNames = map[string]bool{}
var debugPeople = []string{}