1
0
mirror of https://github.com/mgechev/revive.git synced 2025-06-06 23:16:16 +02:00
revive/rule/argument_limit.go

68 lines
1.5 KiB
Go
Raw Normal View History

2018-01-21 18:04:41 -08:00
package rule
2017-11-19 18:23:01 -08:00
import (
"errors"
2017-11-19 18:23:01 -08:00
"fmt"
"go/ast"
2018-01-24 15:44:03 -08:00
"github.com/mgechev/revive/lint"
2017-11-19 18:23:01 -08:00
)
2024-12-01 17:44:41 +02:00
// ArgumentsLimitRule lints the number of arguments a function can receive.
2021-10-17 20:34:48 +02:00
type ArgumentsLimitRule struct {
2024-10-01 12:14:02 +02:00
max int
2021-10-17 20:34:48 +02:00
}
2017-11-19 18:23:01 -08:00
const defaultArgumentsLimit = 8
// Configure validates the rule configuration, and configures the rule accordingly.
//
// Configuration implements the [lint.ConfigurableRule] interface.
func (r *ArgumentsLimitRule) Configure(arguments lint.Arguments) error {
2024-10-01 12:14:02 +02:00
if len(arguments) < 1 {
r.max = defaultArgumentsLimit
return nil
2017-11-19 18:23:01 -08:00
}
2024-10-01 12:14:02 +02:00
maxArguments, ok := arguments[0].(int64) // Alt. non panicking version
if !ok {
return errors.New(`invalid value passed as argument number to the "argument-limit" rule`)
2024-10-01 12:14:02 +02:00
}
r.max = int(maxArguments)
return nil
2022-04-10 09:06:59 +02:00
}
// Apply applies the rule to given file.
func (r *ArgumentsLimitRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
2018-01-24 15:44:03 -08:00
var failures []lint.Failure
2017-11-19 18:23:01 -08:00
for _, decl := range file.AST.Decls {
funcDecl, ok := decl.(*ast.FuncDecl)
if !ok {
continue
}
2017-11-19 18:23:01 -08:00
numParams := 0
for _, l := range funcDecl.Type.Params.List {
numParams += len(l.Names)
}
2024-10-01 12:14:02 +02:00
if numParams <= r.max {
continue
2017-11-19 18:23:01 -08:00
}
2024-10-01 12:14:02 +02:00
failures = append(failures, lint.Failure{
2024-10-01 12:14:02 +02:00
Confidence: 1,
Failure: fmt.Sprintf("maximum number of arguments per function exceeded; max %d but got %d", r.max, numParams),
Node: funcDecl.Type,
2024-10-01 12:14:02 +02:00
})
}
return failures
}
// Name returns the rule name.
func (*ArgumentsLimitRule) Name() string {
return "argument-limit"
2017-11-19 18:23:01 -08:00
}