forked from TheThingsNetwork/lorawan-stack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheaders.go
More file actions
209 lines (189 loc) · 4.66 KB
/
headers.go
File metadata and controls
209 lines (189 loc) · 4.66 KB
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
// Copyright © 2020 The Things Network Foundation, The Things Industries B.V.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ttnmage
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/magefile/mage/mg"
"gopkg.in/yaml.v2"
)
// Headers namespace.
type Headers mg.Namespace
// HeaderRule in the header config file.
type HeaderRule struct {
Include []string `yaml:"include"`
Exclude []string `yaml:"exclude"`
Header string `yaml:"header"`
headerLines []*regexp.Regexp
Prefix string `yaml:"prefix"`
}
func (r *HeaderRule) split() {
lines := bytes.Split([]byte(strings.TrimSpace(r.Header)), []byte("\n"))
r.headerLines = make([]*regexp.Regexp, len(lines))
for i, line := range lines {
r.headerLines[i] = regexp.MustCompile(fmt.Sprintf("^%s$", string(line)))
}
}
func (r *HeaderRule) match(path string) (match bool) {
if len(r.Include) > 0 {
for _, item := range r.Include {
if strings.Contains(path, item) {
match = true
}
}
} else {
match = true
}
for _, item := range r.Exclude {
if strings.Contains(path, item) {
return false
}
}
return
}
// HeaderConfig is the format of the header configuration file.
type HeaderConfig struct {
Rules []*HeaderRule `yaml:"rules"`
}
func (c *HeaderConfig) split() {
for _, rule := range c.Rules {
rule.split()
}
}
func (c *HeaderConfig) get(filename string) (r *HeaderRule) {
for _, rule := range c.Rules {
if !rule.match(filename) {
continue
}
if r == nil {
r = &HeaderRule{}
}
if rule.Header != "" {
r.Header, r.headerLines = rule.Header, rule.headerLines
}
if rule.Prefix != "" {
r.Prefix = rule.Prefix
}
}
return r
}
var (
headerFile string
headerConfig HeaderConfig
)
func init() {
headerFile = os.Getenv("HEADER_FILE")
if headerFile == "" {
headerFile = ".mage/header.yml"
}
}
func (Headers) loadFile() error {
headerBytes, err := ioutil.ReadFile(headerFile)
if err != nil {
return err
}
if err = yaml.Unmarshal(headerBytes, &headerConfig); err != nil {
return err
}
headerConfig.split()
return nil
}
type checkErr struct {
Path string
Reason string
}
func (err checkErr) Error() string {
return fmt.Sprintf("%s %s", err.Path, err.Reason)
}
func (h Headers) check(path string) error {
rule := headerConfig.get(path)
if rule == nil {
return nil
}
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
s := bufio.NewScanner(f)
for i, expected := range rule.headerLines {
if !s.Scan() {
return &checkErr{Path: path, Reason: "has less lines than expected header"}
}
line := s.Bytes()
if i == 0 && bytes.Contains(line, []byte("generated")) {
return nil // Skip generated files.
}
if !bytes.Equal(line, bytes.TrimSpace([]byte(rule.Prefix))) && !expected.Match(bytes.TrimPrefix(line, []byte(rule.Prefix))) {
return &checkErr{Path: path, Reason: fmt.Sprintf("did not match expected header line: %v", expected)}
}
}
if s.Scan() && len(s.Bytes()) != 0 {
return &checkErr{Path: path, Reason: "does not have empty line after header"}
}
return nil
}
type errorSlice []error
func (errs errorSlice) Error() string {
switch len(errs) {
case 0:
return ""
case 1:
return errs[0].Error()
default:
var b strings.Builder
b.WriteString("multiple errors:\n")
for _, err := range errs {
b.WriteString(" - " + err.Error() + "\n")
}
return b.String()
}
}
// Check checks that all files contain the required file header.
func (h Headers) Check() error {
mg.Deps(Headers.loadFile)
var checkErrs errorSlice
err := filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
switch path {
case ".cache", ".dev", ".env", ".git", "dist", "node_modules", "public", "sdk/js/dist", "sdk/js/node_modules", "vendor", "doc/public":
return filepath.SkipDir
}
return nil
}
if selectedFiles != nil && !selectedFiles[path] {
return nil
}
if checkErr := h.check(path); checkErr != nil {
checkErrs = append(checkErrs, checkErr)
}
return nil
})
if err != nil {
return err
}
if len(checkErrs) > 0 {
return checkErrs
}
return nil
}
func init() {
preCommitChecks = append(preCommitChecks, Headers.Check)
}