forked from golangci/golangci-lint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathforbidigo.go
90 lines (74 loc) · 2.33 KB
/
forbidigo.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
package forbidigo
import (
"fmt"
"github.com/ashanbrown/forbidigo/forbidigo"
"golang.org/x/tools/go/analysis"
"gopkg.in/yaml.v3"
"github.com/golangci/golangci-lint/pkg/config"
"github.com/golangci/golangci-lint/pkg/goanalysis"
"github.com/golangci/golangci-lint/pkg/logutils"
)
const linterName = "forbidigo"
func New(settings *config.ForbidigoSettings) *goanalysis.Linter {
analyzer := &analysis.Analyzer{
Name: linterName,
Doc: goanalysis.TheOnlyanalyzerDoc,
Run: func(pass *analysis.Pass) (any, error) {
err := runForbidigo(pass, settings)
if err != nil {
return nil, err
}
return nil, nil
},
}
// Without AnalyzeTypes, LoadModeSyntax is enough.
// But we cannot make this depend on the settings and have to mirror the mode chosen in GetAllSupportedLinterConfigs,
// therefore we have to use LoadModeTypesInfo in all cases.
return goanalysis.NewLinter(
linterName,
"Forbids identifiers",
[]*analysis.Analyzer{analyzer},
nil,
).WithLoadMode(goanalysis.LoadModeTypesInfo)
}
func runForbidigo(pass *analysis.Pass, settings *config.ForbidigoSettings) error {
options := []forbidigo.Option{
forbidigo.OptionExcludeGodocExamples(settings.ExcludeGodocExamples),
// disable "//permit" directives so only "//nolint" directives matters within golangci-lint
forbidigo.OptionIgnorePermitDirectives(true),
forbidigo.OptionAnalyzeTypes(settings.AnalyzeTypes),
}
// Convert patterns back to strings because that is what NewLinter accepts.
var patterns []string
for _, pattern := range settings.Forbid {
buffer, err := yaml.Marshal(pattern)
if err != nil {
return err
}
patterns = append(patterns, string(buffer))
}
forbid, err := forbidigo.NewLinter(patterns, options...)
if err != nil {
return fmt.Errorf("failed to create linter %q: %w", linterName, err)
}
for _, file := range pass.Files {
runConfig := forbidigo.RunConfig{
Fset: pass.Fset,
DebugLog: logutils.Debug(logutils.DebugKeyForbidigo),
}
if settings.AnalyzeTypes {
runConfig.TypesInfo = pass.TypesInfo
}
hints, err := forbid.RunWithConfig(runConfig, file)
if err != nil {
return fmt.Errorf("forbidigo linter failed on file %q: %w", file.Name.String(), err)
}
for _, hint := range hints {
pass.Report(analysis.Diagnostic{
Pos: hint.Pos(),
Message: hint.Details(),
})
}
}
return nil
}