-
Notifications
You must be signed in to change notification settings - Fork 8
/
author.go
100 lines (84 loc) · 2.19 KB
/
author.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
// Copyright 2018 Atelier Disko. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
const (
AuthorsConfigBasename = "AUTHORS.txt"
)
func NewAuthorsFromFile(path string) (*Authors, error) {
as := &Authors{}
f, err := os.Open(path)
defer f.Close()
if err != nil {
return as, err
}
return as, as.AddFrom(f)
}
type Authors struct {
data []*Author
}
type Author struct {
Email string
Name string
}
// Parses given file and adds authors to the internal data.
// Extracts author information from AUTHORS.txt files in mailmap
// format. Currently supports the simple syntax only.
//
// See: https://github.com/git/git/blob/master/Documentation/mailmap.txt
func (as *Authors) AddFrom(r io.Reader) error {
parsed, err := as.parse(r)
if err != nil {
return err
}
for _, a := range parsed {
as.data = append(as.data, a)
}
return nil
}
// Parse lines looking like this:
// Proper Name <[email protected]>
// # this is a comment
// Proper Name <[email protected]> # inline comment
func (as Authors) parse(r io.Reader) ([]*Author, error) {
var parsed []*Author
lineScanner := bufio.NewScanner(r)
for lineScanner.Scan() {
line := strings.TrimSpace(lineScanner.Text())
if line == "" {
continue
}
if strings.HasPrefix(line, "#") {
continue
}
inlineComment := strings.Index(line, "#")
beginMail := strings.Index(line, "<")
if beginMail == -1 || (inlineComment != -1 && inlineComment < beginMail) {
return parsed, fmt.Errorf("expected opening angle bracket in line '%s'", line)
}
endMail := strings.LastIndex(line, ">")
if endMail == -1 || (inlineComment != -1 && inlineComment < endMail) {
return parsed, fmt.Errorf("expected closing angle bracket in line '%s'", line)
}
name := strings.TrimSpace(line[0 : beginMail-1])
email := strings.TrimSpace(line[beginMail+1 : len(line)-1])
parsed = append(parsed, &Author{email, name})
}
return parsed, nil
}
func (as Authors) Get(email string) (ok bool, a *Author, err error) {
for _, a := range as.data {
if a.Email == email {
return true, a, nil
}
}
return false, &Author{}, nil
}