-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
typealiases.go
103 lines (93 loc) · 2.62 KB
/
typealiases.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package typealiases
import (
"fmt"
"go/ast"
"slices"
"strings"
"github.com/gostaticanalysis/comment/passes/commentmap"
"github.com/k1LoW/gostyle/config"
"github.com/k1LoW/gostyle/reporter"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
const (
name = "typealiases"
doc = "Analyzer based on https://google.github.io/styleguide/go/decisions#type-aliases"
msg = "Type aliases are rare; their primary use is to aid migrating packages to new source code locations. Don’t use type aliasing when it is not needed (ref: https://google.github.io/styleguide/go/decisions#type-aliases )"
)
var (
disable bool
includeGenerated bool
exclude string
)
// Analyzer based on https://google.github.io/styleguide/go/decisions#type-aliases
var Analyzer = &analysis.Analyzer{
Name: name,
Doc: doc,
Run: run,
Requires: []*analysis.Analyzer{
inspect.Analyzer,
commentmap.Analyzer,
},
}
// AnalyzerWithConfig based on https://google.github.io/styleguide/go/decisions#type-aliases
var AnalyzerWithConfig = &analysis.Analyzer{
Name: name,
Doc: doc,
Run: run,
Requires: []*analysis.Analyzer{
config.Loader,
inspect.Analyzer,
commentmap.Analyzer,
},
}
func run(pass *analysis.Pass) (any, error) {
c, err := config.Load(pass)
if err != nil {
return nil, err
}
words := strings.Split(exclude, ",")
var opts []reporter.Option
if c != nil {
disable = c.IsDisabled(name)
words = c.AnalyzersSettings.Typealiases.Exclude
includeGenerated = c.AnalyzersSettings.Typealiases.IncludeGenerated
opts = append(opts, reporter.ExcludeFiles(c.ConfigDir, c.ExcludeFiles))
}
if disable {
return nil, nil
}
i, ok := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
if !ok {
return nil, fmt.Errorf("unexpected result type from inspect: %T", pass.ResultOf[inspect.Analyzer])
}
nodeFilter := []ast.Node{
(*ast.TypeSpec)(nil),
}
if includeGenerated {
opts = append(opts, reporter.IncludeGenerated())
}
r, err := reporter.New(name, pass, opts...)
if err != nil {
return nil, err
}
i.Preorder(nodeFilter, func(n ast.Node) {
switch n := n.(type) {
case *ast.TypeSpec:
if slices.Contains(words, n.Name.Name) {
return
}
if n.Assign != 0 {
r.Append(n.Pos(), fmt.Sprintf("%s: %s", msg, n.Name.Name))
}
}
})
r.Report()
return nil, nil
}
func init() {
Analyzer.Flags.BoolVar(&disable, "disable", false, "disable "+name+" analyzer")
Analyzer.Flags.BoolVar(&includeGenerated, "include-generated", false, "include generated codes")
Analyzer.Flags.StringVar(&exclude, "exclude", "", "exclude words (comma separated)")
}