1
0
mirror of https://github.com/mgechev/revive.git synced 2025-07-03 00:26:51 +02:00
Files
revive/lint/linter.go

257 lines
6.2 KiB
Go
Raw Normal View History

2018-01-24 15:44:03 -08:00
package lint
2017-08-27 16:57:16 -07:00
import (
2018-01-21 18:04:41 -08:00
"bufio"
"bytes"
2018-05-31 19:42:58 -07:00
"fmt"
2017-08-27 16:57:16 -07:00
"go/token"
2018-05-31 19:42:58 -07:00
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
goversion "github.com/hashicorp/go-version"
"golang.org/x/mod/modfile"
"golang.org/x/sync/errgroup"
2017-08-27 16:57:16 -07:00
)
// ReadFile defines an abstraction for reading files.
type ReadFile func(path string) (result []byte, err error)
// Linter is used for linting set of files.
2017-08-27 16:57:16 -07:00
type Linter struct {
reader ReadFile
fileReadTokens chan struct{}
2017-08-27 16:57:16 -07:00
}
// New creates a new Linter
func New(reader ReadFile, maxOpenFiles int) Linter {
var fileReadTokens chan struct{}
if maxOpenFiles > 0 {
fileReadTokens = make(chan struct{}, maxOpenFiles)
}
return Linter{
reader: reader,
fileReadTokens: fileReadTokens,
}
}
func (l Linter) readFile(path string) (result []byte, err error) {
if l.fileReadTokens != nil {
// "take" a token by writing to the channel.
// It will block if no more space in the channel's buffer
l.fileReadTokens <- struct{}{}
defer func() {
// "free" a token by reading from the channel
<-l.fileReadTokens
}()
}
return l.reader(path)
2017-08-27 16:57:16 -07:00
}
2018-01-21 18:04:41 -08:00
var (
2024-12-08 11:08:54 +01:00
generatedPrefix = []byte("// Code generated ")
generatedSuffix = []byte(" DO NOT EDIT.")
defaultGoVersion = goversion.Must(goversion.NewVersion("1.0"))
2018-01-21 18:04:41 -08:00
)
2018-05-31 19:42:58 -07:00
// Lint lints a set of files with the specified rule.
func (l *Linter) Lint(packages [][]string, ruleSet []Rule, config Config) (<-chan Failure, error) {
failures := make(chan Failure)
perModVersions := map[string]*goversion.Version{}
perPkgVersions := make([]*goversion.Version, len(packages))
for n, files := range packages {
if len(files) == 0 {
continue
}
if config.GoVersion != nil {
perPkgVersions[n] = config.GoVersion
continue
}
dir, err := filepath.Abs(filepath.Dir(files[0]))
if err != nil {
return nil, err
}
alreadyKnownMod := false
for d, v := range perModVersions {
if strings.HasPrefix(dir, d) {
perPkgVersions[n] = v
alreadyKnownMod = true
break
}
}
if alreadyKnownMod {
continue
}
d, v, err := detectGoMod(dir)
if err != nil {
// No luck finding the go.mod file thus set the default Go version
v = defaultGoVersion
d = dir
}
perModVersions[d] = v
perPkgVersions[n] = v
}
var wg errgroup.Group
for n := range packages {
wg.Go(func() error {
pkg := packages[n]
gover := perPkgVersions[n]
if err := l.lintPackage(pkg, gover, ruleSet, config, failures); err != nil {
return fmt.Errorf("error during linting: %w", err)
2018-05-31 19:42:58 -07:00
}
return nil
})
2018-01-21 18:04:41 -08:00
}
2018-05-31 19:42:58 -07:00
go func() {
err := wg.Wait()
if err != nil {
failures <- NewInternalFailure(err.Error())
}
2018-05-31 19:42:58 -07:00
close(failures)
}()
return failures, nil
2018-01-21 18:04:41 -08:00
}
func (l *Linter) lintPackage(filenames []string, gover *goversion.Version, ruleSet []Rule, config Config, failures chan Failure) error {
if len(filenames) == 0 {
return nil
}
2018-01-21 18:04:41 -08:00
pkg := &Package{
fset: token.NewFileSet(),
files: map[string]*File{},
goVersion: gover,
2018-01-21 18:04:41 -08:00
}
2017-08-27 16:57:16 -07:00
for _, filename := range filenames {
content, err := l.readFile(filename)
2017-08-27 16:57:16 -07:00
if err != nil {
2018-05-31 19:42:58 -07:00
return err
2017-08-27 16:57:16 -07:00
}
if !config.IgnoreGeneratedHeader && isGenerated(content) {
2018-01-21 18:04:41 -08:00
continue
}
2017-08-27 16:57:16 -07:00
2018-01-21 18:04:41 -08:00
file, err := NewFile(filename, content, pkg)
2017-08-27 16:57:16 -07:00
if err != nil {
addInvalidFileFailure(filename, err.Error(), failures)
continue
2017-08-27 16:57:16 -07:00
}
2018-01-21 18:29:07 -08:00
pkg.files[filename] = file
}
2018-05-31 19:42:58 -07:00
if len(pkg.files) == 0 {
return nil
}
2018-01-23 17:14:23 -08:00
return pkg.lint(ruleSet, config, failures)
2018-05-31 19:42:58 -07:00
}
func detectGoMod(dir string) (rootDir string, ver *goversion.Version, err error) {
modFileName, err := retrieveModFile(dir)
if err != nil {
return "", nil, fmt.Errorf("%q doesn't seem to be part of a Go module", dir)
}
mod, err := os.ReadFile(modFileName)
if err != nil {
refactor: fix linting issues (#1188) * refactor: fix thelper issues test/utils_test.go:19:6 thelper test helper function should start from t.Helper() test/utils_test.go:42:6 thelper test helper function should start from t.Helper() test/utils_test.go:63:6 thelper test helper function should start from t.Helper() test/utils_test.go:146:6 thelper test helper function should start from t.Helper() * refactor: fix govet issues rule/error_strings.go:50:21 govet printf: non-constant format string in call to fmt.Errorf * refactor: fix gosimple issue rule/bare_return.go:52:9 gosimple S1016: should convert w (type lintBareReturnRule) to bareReturnFinder instead of using struct literal * refactor: fix errorlint issues lint/filefilter.go:70:86 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors lint/filefilter.go:113:104 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors lint/filefilter.go:125:89 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors lint/linter.go:166:72 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors lint/linter.go:171:73 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors config/config.go:174:57 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors config/config.go:179:64 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors * refactor: fix revive issue about comment spacing cli/main.go:31:2 revive comment-spacings: no space between comment delimiter and comment text * refactor: fix revive issue about unused-receiver revivelib/core_test.go:77:7 revive unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _ revivelib/core_test.go:81:7 revive unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _ rule/context_as_argument.go:76:7 revive unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _ rule/var_naming.go:73:7 revive unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _ rule/modifies_value_receiver.go:59:7 revive unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _ rule/filename_format.go:43:7 revive unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _ * refactor: fix revive issues about unused-parameter revivelib/core_test.go:81:24 revive unused-parameter: parameter 'file' seems to be unused, consider removing or renaming it as _ revivelib/core_test.go:81:41 revive unused-parameter: parameter 'arguments' seems to be unused, consider removing or renaming it as _ * refactor: fix gocritic issues about commentedOutCode test/utils_test.go:119:5 gocritic commentedOutCode: may want to remove commented-out code rule/unreachable_code.go:65:3 gocritic commentedOutCode: may want to remove commented-out code
2024-12-12 08:42:41 +01:00
return "", nil, fmt.Errorf("failed to read %q, got %w", modFileName, err)
}
modAst, err := modfile.ParseLax(modFileName, mod, nil)
if err != nil {
refactor: fix linting issues (#1188) * refactor: fix thelper issues test/utils_test.go:19:6 thelper test helper function should start from t.Helper() test/utils_test.go:42:6 thelper test helper function should start from t.Helper() test/utils_test.go:63:6 thelper test helper function should start from t.Helper() test/utils_test.go:146:6 thelper test helper function should start from t.Helper() * refactor: fix govet issues rule/error_strings.go:50:21 govet printf: non-constant format string in call to fmt.Errorf * refactor: fix gosimple issue rule/bare_return.go:52:9 gosimple S1016: should convert w (type lintBareReturnRule) to bareReturnFinder instead of using struct literal * refactor: fix errorlint issues lint/filefilter.go:70:86 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors lint/filefilter.go:113:104 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors lint/filefilter.go:125:89 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors lint/linter.go:166:72 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors lint/linter.go:171:73 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors config/config.go:174:57 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors config/config.go:179:64 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors * refactor: fix revive issue about comment spacing cli/main.go:31:2 revive comment-spacings: no space between comment delimiter and comment text * refactor: fix revive issue about unused-receiver revivelib/core_test.go:77:7 revive unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _ revivelib/core_test.go:81:7 revive unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _ rule/context_as_argument.go:76:7 revive unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _ rule/var_naming.go:73:7 revive unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _ rule/modifies_value_receiver.go:59:7 revive unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _ rule/filename_format.go:43:7 revive unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _ * refactor: fix revive issues about unused-parameter revivelib/core_test.go:81:24 revive unused-parameter: parameter 'file' seems to be unused, consider removing or renaming it as _ revivelib/core_test.go:81:41 revive unused-parameter: parameter 'arguments' seems to be unused, consider removing or renaming it as _ * refactor: fix gocritic issues about commentedOutCode test/utils_test.go:119:5 gocritic commentedOutCode: may want to remove commented-out code rule/unreachable_code.go:65:3 gocritic commentedOutCode: may want to remove commented-out code
2024-12-12 08:42:41 +01:00
return "", nil, fmt.Errorf("failed to parse %q, got %w", modFileName, err)
}
if modAst.Go == nil {
return "", nil, fmt.Errorf("%q does not specify a Go version", modFileName)
}
ver, err = goversion.NewVersion(modAst.Go.Version)
return filepath.Dir(modFileName), ver, err
}
func retrieveModFile(dir string) (string, error) {
const lookingForFile = "go.mod"
for {
// filepath.Dir returns 'C:\' on Windows, and '/' on Unix
isRootDir := (dir == filepath.VolumeName(dir)+string(filepath.Separator))
if dir == "." || isRootDir {
return "", fmt.Errorf("did not found %q file", lookingForFile)
}
lookingForFilePath := filepath.Join(dir, lookingForFile)
info, err := os.Stat(lookingForFilePath)
if err != nil || info.IsDir() {
// lets check the parent dir
dir = filepath.Dir(dir)
continue
}
return lookingForFilePath, nil
}
}
2018-05-31 19:42:58 -07:00
// isGenerated reports whether the source file is generated code
// according the rules from https://golang.org/s/generatedcode.
// This is inherited from the original go lint.
func isGenerated(src []byte) bool {
sc := bufio.NewScanner(bytes.NewReader(src))
for sc.Scan() {
b := sc.Bytes()
2024-12-08 11:08:54 +01:00
if bytes.HasPrefix(b, generatedPrefix) && bytes.HasSuffix(b, generatedSuffix) && len(b) >= len(generatedPrefix)+len(generatedSuffix) {
2018-05-31 19:42:58 -07:00
return true
}
}
return false
2017-09-01 18:36:47 -07:00
}
// addInvalidFileFailure adds a failure for an invalid formatted file
func addInvalidFileFailure(filename, errStr string, failures chan Failure) {
position := getPositionInvalidFile(filename, errStr)
failures <- Failure{
Confidence: 1,
Failure: fmt.Sprintf("invalid file %s: %v", filename, errStr),
Category: failureCategoryValidity,
Position: position,
}
}
// errPosRegexp matches with an NewFile error message
// i.e. : corrupted.go:10:4: expected '}', found 'EOF
// first group matches the line and the second group, the column
2022-04-10 11:55:13 +02:00
var errPosRegexp = regexp.MustCompile(`.*:(\d*):(\d*):.*$`)
// getPositionInvalidFile gets the position of the error in an invalid file
func getPositionInvalidFile(filename, s string) FailurePosition {
pos := errPosRegexp.FindStringSubmatch(s)
if len(pos) < 3 {
return FailurePosition{}
}
line, err := strconv.Atoi(pos[1])
if err != nil {
return FailurePosition{}
}
column, err := strconv.Atoi(pos[2])
if err != nil {
return FailurePosition{}
}
return FailurePosition{
Start: token.Position{
Filename: filename,
Line: line,
Column: column,
},
}
}