|
| 1 | +package golinters |
| 2 | + |
| 3 | +import ( |
| 4 | + "sort" |
| 5 | + "sync" |
| 6 | + |
| 7 | + "github.com/nakabonne/nestif" |
| 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 nestifName = "nestif" |
| 16 | + |
| 17 | +func NewNestif() *goanalysis.Linter { |
| 18 | + var mu sync.Mutex |
| 19 | + var resIssues []goanalysis.Issue |
| 20 | + |
| 21 | + analyzer := &analysis.Analyzer{ |
| 22 | + Name: goanalysis.TheOnlyAnalyzerName, |
| 23 | + Doc: goanalysis.TheOnlyanalyzerDoc, |
| 24 | + } |
| 25 | + return goanalysis.NewLinter( |
| 26 | + nestifName, |
| 27 | + "Reports deeply nested if statements", |
| 28 | + []*analysis.Analyzer{analyzer}, |
| 29 | + nil, |
| 30 | + ).WithContextSetter(func(lintCtx *linter.Context) { |
| 31 | + analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { |
| 32 | + checker := &nestif.Checker{ |
| 33 | + MinComplexity: lintCtx.Settings().Nestif.MinComplexity, |
| 34 | + } |
| 35 | + var issues []nestif.Issue |
| 36 | + for _, f := range pass.Files { |
| 37 | + issues = append(issues, checker.Check(f, pass.Fset)...) |
| 38 | + } |
| 39 | + if len(issues) == 0 { |
| 40 | + return nil, nil |
| 41 | + } |
| 42 | + |
| 43 | + sort.Slice(issues, func(i, j int) bool { |
| 44 | + return issues[i].Complexity > issues[j].Complexity |
| 45 | + }) |
| 46 | + |
| 47 | + res := make([]goanalysis.Issue, 0, len(issues)) |
| 48 | + for _, i := range issues { |
| 49 | + res = append(res, goanalysis.NewIssue(&result.Issue{ //nolint:scopelint |
| 50 | + Pos: i.Pos, |
| 51 | + Text: i.Message, |
| 52 | + FromLinter: nestifName, |
| 53 | + }, pass)) |
| 54 | + } |
| 55 | + |
| 56 | + mu.Lock() |
| 57 | + resIssues = append(resIssues, res...) |
| 58 | + mu.Unlock() |
| 59 | + |
| 60 | + return nil, nil |
| 61 | + } |
| 62 | + }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { |
| 63 | + return resIssues |
| 64 | + }).WithLoadMode(goanalysis.LoadModeSyntax) |
| 65 | +} |
0 commit comments