1
0
mirror of https://github.com/mgechev/revive.git synced 2025-07-15 01:04:40 +02:00

Allow to customize user functions in rule error-strings (#703)

* Allow to customize user functions in rule `error-strings`

* Rollback the Available Rules table format in README

* adds memoization of the rule's configuration

Co-authored-by: chavacava <salvadorcavadini+github@gmail.com>
This commit is contained in:
hulk
2022-07-06 03:51:50 +08:00
committed by GitHub
parent 5caa8cfc63
commit ce7f0669d3
4 changed files with 67 additions and 8 deletions

View File

@ -4,6 +4,8 @@ import (
"go/ast"
"go/token"
"strconv"
"strings"
"sync"
"unicode"
"unicode/utf8"
@ -11,13 +13,20 @@ import (
)
// ErrorStringsRule lints given else constructs.
type ErrorStringsRule struct{}
type ErrorStringsRule struct {
errorFunctions map[string]map[string]struct{}
sync.Mutex
}
// Apply applies the rule to given file.
func (*ErrorStringsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
var failures []lint.Failure
func (r *ErrorStringsRule) configure(arguments lint.Arguments) {
r.Lock()
defer r.Unlock()
errorFunctions := map[string]map[string]struct{}{
if r.errorFunctions != nil {
return
}
r.errorFunctions = map[string]map[string]struct{}{
"fmt": {
"Errorf": {},
},
@ -31,11 +40,33 @@ func (*ErrorStringsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure
},
}
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 {
panic("found invalid custom function: " + strings.Join(invalidCustomFunctions, ","))
}
}
// Apply applies the rule to given file.
func (r *ErrorStringsRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
var failures []lint.Failure
r.configure(arguments)
fileAst := file.AST
walker := lintErrorStrings{
file: file,
fileAst: fileAst,
errorFunctions: errorFunctions,
errorFunctions: r.errorFunctions,
onFailure: func(failure lint.Failure) {
failures = append(failures, failure)
},