|
| 1 | +package golinters |
| 2 | + |
| 3 | +import ( |
| 4 | + "sync" |
| 5 | + |
| 6 | + "github.com/ashanbrown/makezero/makezero" |
| 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 makezeroName = "makezero" |
| 16 | + |
| 17 | +func NewMakezero() *goanalysis.Linter { |
| 18 | + var mu sync.Mutex |
| 19 | + var resIssues []goanalysis.Issue |
| 20 | + |
| 21 | + analyzer := &analysis.Analyzer{ |
| 22 | + Name: makezeroName, |
| 23 | + Doc: goanalysis.TheOnlyanalyzerDoc, |
| 24 | + } |
| 25 | + return goanalysis.NewLinter( |
| 26 | + makezeroName, |
| 27 | + "Finds slice declarations with non-zero initial length", |
| 28 | + []*analysis.Analyzer{analyzer}, |
| 29 | + nil, |
| 30 | + ).WithContextSetter(func(lintCtx *linter.Context) { |
| 31 | + s := &lintCtx.Settings().Makezero |
| 32 | + |
| 33 | + analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { |
| 34 | + var res []goanalysis.Issue |
| 35 | + linter := makezero.NewLinter(s.Always) |
| 36 | + for _, file := range pass.Files { |
| 37 | + hints, err := linter.Run(pass.Fset, pass.TypesInfo, file) |
| 38 | + if err != nil { |
| 39 | + return nil, errors.Wrapf(err, "makezero linter failed on file %q", file.Name.String()) |
| 40 | + } |
| 41 | + for _, hint := range hints { |
| 42 | + res = append(res, goanalysis.NewIssue(&result.Issue{ |
| 43 | + Pos: hint.Position(), |
| 44 | + Text: hint.Details(), |
| 45 | + FromLinter: makezeroName, |
| 46 | + }, pass)) |
| 47 | + } |
| 48 | + } |
| 49 | + if len(res) == 0 { |
| 50 | + return nil, nil |
| 51 | + } |
| 52 | + mu.Lock() |
| 53 | + resIssues = append(resIssues, res...) |
| 54 | + mu.Unlock() |
| 55 | + return nil, nil |
| 56 | + } |
| 57 | + }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { |
| 58 | + return resIssues |
| 59 | + }).WithLoadMode(goanalysis.LoadModeSyntax | goanalysis.LoadModeTypesInfo) |
| 60 | +} |
0 commit comments