1
0
mirror of https://github.com/mgechev/revive.git synced 2025-03-03 14:52:54 +02:00
revive/rule/error_return.go
chavacava 275b0184e2
refactor (rule/error-return): replace AST walker by iteration over declarations (#1163)
Co-authored-by: chavacava <salvador.cavadini@gmail.com>
2024-12-04 17:43:00 +01:00

52 lines
1.3 KiB
Go

package rule
import (
"go/ast"
"github.com/mgechev/revive/lint"
)
// ErrorReturnRule ensures that the error return parameter is the last parameter.
type ErrorReturnRule struct{}
// Apply applies the rule to given file.
func (*ErrorReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
var failures []lint.Failure
for _, decl := range file.AST.Decls {
funcDecl, ok := decl.(*ast.FuncDecl)
isFunctionWithMoreThanOneResult := ok && funcDecl.Type.Results != nil && len(funcDecl.Type.Results.List) > 1
if !isFunctionWithMoreThanOneResult {
continue
}
funcResults := funcDecl.Type.Results.List
isLastResultError := isIdent(funcResults[len(funcResults)-1].Type, "error")
if isLastResultError {
continue
}
// An error return parameter should be the last parameter.
// Flag any error parameters found before the last.
for _, r := range funcResults[:len(funcResults)-1] {
if isIdent(r.Type, "error") {
failures = append(failures, lint.Failure{
Category: "style",
Confidence: 0.9,
Node: funcDecl,
Failure: "error should be the last type when returning multiple items",
})
break // only flag one
}
}
}
return failures
}
// Name returns the rule name.
func (*ErrorReturnRule) Name() string {
return "error-return"
}