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
|
package analyzer
import (
"flag"
"go/ast"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
const InterfaceMaxMethodsFlag = "max"
const defaultMaxMethods = 10
// New returns new interfacebloat analyzer.
func New() *analysis.Analyzer {
return &analysis.Analyzer{
Name: "interfacebloat",
Doc: "A linter that checks the number of methods inside an interface.",
Run: run,
Flags: flags(),
Requires: []*analysis.Analyzer{inspect.Analyzer},
}
}
func flags() flag.FlagSet {
flags := flag.NewFlagSet("", flag.ExitOnError)
flags.Int(InterfaceMaxMethodsFlag, 10, "maximum number of methods")
return *flags
}
func run(pass *analysis.Pass) (interface{}, error) {
maxMethods, ok := pass.Analyzer.Flags.Lookup(InterfaceMaxMethodsFlag).Value.(flag.Getter).Get().(int)
if !ok {
maxMethods = defaultMaxMethods
}
insp := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
filter := []ast.Node{
(*ast.InterfaceType)(nil),
}
insp.Preorder(filter, func(node ast.Node) {
i, ok := node.(*ast.InterfaceType)
if !ok {
return
}
if len(i.Methods.List) > maxMethods {
pass.Reportf(node.Pos(), `the interface has more than %d methods: %d`, maxMethods, len(i.Methods.List))
}
})
return nil, nil
}
|