forked from golangci/golangci-lint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathloader.go
490 lines (390 loc) · 13.4 KB
/
loader.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
package config
import (
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"github.com/go-viper/mapstructure/v2"
"github.com/mitchellh/go-homedir"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/golangci/golangci-lint/pkg/exitcodes"
"github.com/golangci/golangci-lint/pkg/fsutils"
"github.com/golangci/golangci-lint/pkg/logutils"
)
var errConfigDisabled = errors.New("config is disabled by --no-config")
type LoaderOptions struct {
Config string // Flag only. The path to the golangci config file, as specified with the --config argument.
NoConfig bool // Flag only.
}
type LoadOptions struct {
CheckDeprecation bool
Validation bool
}
type Loader struct {
opts LoaderOptions
viper *viper.Viper
fs *pflag.FlagSet
log logutils.Log
cfg *Config
args []string
}
func NewLoader(log logutils.Log, v *viper.Viper, fs *pflag.FlagSet, opts LoaderOptions, cfg *Config, args []string) *Loader {
return &Loader{
opts: opts,
viper: v,
fs: fs,
log: log,
cfg: cfg,
args: args,
}
}
func (l *Loader) Load(opts LoadOptions) error {
err := l.setConfigFile()
if err != nil {
return err
}
err = l.parseConfig()
if err != nil {
return err
}
l.applyStringSliceHack()
if opts.CheckDeprecation {
err = l.handleDeprecation()
if err != nil {
return err
}
}
l.handleGoVersion()
err = l.handleEnableOnlyOption()
if err != nil {
return err
}
if opts.Validation {
err = l.cfg.Validate()
if err != nil {
return err
}
}
return nil
}
func (l *Loader) setConfigFile() error {
configFile, err := l.evaluateOptions()
if err != nil {
if errors.Is(err, errConfigDisabled) {
return nil
}
return fmt.Errorf("can't parse --config option: %w", err)
}
if configFile != "" {
l.viper.SetConfigFile(configFile)
// Assume YAML if the file has no extension.
if filepath.Ext(configFile) == "" {
l.viper.SetConfigType("yaml")
}
} else {
l.setupConfigFileSearch()
}
return nil
}
func (l *Loader) evaluateOptions() (string, error) {
if l.opts.NoConfig && l.opts.Config != "" {
return "", errors.New("can't combine option --config and --no-config")
}
if l.opts.NoConfig {
return "", errConfigDisabled
}
configFile, err := homedir.Expand(l.opts.Config)
if err != nil {
return "", errors.New("failed to expand configuration path")
}
return configFile, nil
}
func (l *Loader) setupConfigFileSearch() {
l.viper.SetConfigName(".golangci")
configSearchPaths := l.getConfigSearchPaths()
l.log.Infof("Config search paths: %s", configSearchPaths)
for _, p := range configSearchPaths {
l.viper.AddConfigPath(p)
}
}
func (l *Loader) getConfigSearchPaths() []string {
firstArg := "./..."
if len(l.args) > 0 {
firstArg = l.args[0]
}
absPath, err := filepath.Abs(firstArg)
if err != nil {
l.log.Warnf("Can't make abs path for %q: %s", firstArg, err)
absPath = filepath.Clean(firstArg)
}
// start from it
var currentDir string
if fsutils.IsDir(absPath) {
currentDir = absPath
} else {
currentDir = filepath.Dir(absPath)
}
// find all dirs from it up to the root
searchPaths := []string{"./"}
for {
searchPaths = append(searchPaths, currentDir)
parent := filepath.Dir(currentDir)
if currentDir == parent || parent == "" {
break
}
currentDir = parent
}
// find home directory for global config
if home, err := homedir.Dir(); err != nil {
l.log.Warnf("Can't get user's home directory: %v", err)
} else if !slices.Contains(searchPaths, home) {
searchPaths = append(searchPaths, home)
}
return searchPaths
}
func (l *Loader) parseConfig() error {
if err := l.viper.ReadInConfig(); err != nil {
var configFileNotFoundError viper.ConfigFileNotFoundError
if errors.As(err, &configFileNotFoundError) {
// Load configuration from flags only.
err = l.viper.Unmarshal(l.cfg, customDecoderHook())
if err != nil {
return fmt.Errorf("can't unmarshal config by viper (flags): %w", err)
}
return nil
}
return fmt.Errorf("can't read viper config: %w", err)
}
err := l.setConfigDir()
if err != nil {
return err
}
// Load configuration from all sources (flags, file).
if err := l.viper.Unmarshal(l.cfg, customDecoderHook()); err != nil {
return fmt.Errorf("can't unmarshal config by viper (flags, file): %w", err)
}
if l.cfg.InternalTest { // just for testing purposes: to detect config file usage
_, _ = fmt.Fprintln(logutils.StdOut, "test")
os.Exit(exitcodes.Success)
}
return nil
}
func (l *Loader) setConfigDir() error {
usedConfigFile := l.viper.ConfigFileUsed()
if usedConfigFile == "" {
return nil
}
if usedConfigFile == os.Stdin.Name() {
usedConfigFile = ""
l.log.Infof("Reading config file stdin")
} else {
var err error
usedConfigFile, err = fsutils.ShortestRelPath(usedConfigFile, "")
if err != nil {
l.log.Warnf("Can't pretty print config file path: %v", err)
}
l.log.Infof("Used config file %s", usedConfigFile)
}
usedConfigDir, err := filepath.Abs(filepath.Dir(usedConfigFile))
if err != nil {
return errors.New("can't get config directory")
}
l.cfg.cfgDir = usedConfigDir
return nil
}
// Hack to append values from StringSlice flags.
// Viper always overrides StringSlice values.
// https://github.com/spf13/viper/issues/1448
// So StringSlice flags are not bind to Viper like that their values are obtain via Cobra Flags.
func (l *Loader) applyStringSliceHack() {
if l.fs == nil {
return
}
l.appendStringSlice("enable", &l.cfg.Linters.Enable)
l.appendStringSlice("disable", &l.cfg.Linters.Disable)
l.appendStringSlice("presets", &l.cfg.Linters.Presets)
l.appendStringSlice("build-tags", &l.cfg.Run.BuildTags)
l.appendStringSlice("exclude", &l.cfg.Issues.ExcludePatterns)
l.appendStringSlice("skip-dirs", &l.cfg.Run.SkipDirs)
l.appendStringSlice("skip-files", &l.cfg.Run.SkipFiles)
l.appendStringSlice("exclude-dirs", &l.cfg.Issues.ExcludeDirs)
l.appendStringSlice("exclude-files", &l.cfg.Issues.ExcludeFiles)
}
func (l *Loader) appendStringSlice(name string, current *[]string) {
if l.fs.Changed(name) {
val, _ := l.fs.GetStringSlice(name)
*current = append(*current, val...)
}
}
func (l *Loader) handleGoVersion() {
if l.cfg.Run.Go == "" {
l.cfg.Run.Go = detectGoVersion()
}
l.cfg.LintersSettings.Govet.Go = l.cfg.Run.Go
l.cfg.LintersSettings.ParallelTest.Go = l.cfg.Run.Go
if l.cfg.LintersSettings.Gofumpt.LangVersion == "" {
l.cfg.LintersSettings.Gofumpt.LangVersion = l.cfg.Run.Go
}
trimmedGoVersion := trimGoVersion(l.cfg.Run.Go)
l.cfg.LintersSettings.Revive.Go = trimmedGoVersion
l.cfg.LintersSettings.Gocritic.Go = trimmedGoVersion
// staticcheck related linters.
if l.cfg.LintersSettings.Staticcheck.GoVersion == "" {
l.cfg.LintersSettings.Staticcheck.GoVersion = trimmedGoVersion
}
if l.cfg.LintersSettings.Gosimple.GoVersion == "" {
l.cfg.LintersSettings.Gosimple.GoVersion = trimmedGoVersion
}
if l.cfg.LintersSettings.Stylecheck.GoVersion == "" {
l.cfg.LintersSettings.Stylecheck.GoVersion = trimmedGoVersion
}
os.Setenv("GOSECGOVERSION", l.cfg.Run.Go)
}
func (l *Loader) handleDeprecation() error {
if l.cfg.InternalTest || l.cfg.InternalCmdTest || os.Getenv(logutils.EnvTestRun) == "1" {
return nil
}
// Deprecated since v1.57.0
if len(l.cfg.Run.SkipFiles) > 0 {
l.log.Warnf("The configuration option `run.skip-files` is deprecated, please use `issues.exclude-files`.")
l.cfg.Issues.ExcludeFiles = l.cfg.Run.SkipFiles
}
// Deprecated since v1.57.0
if len(l.cfg.Run.SkipDirs) > 0 {
l.log.Warnf("The configuration option `run.skip-dirs` is deprecated, please use `issues.exclude-dirs`.")
l.cfg.Issues.ExcludeDirs = l.cfg.Run.SkipDirs
}
// The 2 options are true by default.
// Deprecated since v1.57.0
if !l.cfg.Run.UseDefaultSkipDirs {
l.log.Warnf("The configuration option `run.skip-dirs-use-default` is deprecated, please use `issues.exclude-dirs-use-default`.")
}
l.cfg.Issues.UseDefaultExcludeDirs = l.cfg.Run.UseDefaultSkipDirs && l.cfg.Issues.UseDefaultExcludeDirs
// The 2 options are false by default.
// Deprecated since v1.57.0
if l.cfg.Run.ShowStats {
l.log.Warnf("The configuration option `run.show-stats` is deprecated, please use `output.show-stats`")
}
l.cfg.Output.ShowStats = l.cfg.Run.ShowStats || l.cfg.Output.ShowStats
// Deprecated since v1.57.0
if l.cfg.Output.Format != "" {
l.log.Warnf("The configuration option `output.format` is deprecated, please use `output.formats`")
var f OutputFormats
err := f.UnmarshalText([]byte(l.cfg.Output.Format))
if err != nil {
return fmt.Errorf("unmarshal output format: %w", err)
}
l.cfg.Output.Formats = f
}
for _, format := range l.cfg.Output.Formats {
if format.Format == OutFormatGithubActions {
l.log.Warnf("The output format `%s` is deprecated, please use `%s`", OutFormatGithubActions, OutFormatColoredLineNumber)
break // To avoid repeating the message if there are several usages of github-actions format.
}
}
// Deprecated since v1.59.0
if l.cfg.Issues.ExcludeGeneratedStrict {
l.log.Warnf("The configuration option `issues.exclude-generated-strict` is deprecated, please use `issues.exclude-generated`")
l.cfg.Issues.ExcludeGenerated = "strict" // Don't use the constants to avoid cyclic dependencies.
}
l.handleLinterOptionDeprecations()
return nil
}
//nolint:gocyclo // the complexity cannot be reduced.
func (l *Loader) handleLinterOptionDeprecations() {
// Deprecated since v1.57.0,
// but it was unofficially deprecated since v1.19 (2019) (https://github.com/golangci/golangci-lint/pull/697).
if l.cfg.LintersSettings.Govet.CheckShadowing {
l.log.Warnf("The configuration option `linters.govet.check-shadowing` is deprecated. " +
"Please enable `shadow` instead, if you are not using `enable-all`.")
}
if l.cfg.LintersSettings.CopyLoopVar.IgnoreAlias {
l.log.Warnf("The configuration option `linters.copyloopvar.ignore-alias` is deprecated and ignored," +
"please use `linters.copyloopvar.check-alias`.")
}
// Deprecated since v1.42.0.
if l.cfg.LintersSettings.Errcheck.Exclude != "" {
l.log.Warnf("The configuration option `linters.errcheck.exclude` is deprecated, please use `linters.errcheck.exclude-functions`.")
}
// Deprecated since v1.59.0,
// but it was unofficially deprecated since v1.13 (2018) (https://github.com/golangci/golangci-lint/pull/332).
if l.cfg.LintersSettings.Errcheck.Ignore != "" {
l.log.Warnf("The configuration option `linters.errcheck.ignore` is deprecated, please use `linters.errcheck.exclude-functions`.")
}
// Deprecated since v1.44.0.
if l.cfg.LintersSettings.Gci.LocalPrefixes != "" {
l.log.Warnf("The configuration option `linters.gci.local-prefixes` is deprecated, please use `prefix()` inside `linters.gci.sections`.")
}
// Deprecated since v1.33.0.
if l.cfg.LintersSettings.Godot.CheckAll {
l.log.Warnf("The configuration option `linters.godot.check-all` is deprecated, please use `linters.godot.scope: all`.")
}
// Deprecated since v1.44.0.
if len(l.cfg.LintersSettings.Gomnd.Settings) > 0 {
l.log.Warnf("The configuration option `linters.gomnd.settings` is deprecated. Please use the options " +
"`linters.gomnd.checks`,`linters.gomnd.ignored-numbers`,`linters.gomnd.ignored-files`,`linters.gomnd.ignored-functions`.")
}
// Deprecated since v1.47.0
if l.cfg.LintersSettings.Gofumpt.LangVersion != "" {
l.log.Warnf("The configuration option `linters.gofumpt.lang-version` is deprecated, please use global `run.go`.")
}
// Deprecated since v1.47.0
if l.cfg.LintersSettings.Staticcheck.GoVersion != "" {
l.log.Warnf("The configuration option `linters.staticcheck.go` is deprecated, please use global `run.go`.")
}
// Deprecated since v1.47.0
if l.cfg.LintersSettings.Gosimple.GoVersion != "" {
l.log.Warnf("The configuration option `linters.gosimple.go` is deprecated, please use global `run.go`.")
}
// Deprecated since v1.47.0
if l.cfg.LintersSettings.Stylecheck.GoVersion != "" {
l.log.Warnf("The configuration option `linters.stylecheck.go` is deprecated, please use global `run.go`.")
}
// Deprecated since v1.60.0
if !l.cfg.LintersSettings.Unused.ExportedIsUsed {
l.log.Warnf("The configuration option `linters.unused.exported-is-used` is deprecated.")
}
// Deprecated since v1.58.0
if l.cfg.LintersSettings.SlogLint.ContextOnly {
l.log.Warnf("The configuration option `linters.sloglint.context-only` is deprecated, please use `linters.sloglint.context`.")
if l.cfg.LintersSettings.SlogLint.Context == "" {
l.cfg.LintersSettings.SlogLint.Context = "all"
}
}
// Deprecated since v1.51.0
if l.cfg.LintersSettings.UseStdlibVars.OSDevNull {
l.log.Warnf("The configuration option `linters.usestdlibvars.os-dev-null` is deprecated.")
}
// Deprecated since v1.51.0
if l.cfg.LintersSettings.UseStdlibVars.SyslogPriority {
l.log.Warnf("The configuration option `linters.usestdlibvars.syslog-priority` is deprecated.")
}
}
func (l *Loader) handleEnableOnlyOption() error {
lookup := l.fs.Lookup("enable-only")
if lookup == nil {
return nil
}
only, err := l.fs.GetStringSlice("enable-only")
if err != nil {
return err
}
if len(only) > 0 {
l.cfg.Linters = Linters{
Enable: only,
DisableAll: true,
}
}
return nil
}
func customDecoderHook() viper.DecoderConfigOption {
return viper.DecodeHook(mapstructure.ComposeDecodeHookFunc(
// Default hooks (https://github.com/spf13/viper/blob/518241257478c557633ab36e474dfcaeb9a3c623/viper.go#L135-L138).
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.StringToSliceHookFunc(","),
// Needed for forbidigo, and output.formats.
mapstructure.TextUnmarshallerHookFunc(),
))
}