1
0
mirror of https://github.com/mgechev/revive.git synced 2025-03-05 15:05:47 +02:00
revive/rule/error_return.go

52 lines
1.3 KiB
Go
Raw Normal View History

2018-01-25 11:34:38 -08:00
package rule
import (
"go/ast"
"github.com/mgechev/revive/lint"
)
2024-12-01 17:44:41 +02:00
// ErrorReturnRule ensures that the error return parameter is the last parameter.
2018-01-25 11:34:38 -08:00
type ErrorReturnRule struct{}
// Apply applies the rule to given file.
2022-04-10 11:55:13 +02:00
func (*ErrorReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
2018-01-25 11:34:38 -08:00
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
}
2018-01-25 11:34:38 -08:00
// 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
}
}
}
2018-01-25 11:34:38 -08:00
return failures
}
// Name returns the rule name.
2022-04-10 11:55:13 +02:00
func (*ErrorReturnRule) Name() string {
2018-01-25 11:34:38 -08:00
return "error-return"
}