forked from mgechev/revive
/
max-public-structs.go
88 lines (71 loc) 路 1.7 KB
/
max-public-structs.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
85
86
87
88
package rule
import (
"go/ast"
"strings"
"sync"
"github.com/mgechev/revive/lint"
)
// MaxPublicStructsRule lints given else constructs.
type MaxPublicStructsRule struct {
max int64
sync.Mutex
}
const defaultMaxPublicStructs = 5
func (r *MaxPublicStructsRule) configure(arguments lint.Arguments) {
r.Lock()
defer r.Unlock()
if r.max < 1 {
if len(arguments) < 1 {
r.max = defaultMaxPublicStructs
return
}
checkNumberOfArguments(1, arguments, r.Name())
max, ok := arguments[0].(int64) // Alt. non panicking version
if !ok {
panic(`invalid value passed as argument number to the "max-public-structs" rule`)
}
r.max = max
}
}
// Apply applies the rule to given file.
func (r *MaxPublicStructsRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
r.configure(arguments)
var failures []lint.Failure
fileAst := file.AST
walker := &lintMaxPublicStructs{
fileAst: fileAst,
onFailure: func(failure lint.Failure) {
failures = append(failures, failure)
},
}
ast.Walk(walker, fileAst)
if walker.current > r.max {
walker.onFailure(lint.Failure{
Failure: "you have exceeded the maximum number of public struct declarations",
Confidence: 1,
Node: fileAst,
Category: "style",
})
}
return failures
}
// Name returns the rule name.
func (*MaxPublicStructsRule) Name() string {
return "max-public-structs"
}
type lintMaxPublicStructs struct {
current int64
fileAst *ast.File
onFailure func(lint.Failure)
}
func (w *lintMaxPublicStructs) Visit(n ast.Node) ast.Visitor {
switch v := n.(type) {
case *ast.TypeSpec:
name := v.Name.Name
first := string(name[0])
if strings.ToUpper(first) == first {
w.current++
}
}
return w
}