1
0
mirror of https://github.com/mgechev/revive.git synced 2025-06-10 23:27:48 +02:00
revive/rule/use_errors_new.go
Oleksandr Redko 395f7902d3
refactor: replace failure Category raw string with constant (#1196)
* refactor: replace Category raw strings with constants

* Add type FailureCategory; add comments for constants
2025-01-18 12:16:19 +01:00

61 lines
1.2 KiB
Go

package rule
import (
"go/ast"
"github.com/mgechev/revive/lint"
)
// UseErrorsNewRule spots calls to fmt.Errorf that can be replaced by errors.New.
type UseErrorsNewRule struct{}
// Apply applies the rule to given file.
func (*UseErrorsNewRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
var failures []lint.Failure
walker := lintFmtErrorf{
onFailure: func(failure lint.Failure) {
failures = append(failures, failure)
},
}
ast.Walk(walker, file.AST)
return failures
}
// Name returns the rule name.
func (*UseErrorsNewRule) Name() string {
return "use-errors-new"
}
type lintFmtErrorf struct {
onFailure func(lint.Failure)
}
func (w lintFmtErrorf) Visit(n ast.Node) ast.Visitor {
funcCall, ok := n.(*ast.CallExpr)
if !ok {
return w // not a function call
}
isFmtErrorf := isPkgDot(funcCall.Fun, "fmt", "Errorf")
if !isFmtErrorf {
return w // not a call to fmt.Errorf
}
if len(funcCall.Args) > 1 {
return w // the use of fmt.Errorf is legit
}
// the call is of the form fmt.Errorf("...")
w.onFailure(lint.Failure{
Category: lint.FailureCategoryErrors,
Node: n,
Confidence: 1,
Failure: "replace fmt.Errorf by errors.New",
})
return w
}