-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanalysis.go
227 lines (197 loc) · 5.96 KB
/
analysis.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
// Copyright (c) 2025 Joshua Sing <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Package golicenser implements a go/analysis for linting license headers.
package golicenser
import (
"fmt"
"go/ast"
"regexp"
"runtime"
"strings"
"github.com/bmatcuk/doublestar/v4"
"golang.org/x/sync/errgroup"
"golang.org/x/tools/go/analysis"
)
const (
analyzerName = "golicenser"
// DefaultCopyrightHeaderMatcher is the default regexp used to detect the
// existence of any copyright header. This will match any header containing
// "copyright".
DefaultCopyrightHeaderMatcher = "(?i)copyright"
)
var (
// DefaultMaxConcurrent is the default maximum concurrency to use when
// analyzing files.
DefaultMaxConcurrent = runtime.GOMAXPROCS(0) * 2
// DefaultExcludes are the default files to exclude when analyzing.
DefaultExcludes = []string{
"**/testdata/**", // Exclude testdata directories
}
)
// Config is the golicenser configuration.
type Config struct {
Header HeaderOpts
Exclude []string
MaxConcurrent int
CopyrightHeaderMatcher string
}
// NewAnalyzer creates a golicenser analyzer.
func NewAnalyzer(cfg Config) (*analysis.Analyzer, error) {
a, err := newAnalyzer(cfg)
if err != nil {
return nil, err
}
return &analysis.Analyzer{
Name: analyzerName,
Doc: "manages license headers",
URL: "https://github.com/joshuasing/golicenser",
Run: a.run,
RunDespiteErrors: true,
}, nil
}
// ExcludeMatcherFunc is a function for determining whether to exclude a file.
type ExcludeMatcherFunc func(filename string) bool
type analyzer struct {
cfg Config
excludes []ExcludeMatcherFunc
headerMatcher *regexp.Regexp
header *Header
}
func newAnalyzer(cfg Config) (*analyzer, error) {
if cfg.MaxConcurrent < 1 {
cfg.MaxConcurrent = DefaultMaxConcurrent
}
if cfg.CopyrightHeaderMatcher == "" {
cfg.CopyrightHeaderMatcher = DefaultCopyrightHeaderMatcher
}
if cfg.Exclude == nil {
cfg.Exclude = DefaultExcludes
}
a := &analyzer{cfg: cfg}
var err error
a.headerMatcher, err = regexp.Compile(a.cfg.CopyrightHeaderMatcher)
if err != nil {
return nil, fmt.Errorf("compile match header regexp: %w", err)
}
// Compile exclude regexes.
for _, exclude := range cfg.Exclude {
if exclude == "" {
continue
}
if strings.HasPrefix(exclude, "r!") {
expr := strings.TrimPrefix(exclude, "r!")
re, err := regexp.Compile(expr)
if err != nil {
return nil, fmt.Errorf("invalid exclude regexp pattern (%s): %w",
expr, err)
}
a.excludes = append(a.excludes, func(filename string) bool {
return re.MatchString(filename)
})
continue
}
if !doublestar.ValidatePattern(exclude) {
return nil, fmt.Errorf("invalid exclude pattern: %s", exclude)
}
a.excludes = append(a.excludes, func(filename string) bool {
matched, _ := doublestar.Match(exclude, filename)
return matched
})
}
// Create license header.
a.header, err = NewHeader(cfg.Header)
if err != nil {
return nil, err
}
return a, nil
}
func (a *analyzer) run(pass *analysis.Pass) (any, error) {
var errg errgroup.Group
errg.SetLimit(a.cfg.MaxConcurrent)
for _, file := range pass.Files {
if ast.IsGenerated(file) {
// Skip generated files.
continue
}
errg.Go(func() error {
return a.checkFile(pass, file)
})
}
return nil, errg.Wait()
}
func (a *analyzer) checkFile(pass *analysis.Pass, file *ast.File) error {
// Check whether the file is excluded.
filename := pass.Fset.File(file.Pos()).Name()
for _, exclude := range a.excludes {
if exclude(filename) {
return nil
}
}
var header string
headerPos, headerEnd := file.FileStart, file.FileStart
if len(file.Comments) > 0 {
if c := file.Comments[0]; c.Pos() < file.Package {
headerPos, headerEnd = c.Pos(), c.End()
for _, comment := range c.List {
header += comment.Text + "\n"
}
}
}
if header == "" || !a.headerMatcher.MatchString(header) {
// License header is missing, generate a new one.
newHeader, err := a.header.Create(filename)
if err != nil {
return fmt.Errorf("create %s header: %w", filename, err)
}
pass.Report(analysis.Diagnostic{
Pos: file.FileStart,
Category: analyzerName,
Message: "missing license header",
SuggestedFixes: []analysis.SuggestedFix{{
Message: "add license header",
TextEdits: []analysis.TextEdit{{
Pos: file.FileStart,
NewText: []byte(newHeader + "\n"),
}},
}},
})
return nil
}
newHeader, modified, err := a.header.Update(filename, header)
if err != nil {
return fmt.Errorf("update %s header: %w", filename, err)
}
if modified {
pass.Report(analysis.Diagnostic{
Pos: headerPos,
End: headerEnd,
Message: "invalid license header",
SuggestedFixes: []analysis.SuggestedFix{{
Message: "update license header",
TextEdits: []analysis.TextEdit{{
Pos: headerPos,
End: headerEnd,
NewText: []byte(newHeader + "\n"),
}},
}},
})
}
return nil
}