1
0
mirror of https://github.com/mgechev/revive.git synced 2025-11-23 22:04:49 +02:00
Files
revive/rule/error_return.go
chavacava 92f28cb5e1 refactor: moves code related to AST from rule.utils into astutils package (#1380)
Modifications summary:

* Moves AST-related functions from rule/utils.go to astutils/ast_utils.go (+ modifies function calls)
* Renames some of these AST-related functions
* Avoids instantiating a printer config at each call to astutils.GoFmt
* Uses astutils.IsIdent and astutils.IsPkgDotName when possible
2025-05-26 13:18:38 +02:00

53 lines
1.4 KiB
Go

package rule
import (
"go/ast"
"github.com/mgechev/revive/internal/astutils"
"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 := astutils.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 astutils.IsIdent(r.Type, "error") {
failures = append(failures, lint.Failure{
Category: lint.FailureCategoryStyle,
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"
}