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
|
|
|
|
|
2024-12-04 17:43:00 +01:00
|
|
|
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
|
|
|
|
2024-12-04 17:43:00 +01: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"
|
|
|
|
}
|