-
Notifications
You must be signed in to change notification settings - Fork 113
/
ruleguard_checker.go
282 lines (258 loc) · 7.71 KB
/
ruleguard_checker.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
280
281
282
package checkers
import (
"bytes"
"errors"
"fmt"
"go/ast"
"go/token"
"log"
"os"
"path/filepath"
"sort"
"strings"
"github.com/quasilyte/go-ruleguard/ruleguard"
"github.com/go-critic/go-critic/framework/linter"
)
func init() {
var info linter.CheckerInfo
info.Name = "ruleguard"
info.Tags = []string{"style", "experimental"}
info.Params = linter.CheckerParams{
"rules": {
Value: "",
Usage: "comma-separated list of gorule file paths. Glob patterns such as 'rules-*.go' may be specified",
},
"debug": {
Value: "",
Usage: "enable debug for the specified named rules group",
},
"failOnError": {
Value: false,
Usage: "deprecated, use failOn param; if set to true, identical to failOn='all', otherwise failOn=''",
},
"failOn": {
Value: "",
Usage: `Determines the behavior when an error occurs while parsing ruleguard files.
If flag is not set, log error and skip rule files that contain an error.
If flag is set, the value must be a comma-separated list of error conditions.
* 'import': rule refers to a package that cannot be loaded.
* 'dsl': gorule file does not comply with the ruleguard DSL.`,
},
"enable": {
Value: "<all>",
Usage: "comma-separated list of enabled groups or skip empty to enable everything",
},
"disable": {
Value: "",
Usage: "comma-separated list of disabled groups or skip empty to enable everything",
},
}
info.Summary = "Runs user-defined rules using ruleguard linter"
info.Details = "Reads a rules file and turns them into go-critic checkers."
info.Before = `N/A`
info.After = `N/A`
info.Note = "See https://github.com/quasilyte/go-ruleguard."
collection.AddChecker(&info, func(ctx *linter.CheckerContext) (linter.FileWalker, error) {
return newRuleguardChecker(&info, ctx)
})
}
// parseErrorHandler is used to determine whether to ignore or fail ruleguard parsing errors.
type parseErrorHandler struct {
// failureConditions is a map of predicates which are evaluated against a ruleguard parsing error.
// If at least one predicate returns true, then an error is returned.
// Otherwise, the ruleguard file is skipped.
failureConditions map[string]func(err error) bool
}
// failOnParseError returns true if a parseError occurred and that error should be not be ignored.
func (e parseErrorHandler) failOnParseError(parseError error) bool {
for _, p := range e.failureConditions {
if p(parseError) {
return true
}
}
return false
}
func newErrorHandler(failOnErrorFlag string) (*parseErrorHandler, error) {
h := parseErrorHandler{
failureConditions: make(map[string]func(err error) bool),
}
var failOnErrorPredicates = map[string]func(error) bool{
"dsl": func(err error) bool { var e *ruleguard.ImportError; return !errors.As(err, &e) },
"import": func(err error) bool { var e *ruleguard.ImportError; return errors.As(err, &e) },
"all": func(err error) bool { return true },
}
for _, k := range strings.Split(failOnErrorFlag, ",") {
if k == "" {
continue
}
if p, ok := failOnErrorPredicates[k]; ok {
h.failureConditions[k] = p
} else {
// Wrong flag value.
supportedValues := []string{}
for key := range failOnErrorPredicates {
supportedValues = append(supportedValues, key)
}
return nil, fmt.Errorf("ruleguard init error: 'failOnError' flag '%s' is invalid. It must be a comma-separated list and supported values are '%s'",
k, strings.Join(supportedValues, ","))
}
}
return &h, nil
}
func newRuleguardChecker(info *linter.CheckerInfo, ctx *linter.CheckerContext) (*ruleguardChecker, error) {
c := &ruleguardChecker{
ctx: ctx,
debugGroup: info.Params.String("debug"),
}
rulesFlag := info.Params.String("rules")
if rulesFlag == "" {
return c, nil
}
failOn := info.Params.String("failOn")
if failOn == "" {
if info.Params.Bool("failOnError") {
failOn = "all"
}
}
h, err := newErrorHandler(failOn)
if err != nil {
return nil, err
}
engine := ruleguard.NewEngine()
engine.InferBuildContext()
fset := token.NewFileSet()
filePatterns := strings.Split(rulesFlag, ",")
enabledGroups := make(map[string]bool)
disabledGroups := make(map[string]bool)
for _, g := range strings.Split(info.Params.String("disable"), ",") {
g = strings.TrimSpace(g)
disabledGroups[g] = true
}
flagEnable := info.Params.String("enable")
if flagEnable != "<all>" {
for _, g := range strings.Split(flagEnable, ",") {
g = strings.TrimSpace(g)
enabledGroups[g] = true
}
}
ruleguardDebug := os.Getenv("GOCRITIC_RULEGUARD_DEBUG") != ""
loadContext := &ruleguard.LoadContext{
Fset: fset,
DebugImports: ruleguardDebug,
DebugPrint: debugPrint,
GroupFilter: func(g string) bool {
whyDisabled := ""
enabled := flagEnable == "<all>" || enabledGroups[g]
switch {
case !enabled:
whyDisabled = "not enabled by -enabled flag"
case disabledGroups[g]:
whyDisabled = "disabled by -disable flag"
}
if ruleguardDebug {
if whyDisabled != "" {
debugPrint(fmt.Sprintf("(-) %s is %s", g, whyDisabled))
} else {
debugPrint(fmt.Sprintf("(+) %s is enabled", g))
}
}
return whyDisabled == ""
},
}
loaded := 0
for _, filePattern := range filePatterns {
filenames, err := filepath.Glob(strings.TrimSpace(filePattern))
if err != nil {
// The only possible returned error is ErrBadPattern, when pattern is malformed.
log.Printf("ruleguard init error: %+v", err)
continue
}
if len(filenames) == 0 {
return nil, fmt.Errorf("ruleguard init error: no file matching '%s'", strings.TrimSpace(filePattern))
}
for _, filename := range filenames {
data, err := os.ReadFile(filename)
if err != nil {
if h.failOnParseError(err) {
return nil, fmt.Errorf("ruleguard init error: %+v", err)
}
log.Printf("ruleguard init error, skip %s: %+v", filename, err)
}
if err := engine.Load(loadContext, filename, bytes.NewReader(data)); err != nil {
if h.failOnParseError(err) {
return nil, fmt.Errorf("ruleguard init error: %+v", err)
}
log.Printf("ruleguard init error, skip %s: %+v", filename, err)
}
loaded++
}
}
if loaded != 0 {
c.engine = engine
}
return c, nil
}
type ruleguardChecker struct {
ctx *linter.CheckerContext
debugGroup string
engine *ruleguard.Engine
}
func (c *ruleguardChecker) WalkFile(f *ast.File) {
if c.engine == nil {
return
}
runRuleguardEngine(c.ctx, f, c.engine, &ruleguard.RunContext{
Debug: c.debugGroup,
DebugPrint: func(s string) {
fmt.Fprintln(os.Stderr, s)
},
Pkg: c.ctx.Pkg,
Types: c.ctx.TypesInfo,
Sizes: c.ctx.SizesInfo,
Fset: c.ctx.FileSet,
})
}
func runRuleguardEngine(ctx *linter.CheckerContext, f *ast.File, e *ruleguard.Engine, runCtx *ruleguard.RunContext) {
type ruleguardReport struct {
node ast.Node
message string
fix linter.QuickFix
}
var reports []ruleguardReport
runCtx.Report = func(data *ruleguard.ReportData) {
// TODO(quasilyte): investigate whether we should add a rule name as
// a message prefix here.
r := ruleguardReport{
node: data.Node,
message: data.Message,
}
fix := data.Suggestion
if fix != nil {
r.fix = linter.QuickFix{
From: fix.From,
To: fix.To,
Replacement: fix.Replacement,
}
}
reports = append(reports, r)
}
if err := e.Run(runCtx, f); err != nil {
// Normally this should never happen, but since
// we don't have a better mechanism to report errors,
// emit a warning.
ctx.Warn(f, "execution error: %v", err)
}
sort.Slice(reports, func(i, j int) bool {
return reports[i].message < reports[j].message
})
for _, report := range reports {
if report.fix.Replacement != nil {
ctx.WarnFixable(report.node, report.fix, "%s", report.message)
} else {
ctx.Warn(report.node, "%s", report.message)
}
}
}
func debugPrint(s string) {
fmt.Println("debug:", s)
}