2018-01-21 18:04:41 -08:00
|
|
|
package rule
|
2017-11-19 18:23:01 -08:00
|
|
|
|
|
|
|
import (
|
2024-12-11 19:35:58 +01:00
|
|
|
"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
|
|
|
|
2023-05-20 14:44:34 +02:00
|
|
|
const defaultArgumentsLimit = 8
|
|
|
|
|
2024-12-13 21:38:46 +01:00
|
|
|
// 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
|
2024-12-11 19:35:58 +01:00
|
|
|
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 {
|
2024-12-11 19:35:58 +01:00
|
|
|
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)
|
2024-12-11 19:35:58 +01:00
|
|
|
return nil
|
2022-04-10 09:06:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Apply applies the rule to given file.
|
2024-12-13 21:38:46 +01:00
|
|
|
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
|
|
|
|
2024-12-04 20:53:35 +01:00
|
|
|
for _, decl := range file.AST.Decls {
|
|
|
|
funcDecl, ok := decl.(*ast.FuncDecl)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
2017-11-19 18:23:01 -08:00
|
|
|
|
2024-12-04 20:53:35 +01:00
|
|
|
numParams := 0
|
|
|
|
for _, l := range funcDecl.Type.Params.List {
|
|
|
|
numParams += len(l.Names)
|
|
|
|
}
|
2024-10-01 12:14:02 +02:00
|
|
|
|
2024-12-04 20:53:35 +01:00
|
|
|
if numParams <= r.max {
|
|
|
|
continue
|
2017-11-19 18:23:01 -08:00
|
|
|
}
|
2024-10-01 12:14:02 +02:00
|
|
|
|
2024-12-04 20:53:35 +01:00
|
|
|
failures = append(failures, lint.Failure{
|
2024-10-01 12:14:02 +02:00
|
|
|
Confidence: 1,
|
2024-12-04 20:53:35 +01:00
|
|
|
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
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2024-12-04 20:53:35 +01:00
|
|
|
return failures
|
|
|
|
}
|
|
|
|
|
|
|
|
// Name returns the rule name.
|
|
|
|
func (*ArgumentsLimitRule) Name() string {
|
|
|
|
return "argument-limit"
|
2017-11-19 18:23:01 -08:00
|
|
|
}
|