-
Notifications
You must be signed in to change notification settings - Fork 0
/
protogetter.go
279 lines (233 loc) · 6.04 KB
/
protogetter.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
package protogetter
import (
"bytes"
"flag"
"fmt"
"go/ast"
"go/format"
"go/token"
"log"
"path/filepath"
"strings"
"github.com/gobwas/glob"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/ast/inspector"
)
type Mode int
const (
StandaloneMode Mode = iota
GolangciLintMode
)
const msgFormat = "avoid direct access to proto field %s, use %s instead"
func NewAnalyzer(cfg *Config) *analysis.Analyzer {
if cfg == nil {
cfg = &Config{}
}
return &analysis.Analyzer{
Name: "protogetter",
Doc: "Reports direct reads from proto message fields when getters should be used",
Flags: flags(cfg),
Run: func(pass *analysis.Pass) (any, error) {
_, err := Run(pass, cfg)
return nil, err
},
}
}
func flags(opts *Config) flag.FlagSet {
fs := flag.NewFlagSet("protogetter", flag.ContinueOnError)
fs.Func("skip-generated-by", "skip files generated with the given prefixes", func(s string) error {
for _, prefix := range strings.Split(s, ",") {
opts.SkipGeneratedBy = append(opts.SkipGeneratedBy, prefix)
}
return nil
})
fs.Func("skip-files", "skip files with the given glob patterns", func(s string) error {
for _, pattern := range strings.Split(s, ",") {
opts.SkipFiles = append(opts.SkipFiles, pattern)
}
return nil
})
fs.BoolVar(&opts.SkipAnyGenerated, "skip-any-generated", false, "skip any generated files")
return *fs
}
type Config struct {
Mode Mode // Zero value is StandaloneMode.
SkipGeneratedBy []string
SkipFiles []string
SkipAnyGenerated bool
ReplaceFirstArgInAppend bool
}
func Run(pass *analysis.Pass, cfg *Config) ([]Issue, error) {
skipGeneratedBy := make([]string, 0, len(cfg.SkipGeneratedBy)+3)
// Always skip files generated by protoc-gen-go, protoc-gen-go-grpc and protoc-gen-grpc-gateway.
skipGeneratedBy = append(skipGeneratedBy, "protoc-gen-go", "protoc-gen-go-grpc", "protoc-gen-grpc-gateway")
for _, s := range cfg.SkipGeneratedBy {
s = strings.TrimSpace(s)
if s == "" {
continue
}
skipGeneratedBy = append(skipGeneratedBy, s)
}
skipFilesGlobPatterns := make([]glob.Glob, 0, len(cfg.SkipFiles))
for _, s := range cfg.SkipFiles {
s = strings.TrimSpace(s)
if s == "" {
continue
}
compile, err := glob.Compile(s)
if err != nil {
return nil, fmt.Errorf("invalid glob pattern: %w", err)
}
skipFilesGlobPatterns = append(skipFilesGlobPatterns, compile)
}
nodeTypes := []ast.Node{
(*ast.AssignStmt)(nil),
(*ast.BinaryExpr)(nil),
(*ast.CallExpr)(nil),
(*ast.SelectorExpr)(nil),
(*ast.StarExpr)(nil),
(*ast.IncDecStmt)(nil),
(*ast.UnaryExpr)(nil),
}
// Skip filtered files.
var files []*ast.File
for _, f := range pass.Files {
if skipGeneratedFile(f, skipGeneratedBy, cfg.SkipAnyGenerated) {
continue
}
if skipFilesByGlob(pass.Fset.File(f.Pos()).Name(), skipFilesGlobPatterns) {
continue
}
files = append(files, f)
// ast.Print(pass.Fset, f)
}
ins := inspector.New(files)
var issues []Issue
filter := NewPosFilter()
ins.Preorder(nodeTypes, func(node ast.Node) {
report := analyse(pass, filter, node, cfg)
if report == nil {
return
}
switch cfg.Mode {
case StandaloneMode:
pass.Report(report.ToDiagReport())
case GolangciLintMode:
issues = append(issues, report.ToIssue(pass.Fset))
}
})
return issues, nil
}
func analyse(pass *analysis.Pass, filter *PosFilter, n ast.Node, cfg *Config) *Report {
// fmt.Printf("\n>>> check: %s\n", formatNode(n))
// ast.Print(pass.Fset, n)
if filter.IsFiltered(n.Pos()) {
// fmt.Printf(">>> filtered\n")
return nil
}
result, err := Process(pass.TypesInfo, filter, n, cfg)
if err != nil {
pass.Report(analysis.Diagnostic{
Pos: n.Pos(),
End: n.End(),
Message: fmt.Sprintf("error: %v", err),
})
return nil
}
// If existing in filter, skip it.
if filter.IsFiltered(n.Pos()) {
return nil
}
if result.Skipped() {
return nil
}
// If the expression has already been replaced, skip it.
if filter.IsAlreadyReplaced(pass.Fset, n.Pos(), n.End()) {
return nil
}
// Add the expression to the filter.
filter.AddAlreadyReplaced(pass.Fset, n.Pos(), n.End())
return &Report{
node: n,
result: result,
}
}
// Issue is used to integrate with golangci-lint's inline auto fix.
type Issue struct {
Pos token.Position
Message string
InlineFix InlineFix
}
type InlineFix struct {
StartCol int // zero-based
Length int
NewString string
}
type Report struct {
node ast.Node
result *Result
}
func (r *Report) ToDiagReport() analysis.Diagnostic {
msg := fmt.Sprintf(msgFormat, r.result.From, r.result.To)
return analysis.Diagnostic{
Pos: r.node.Pos(),
End: r.node.End(),
Message: msg,
SuggestedFixes: []analysis.SuggestedFix{
{
Message: msg,
TextEdits: []analysis.TextEdit{
{
Pos: r.node.Pos(),
End: r.node.End(),
NewText: []byte(r.result.To),
},
},
},
},
}
}
func (r *Report) ToIssue(fset *token.FileSet) Issue {
msg := fmt.Sprintf(msgFormat, r.result.From, r.result.To)
return Issue{
Pos: fset.Position(r.node.Pos()),
Message: msg,
InlineFix: InlineFix{
StartCol: fset.Position(r.node.Pos()).Column - 1,
Length: len(r.result.From),
NewString: r.result.To,
},
}
}
func skipGeneratedFile(f *ast.File, prefixes []string, skipAny bool) bool {
if len(f.Comments) == 0 {
return false
}
firstComment := f.Comments[0].Text()
// https://golang.org/s/generatedcode
if skipAny && strings.HasPrefix(firstComment, "Code generated") {
return true
}
for _, prefix := range prefixes {
if strings.HasPrefix(firstComment, "Code generated by "+prefix) {
return true
}
}
return false
}
func skipFilesByGlob(filename string, patterns []glob.Glob) bool {
for _, pattern := range patterns {
if pattern.Match(filename) || pattern.Match(filepath.Base(filename)) {
return true
}
}
return false
}
func formatNode(node ast.Node) string {
buf := new(bytes.Buffer)
if err := format.Node(buf, token.NewFileSet(), node); err != nil {
log.Printf("Error formatting expression: %v", err)
return ""
}
return buf.String()
}