-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathrunner.go
336 lines (282 loc) · 9.33 KB
/
runner.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
package lint
import (
"context"
"fmt"
"runtime/debug"
"strings"
"github.com/hashicorp/go-multierror"
gopackages "golang.org/x/tools/go/packages"
"github.com/golangci/golangci-lint/internal/errorutil"
"github.com/golangci/golangci-lint/pkg/config"
"github.com/golangci/golangci-lint/pkg/fsutils"
"github.com/golangci/golangci-lint/pkg/goutil"
"github.com/golangci/golangci-lint/pkg/lint/linter"
"github.com/golangci/golangci-lint/pkg/lint/lintersdb"
"github.com/golangci/golangci-lint/pkg/logutils"
"github.com/golangci/golangci-lint/pkg/packages"
"github.com/golangci/golangci-lint/pkg/result"
"github.com/golangci/golangci-lint/pkg/result/processors"
"github.com/golangci/golangci-lint/pkg/timeutils"
)
type Runner struct {
Processors []processors.Processor
Log logutils.Log
}
func NewRunner(cfg *config.Config, log logutils.Log, goenv *goutil.Env, es *lintersdb.EnabledSet,
lineCache *fsutils.LineCache, dbManager *lintersdb.Manager, pkgs []*gopackages.Package) (*Runner, error) {
skipFilesProcessor, err := processors.NewSkipFiles(cfg.Run.SkipFiles)
if err != nil {
return nil, err
}
skipDirs := cfg.Run.SkipDirs
if cfg.Run.UseDefaultSkipDirs {
skipDirs = append(skipDirs, packages.StdExcludeDirRegexps...)
}
skipDirsProcessor, err := processors.NewSkipDirs(skipDirs, log.Child(logutils.DebugKeySkipDirs), cfg.Run.Args)
if err != nil {
return nil, err
}
enabledLinters, err := es.GetEnabledLintersMap()
if err != nil {
return nil, fmt.Errorf("failed to get enabled linters: %w", err)
}
// print deprecated messages
if !cfg.InternalCmdTest {
for name, lc := range enabledLinters {
if !lc.IsDeprecated() {
continue
}
var extra string
if lc.Deprecation.Replacement != "" {
extra = fmt.Sprintf("Replaced by %s.", lc.Deprecation.Replacement)
}
log.Warnf("The linter '%s' is deprecated (since %s) due to: %s %s", name, lc.Deprecation.Since, lc.Deprecation.Message, extra)
}
}
return &Runner{
Processors: []processors.Processor{
processors.NewCgo(goenv),
// Must go after Cgo.
processors.NewFilenameUnadjuster(pkgs, log.Child(logutils.DebugKeyFilenameUnadjuster)),
// Must be before diff, nolint and exclude autogenerated processor at least.
processors.NewPathPrettifier(),
skipFilesProcessor,
skipDirsProcessor, // must be after path prettifier
processors.NewAutogeneratedExclude(),
// Must be before exclude because users see already marked output and configure excluding by it.
processors.NewIdentifierMarker(),
getExcludeProcessor(&cfg.Issues),
getExcludeRulesProcessor(&cfg.Issues, log, lineCache),
processors.NewNolint(log.Child(logutils.DebugKeyNolint), dbManager, enabledLinters),
processors.NewUniqByLine(cfg),
processors.NewDiff(cfg.Issues.Diff, cfg.Issues.DiffFromRevision, cfg.Issues.DiffPatchFilePath, cfg.Issues.WholeFiles),
processors.NewMaxPerFileFromLinter(cfg),
processors.NewMaxSameIssues(cfg.Issues.MaxSameIssues, log.Child(logutils.DebugKeyMaxSameIssues), cfg),
processors.NewMaxFromLinter(cfg.Issues.MaxIssuesPerLinter, log.Child(logutils.DebugKeyMaxFromLinter), cfg),
processors.NewSourceCode(lineCache, log.Child(logutils.DebugKeySourceCode)),
processors.NewPathShortener(),
getSeverityRulesProcessor(&cfg.Severity, log, lineCache),
processors.NewPathPrefixer(cfg.Output.PathPrefix),
processors.NewSortResults(cfg),
},
Log: log,
}, nil
}
func (r *Runner) runLinterSafe(ctx context.Context, lintCtx *linter.Context,
lc *linter.Config) (ret []result.Issue, err error) {
defer func() {
if panicData := recover(); panicData != nil {
if pe, ok := panicData.(*errorutil.PanicError); ok {
err = fmt.Errorf("%s: %w", lc.Name(), pe)
// Don't print stacktrace from goroutines twice
r.Log.Errorf("Panic: %s: %s", pe, pe.Stack())
} else {
err = fmt.Errorf("panic occurred: %s", panicData)
r.Log.Errorf("Panic stack trace: %s", debug.Stack())
}
}
}()
issues, err := lc.Linter.Run(ctx, lintCtx)
if lc.DoesChangeTypes {
// Packages in lintCtx might be dirty due to the last analysis,
// which affects to the next analysis.
// To avoid this issue, we clear type information from the packages.
// See https://github.com/golangci/golangci-lint/pull/944.
// Currently, DoesChangeTypes is true only for `unused`.
lintCtx.ClearTypesInPackages()
}
if err != nil {
return nil, err
}
for i := range issues {
if issues[i].FromLinter == "" {
issues[i].FromLinter = lc.Name()
}
}
return issues, nil
}
type processorStat struct {
inCount int
outCount int
}
func (r Runner) processLintResults(inIssues []result.Issue) []result.Issue {
sw := timeutils.NewStopwatch("processing", r.Log)
var issuesBefore, issuesAfter int
statPerProcessor := map[string]processorStat{}
var outIssues []result.Issue
if len(inIssues) != 0 {
issuesBefore += len(inIssues)
outIssues = r.processIssues(inIssues, sw, statPerProcessor)
issuesAfter += len(outIssues)
}
// finalize processors: logging, clearing, no heavy work here
for _, p := range r.Processors {
p := p
sw.TrackStage(p.Name(), func() {
p.Finish()
})
}
if issuesBefore != issuesAfter {
r.Log.Infof("Issues before processing: %d, after processing: %d", issuesBefore, issuesAfter)
}
r.printPerProcessorStat(statPerProcessor)
sw.PrintStages()
return outIssues
}
func (r Runner) printPerProcessorStat(stat map[string]processorStat) {
parts := make([]string, 0, len(stat))
for name, ps := range stat {
if ps.inCount != 0 {
parts = append(parts, fmt.Sprintf("%s: %d/%d", name, ps.outCount, ps.inCount))
}
}
if len(parts) != 0 {
r.Log.Infof("Processors filtering stat (out/in): %s", strings.Join(parts, ", "))
}
}
func (r Runner) Run(ctx context.Context, linters []*linter.Config, lintCtx *linter.Context) ([]result.Issue, error) {
sw := timeutils.NewStopwatch("linters", r.Log)
defer sw.Print()
var (
lintErrors *multierror.Error
issues []result.Issue
)
for _, lc := range linters {
lc := lc
sw.TrackStage(lc.Name(), func() {
linterIssues, err := r.runLinterSafe(ctx, lintCtx, lc)
if err != nil {
lintErrors = multierror.Append(lintErrors, fmt.Errorf("can't run linter %s: %w", lc.Linter.Name(), err))
r.Log.Warnf("Can't run linter %s: %v", lc.Linter.Name(), err)
return
}
issues = append(issues, linterIssues...)
})
}
return r.processLintResults(issues), lintErrors.ErrorOrNil()
}
func (r *Runner) processIssues(issues []result.Issue, sw *timeutils.Stopwatch, statPerProcessor map[string]processorStat) []result.Issue {
for _, p := range r.Processors {
var newIssues []result.Issue
var err error
p := p
sw.TrackStage(p.Name(), func() {
newIssues, err = p.Process(issues)
})
if err != nil {
r.Log.Warnf("Can't process result by %s processor: %s", p.Name(), err)
} else {
stat := statPerProcessor[p.Name()]
stat.inCount += len(issues)
stat.outCount += len(newIssues)
statPerProcessor[p.Name()] = stat
issues = newIssues
}
if issues == nil {
issues = []result.Issue{}
}
}
return issues
}
func getExcludeProcessor(cfg *config.Issues) processors.Processor {
var excludeTotalPattern string
if len(cfg.ExcludePatterns) != 0 {
excludeTotalPattern = fmt.Sprintf("(%s)", strings.Join(cfg.ExcludePatterns, "|"))
}
var excludeProcessor processors.Processor
if cfg.ExcludeCaseSensitive {
excludeProcessor = processors.NewExcludeCaseSensitive(excludeTotalPattern)
} else {
excludeProcessor = processors.NewExclude(excludeTotalPattern)
}
return excludeProcessor
}
func getExcludeRulesProcessor(cfg *config.Issues, log logutils.Log, lineCache *fsutils.LineCache) processors.Processor {
var excludeRules []processors.ExcludeRule
for _, r := range cfg.ExcludeRules {
excludeRules = append(excludeRules, processors.ExcludeRule{
BaseRule: processors.BaseRule{
Text: r.Text,
Source: r.Source,
Path: r.Path,
Linters: r.Linters,
},
})
}
if cfg.UseDefaultExcludes {
for _, r := range config.GetExcludePatterns(cfg.IncludeDefaultExcludes) {
excludeRules = append(excludeRules, processors.ExcludeRule{
BaseRule: processors.BaseRule{
Text: r.Pattern,
Linters: []string{r.Linter},
},
})
}
}
var excludeRulesProcessor processors.Processor
if cfg.ExcludeCaseSensitive {
excludeRulesProcessor = processors.NewExcludeRulesCaseSensitive(
excludeRules,
lineCache,
log.Child(logutils.DebugKeyExcludeRules),
)
} else {
excludeRulesProcessor = processors.NewExcludeRules(
excludeRules,
lineCache,
log.Child(logutils.DebugKeyExcludeRules),
)
}
return excludeRulesProcessor
}
func getSeverityRulesProcessor(cfg *config.Severity, log logutils.Log, lineCache *fsutils.LineCache) processors.Processor {
var severityRules []processors.SeverityRule
for _, r := range cfg.Rules {
severityRules = append(severityRules, processors.SeverityRule{
Severity: r.Severity,
BaseRule: processors.BaseRule{
Text: r.Text,
Source: r.Source,
Path: r.Path,
Linters: r.Linters,
},
})
}
var severityRulesProcessor processors.Processor
if cfg.CaseSensitive {
severityRulesProcessor = processors.NewSeverityRulesCaseSensitive(
cfg.Default,
severityRules,
lineCache,
log.Child(logutils.DebugKeySeverityRules),
)
} else {
severityRulesProcessor = processors.NewSeverityRules(
cfg.Default,
severityRules,
lineCache,
log.Child(logutils.DebugKeySeverityRules),
)
}
return severityRulesProcessor
}