|
| 1 | +package golinters |
| 2 | + |
| 3 | +import ( |
| 4 | + "sync" |
| 5 | + |
| 6 | + "github.com/ashanbrown/forbidigo/forbidigo" |
| 7 | + "github.com/pkg/errors" |
| 8 | + "golang.org/x/tools/go/analysis" |
| 9 | + |
| 10 | + "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" |
| 11 | + "github.com/golangci/golangci-lint/pkg/lint/linter" |
| 12 | + "github.com/golangci/golangci-lint/pkg/result" |
| 13 | +) |
| 14 | + |
| 15 | +const forbidigoName = "forbidigo" |
| 16 | + |
| 17 | +func NewForbidigo() *goanalysis.Linter { |
| 18 | + var mu sync.Mutex |
| 19 | + var resIssues []goanalysis.Issue |
| 20 | + |
| 21 | + analyzer := &analysis.Analyzer{ |
| 22 | + Name: forbidigoName, |
| 23 | + Doc: goanalysis.TheOnlyanalyzerDoc, |
| 24 | + } |
| 25 | + return goanalysis.NewLinter( |
| 26 | + forbidigoName, |
| 27 | + "Forbids identifiers", |
| 28 | + []*analysis.Analyzer{analyzer}, |
| 29 | + nil, |
| 30 | + ).WithContextSetter(func(lintCtx *linter.Context) { |
| 31 | + s := &lintCtx.Settings().Forbidigo |
| 32 | + |
| 33 | + analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { |
| 34 | + var res []goanalysis.Issue |
| 35 | + forbid, err := forbidigo.NewLinter(s.Forbid) |
| 36 | + if err != nil { |
| 37 | + return nil, errors.Wrapf(err, "failed to create linter %q", forbidigoName) |
| 38 | + } |
| 39 | + |
| 40 | + for _, file := range pass.Files { |
| 41 | + hints, err := forbid.Run(pass.Fset, file) |
| 42 | + if err != nil { |
| 43 | + return nil, errors.Wrapf(err, "forbidigo linter failed on file %q", file.Name.String()) |
| 44 | + } |
| 45 | + for _, hint := range hints { |
| 46 | + res = append(res, goanalysis.NewIssue(&result.Issue{ |
| 47 | + Pos: hint.Position(), |
| 48 | + Text: hint.Details(), |
| 49 | + FromLinter: makezeroName, |
| 50 | + }, pass)) |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + if len(res) == 0 { |
| 55 | + return nil, nil |
| 56 | + } |
| 57 | + |
| 58 | + mu.Lock() |
| 59 | + resIssues = append(resIssues, res...) |
| 60 | + mu.Unlock() |
| 61 | + return nil, nil |
| 62 | + } |
| 63 | + }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { |
| 64 | + return resIssues |
| 65 | + }).WithLoadMode(goanalysis.LoadModeSyntax) |
| 66 | +} |
0 commit comments