1
0
mirror of https://github.com/mgechev/revive.git synced 2025-11-23 22:04:49 +02:00
Files
revive/rule/function_result_limit.go

72 lines
1.7 KiB
Go
Raw Normal View History

package rule
import (
"errors"
"fmt"
"go/ast"
"github.com/mgechev/revive/lint"
)
2024-12-01 17:44:41 +02:00
// FunctionResultsLimitRule limits the maximum number of results a function can return.
2021-10-17 20:34:48 +02:00
type FunctionResultsLimitRule struct {
max int
}
2022-04-10 09:06:59 +02:00
// Apply applies the rule to given file.
func (r *FunctionResultsLimitRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
var failures []lint.Failure
for _, decl := range file.AST.Decls {
funcDecl, ok := decl.(*ast.FuncDecl)
if !ok {
continue
}
num := 0
hasResults := funcDecl.Type.Results != nil
if hasResults {
num = funcDecl.Type.Results.NumFields()
}
if num <= r.max {
continue
}
failures = append(failures, lint.Failure{
Confidence: 1,
Failure: fmt.Sprintf("maximum number of return results per function exceeded; max %d but got %d", r.max, num),
Node: funcDecl.Type,
})
}
return failures
}
// Name returns the rule name.
2022-04-10 11:55:13 +02:00
func (*FunctionResultsLimitRule) Name() string {
return "function-result-limit"
}
const defaultResultsLimit = 3
// Configure validates the rule configuration, and configures the rule accordingly.
//
// Configuration implements the [lint.ConfigurableRule] interface.
func (r *FunctionResultsLimitRule) Configure(arguments lint.Arguments) error {
if len(arguments) < 1 {
r.max = defaultResultsLimit
return nil
}
2024-10-01 12:14:02 +02:00
maxResults, ok := arguments[0].(int64) // Alt. non panicking version
if !ok {
return fmt.Errorf(`invalid value passed as return results number to the "function-result-limit" rule; need int64 but got %T`, arguments[0])
}
if maxResults < 0 {
return errors.New(`the value passed as return results number to the "function-result-limit" rule cannot be negative`)
}
2024-10-01 12:14:02 +02:00
r.max = int(maxResults)
return nil
}