1
0
mirror of https://github.com/mgechev/revive.git synced 2025-06-12 23:37:32 +02:00
revive/rule/error_strings.go

194 lines
4.5 KiB
Go
Raw Normal View History

2018-01-25 11:06:56 -08:00
package rule
import (
"fmt"
2018-01-25 11:06:56 -08:00
"go/ast"
"go/token"
"strconv"
"strings"
2018-01-25 11:06:56 -08:00
"unicode"
"unicode/utf8"
"github.com/mgechev/revive/lint"
)
2024-12-01 17:44:41 +02:00
// ErrorStringsRule lints error strings.
type ErrorStringsRule struct {
errorFunctions map[string]map[string]struct{}
}
2018-01-25 11:06:56 -08:00
// Configure validates the rule configuration, and configures the rule accordingly.
//
// Configuration implements the [lint.ConfigurableRule] interface.
func (r *ErrorStringsRule) Configure(arguments lint.Arguments) error {
r.errorFunctions = map[string]map[string]struct{}{
"fmt": {
"Errorf": {},
},
"errors": {
"Errorf": {},
"WithMessage": {},
"Wrap": {},
"New": {},
"WithMessagef": {},
"Wrapf": {},
},
}
var invalidCustomFunctions []string
for _, argument := range arguments {
if functionName, ok := argument.(string); ok {
fields := strings.Split(strings.TrimSpace(functionName), ".")
if len(fields) != 2 || len(fields[0]) == 0 || len(fields[1]) == 0 {
invalidCustomFunctions = append(invalidCustomFunctions, functionName)
continue
}
r.errorFunctions[fields[0]] = map[string]struct{}{fields[1]: {}}
}
}
if len(invalidCustomFunctions) != 0 {
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 fmt.Errorf("found invalid custom function: %s", strings.Join(invalidCustomFunctions, ","))
}
return nil
}
// Apply applies the rule to given file.
func (r *ErrorStringsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
var failures []lint.Failure
2018-01-25 11:06:56 -08:00
fileAst := file.AST
walker := lintErrorStrings{
file: file,
fileAst: fileAst,
errorFunctions: r.errorFunctions,
2018-01-25 11:06:56 -08:00
onFailure: func(failure lint.Failure) {
failures = append(failures, failure)
},
}
ast.Walk(walker, fileAst)
return failures
}
// Name returns the rule name.
2022-04-10 11:55:13 +02:00
func (*ErrorStringsRule) Name() string {
2018-01-27 17:01:18 -08:00
return "error-strings"
2018-01-25 11:06:56 -08:00
}
type lintErrorStrings struct {
file *lint.File
fileAst *ast.File
errorFunctions map[string]map[string]struct{}
onFailure func(lint.Failure)
2018-01-25 11:06:56 -08:00
}
// Visit browses the AST
2018-01-25 11:06:56 -08:00
func (w lintErrorStrings) Visit(n ast.Node) ast.Visitor {
ce, ok := n.(*ast.CallExpr)
if !ok {
return w
}
if len(ce.Args) < 1 {
2018-01-25 11:06:56 -08:00
return w
}
// expression matches the known pkg.function
ok = w.match(ce)
if !ok {
2018-01-25 11:06:56 -08:00
return w
}
str, ok := w.getMessage(ce)
if !ok {
2018-01-25 11:06:56 -08:00
return w
}
s, _ := strconv.Unquote(str.Value) // can assume well-formed Go
if s == "" {
return w
}
clean, conf := lintErrorString(s)
if clean {
return w
}
w.onFailure(lint.Failure{
Node: str,
Confidence: conf,
Category: lint.FailureCategoryErrors,
2018-01-25 11:06:56 -08:00
Failure: "error strings should not be capitalized or end with punctuation or a newline",
})
return w
}
// match returns true if the expression corresponds to the known pkg.function
// i.e.: errors.Wrap
func (w lintErrorStrings) match(expr *ast.CallExpr) bool {
sel, ok := expr.Fun.(*ast.SelectorExpr)
if !ok {
return false
}
// retrieve the package
id, ok := sel.X.(*ast.Ident)
if !ok {
return false
}
functions, ok := w.errorFunctions[id.Name]
if !ok {
return false
}
// retrieve the function
_, ok = functions[sel.Sel.Name]
return ok
}
// getMessage returns the message depending on its position
// returns false if the cast is unsuccessful
func (w lintErrorStrings) getMessage(expr *ast.CallExpr) (s *ast.BasicLit, success bool) {
str, ok := w.checkArg(expr, 0)
if ok {
return str, true
}
if len(expr.Args) < 2 {
return s, false
}
str, ok = w.checkArg(expr, 1)
if !ok {
return s, false
}
return str, true
}
func (lintErrorStrings) checkArg(expr *ast.CallExpr, arg int) (s *ast.BasicLit, success bool) {
str, ok := expr.Args[arg].(*ast.BasicLit)
if !ok {
return s, false
}
if str.Kind != token.STRING {
return s, false
}
return str, true
}
2018-01-25 11:06:56 -08:00
func lintErrorString(s string) (isClean bool, conf float64) {
const basicConfidence = 0.8
const capConfidence = basicConfidence - 0.2
first, firstN := utf8.DecodeRuneInString(s)
last, _ := utf8.DecodeLastRuneInString(s)
if last == '.' || last == ':' || last == '!' || last == '\n' {
return false, basicConfidence
}
if unicode.IsUpper(first) {
// People use proper nouns and exported Go identifiers in error strings,
// so decrease the confidence of warnings for capitalization.
if len(s) <= firstN {
return false, capConfidence
}
// Flag strings starting with something that doesn't look like an initialism.
if second, _ := utf8.DecodeRuneInString(s[firstN:]); !unicode.IsUpper(second) {
return false, capConfidence
}
}
return true, 0
}