|
1 | 1 | // Package codeowners provides funcionality to evaluate CODEOWNERS file. |
2 | 2 | package codeowners // import "github.com/fmenezes/codeowners" |
3 | 3 |
|
4 | | -import ( |
5 | | - "bufio" |
6 | | - "io" |
7 | | - "strings" |
8 | | -) |
9 | | - |
10 | 4 | // DefaultLocations provides default locations for the CODEOWNERS file |
11 | 5 | var DefaultLocations = [...]string{"CODEOWNERS", "docs/CODEOWNERS", ".github/CODEOWNERS"} |
12 | | - |
13 | | -// Decoder providers functionality to read CODEOWNERS data |
14 | | -type Decoder struct { |
15 | | - scanner *bufio.Scanner |
16 | | - line string |
17 | | - done bool |
18 | | -} |
19 | | - |
20 | | -// NewDecoder generates a new CodeOwnersScanner instance. The reader should be a reader containing the contents of the CODEOWNERS file |
21 | | -func NewDecoder(r io.Reader) *Decoder { |
22 | | - return &Decoder{ |
23 | | - scanner: bufio.NewScanner(r), |
24 | | - line: "", |
25 | | - done: false, |
26 | | - } |
27 | | -} |
28 | | - |
29 | | -// peek will scan the next line |
30 | | -func (s *Decoder) peek() { |
31 | | - if !s.scanner.Scan() { |
32 | | - s.done = true |
33 | | - return |
34 | | - } |
35 | | - line := sanitiseLine(s.scanner.Text()) |
36 | | - s.line = line |
37 | | - if len(s.line) == 0 && !s.done { |
38 | | - s.peek() |
39 | | - } |
40 | | -} |
41 | | - |
42 | | -// sanitiseLine removes all empty space and comments from a given line |
43 | | -func sanitiseLine(line string) string { |
44 | | - i := strings.Index(line, "#") |
45 | | - if i >= 0 { |
46 | | - line = line[:i] |
47 | | - } |
48 | | - return strings.Trim(line, " ") |
49 | | -} |
50 | | - |
51 | | -// More returns true if there are available CODEOWNERS lines to be scanned. |
52 | | -// And also advances to the next line. |
53 | | -func (s *Decoder) More() bool { |
54 | | - s.peek() |
55 | | - return !s.done |
56 | | -} |
57 | | - |
58 | | -// Token parses the next available line in the CODEOWNERS file. |
59 | | -// If More was never called it will return an empty token. |
60 | | -// After end of file Token will always return the last line. |
61 | | -func (s *Decoder) Token() Token { |
62 | | - line := strings.ReplaceAll(s.line, "\\ ", "\\s") |
63 | | - |
64 | | - data := strings.Split(line, " ") |
65 | | - |
66 | | - for i := range data { |
67 | | - data[i] = strings.ReplaceAll(data[i], "\\s", " ") |
68 | | - } |
69 | | - |
70 | | - return Token{ |
71 | | - path: data[0], |
72 | | - owners: data[1:], |
73 | | - } |
74 | | -} |
75 | | - |
76 | | -// Token providers reading capabilities for every CODEOWNERS line |
77 | | -type Token struct { |
78 | | - path string |
79 | | - owners []string |
80 | | -} |
81 | | - |
82 | | -// Path returns the file path pattern |
83 | | -func (t Token) Path() string { |
84 | | - return t.path |
85 | | -} |
86 | | - |
87 | | -// Owners returns the owners |
88 | | -func (t Token) Owners() []string { |
89 | | - return t.owners |
90 | | -} |
0 commit comments