
Use build.Import instead of manual parser.ParseFile and paths traversal. It allows: 1. support build tags for all linters. 2. analyze files only for current GOOS/GOARCH: less false-positives. 3. analyze xtest packages (*_test) by golint: upstream golint and gometalinter can't do it! And don't break analysis on the first xtest package like it was before. 4. proper handling of xtest packages for linters like goconst where package boundary is important: less false-positives is expected. Also: 1. reuse AST parsing for golint and goconst: minor speedup. 2. allow to specify path (not only name) regexp for --skip-files and --skip-dirs 3. add more default exclude filters for golint about commits: `(comment on exported (method|function)|should have( a package)? comment|comment should be of the form)` 4. print skipped dir in verbose (-v) mode 5. refactor per-linter tests: declare arguments in comments, run only one linter and in combination with slow linter
64 lines
1.6 KiB
Go
64 lines
1.6 KiB
Go
package golinters
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
goconstAPI "github.com/golangci/goconst"
|
|
"github.com/golangci/golangci-lint/pkg/lint/linter"
|
|
"github.com/golangci/golangci-lint/pkg/result"
|
|
)
|
|
|
|
type Goconst struct{}
|
|
|
|
func (Goconst) Name() string {
|
|
return "goconst"
|
|
}
|
|
|
|
func (Goconst) Desc() string {
|
|
return "Finds repeated strings that could be replaced by a constant"
|
|
}
|
|
|
|
func (lint Goconst) Run(ctx context.Context, lintCtx *linter.Context) ([]result.Issue, error) {
|
|
var goconstIssues []goconstAPI.Issue
|
|
cfg := goconstAPI.Config{
|
|
MatchWithConstants: true,
|
|
MinStringLength: lintCtx.Settings().Goconst.MinStringLen,
|
|
MinOccurrences: lintCtx.Settings().Goconst.MinOccurrencesCount,
|
|
}
|
|
for _, pkg := range lintCtx.PkgProgram.Packages() {
|
|
files, fset, err := getASTFilesForPkg(lintCtx, &pkg)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
issues, err := goconstAPI.Run(files, fset, &cfg)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
goconstIssues = append(goconstIssues, issues...)
|
|
}
|
|
if len(goconstIssues) == 0 {
|
|
return nil, nil
|
|
}
|
|
|
|
res := make([]result.Issue, 0, len(goconstIssues))
|
|
for _, i := range goconstIssues {
|
|
textBegin := fmt.Sprintf("string %s has %d occurrences", formatCode(i.Str, lintCtx.Cfg), i.OccurencesCount)
|
|
var textEnd string
|
|
if i.MatchingConst == "" {
|
|
textEnd = ", make it a constant"
|
|
} else {
|
|
textEnd = fmt.Sprintf(", but such constant %s already exists", formatCode(i.MatchingConst, lintCtx.Cfg))
|
|
}
|
|
res = append(res, result.Issue{
|
|
Pos: i.Pos,
|
|
Text: textBegin + textEnd,
|
|
FromLinter: lint.Name(),
|
|
})
|
|
}
|
|
|
|
return res, nil
|
|
}
|