forked from mgechev/revive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
argument-limit.go
84 lines (70 loc) · 1.58 KB
/
argument-limit.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package rule
import (
"fmt"
"go/ast"
"sync"
"github.com/mgechev/revive/lint"
)
// ArgumentsLimitRule lints given else constructs.
type ArgumentsLimitRule struct {
total int
sync.Mutex
}
const defaultArgumentsLimit = 8
func (r *ArgumentsLimitRule) configure(arguments lint.Arguments) {
r.Lock()
defer r.Unlock()
if r.total == 0 {
if len(arguments) < 1 {
r.total = defaultArgumentsLimit
return
}
total, ok := arguments[0].(int64) // Alt. non panicking version
if !ok {
panic(`invalid value passed as argument number to the "argument-limit" rule`)
}
r.total = int(total)
}
}
// Apply applies the rule to given file.
func (r *ArgumentsLimitRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
r.configure(arguments)
var failures []lint.Failure
onFailure := func(failure lint.Failure) {
failures = append(failures, failure)
}
walker := lintArgsNum{
total: r.total,
onFailure: onFailure,
}
ast.Walk(walker, file.AST)
return failures
}
// Name returns the rule name.
func (*ArgumentsLimitRule) Name() string {
return "argument-limit"
}
type lintArgsNum struct {
total int
onFailure func(lint.Failure)
}
func (w lintArgsNum) Visit(n ast.Node) ast.Visitor {
node, ok := n.(*ast.FuncDecl)
if ok {
num := 0
for _, l := range node.Type.Params.List {
for range l.Names {
num++
}
}
if num > w.total {
w.onFailure(lint.Failure{
Confidence: 1,
Failure: fmt.Sprintf("maximum number of arguments per function exceeded; max %d but got %d", w.total, num),
Node: node.Type,
})
return w
}
}
return w
}