1
0
mirror of https://github.com/mgechev/revive.git synced 2025-03-21 21:17:06 +02:00
revive/rule/argument-limit.go

63 lines
1.3 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 (
"fmt"
"go/ast"
"strconv"
2018-01-21 18:04:41 -08:00
"github.com/mgechev/revive/linter"
2017-11-19 18:23:01 -08:00
)
// ArgumentsLimitRule lints given else constructs.
type ArgumentsLimitRule struct{}
// Apply applies the rule to given file.
2018-01-21 18:04:41 -08:00
func (r *ArgumentsLimitRule) Apply(file *linter.File, arguments linter.Arguments) []linter.Failure {
2017-11-19 18:23:01 -08:00
if len(arguments) != 1 {
panic(`invalid configuration for "argument-limit"`)
}
total, err := strconv.ParseInt(arguments[0], 10, 32)
if err != nil {
panic(`invalid configuration for "argument-limit"`)
}
2018-01-21 18:04:41 -08:00
var failures []linter.Failure
2017-11-19 18:23:01 -08:00
walker := lintArgsNum{
total: total,
2018-01-21 18:04:41 -08:00
onFailure: func(failure linter.Failure) {
2017-11-19 18:23:01 -08:00
failures = append(failures, failure)
},
}
2018-01-21 18:48:51 -08:00
ast.Walk(walker, file.AST)
2017-11-19 18:23:01 -08:00
return failures
}
// Name returns the rule name.
func (r *ArgumentsLimitRule) Name() string {
return "argument-limit"
}
type lintArgsNum struct {
total int64
2018-01-21 18:04:41 -08:00
onFailure func(linter.Failure)
2017-11-19 18:23:01 -08:00
}
func (w lintArgsNum) Visit(n ast.Node) ast.Visitor {
node, ok := n.(*ast.FuncDecl)
if ok {
num := int64(len(node.Type.Params.List))
if num > w.total {
2018-01-21 18:04:41 -08:00
w.onFailure(linter.Failure{
2017-11-19 18:23:01 -08:00
Failure: fmt.Sprintf("maximum number of arguments per function exceeded; max %d but got %d", w.total, num),
2018-01-21 18:04:41 -08:00
Type: linter.FailureTypeWarning,
2017-11-19 18:23:01 -08:00
Node: node.Type,
})
2017-11-19 20:32:18 -08:00
return w
2017-11-19 18:23:01 -08:00
}
}
return w
}