-
-
Notifications
You must be signed in to change notification settings - Fork 140
/
check.go
484 lines (426 loc) · 12.2 KB
/
check.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package check
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"github.com/ValeLint/vale/core"
"github.com/ValeLint/vale/rule"
"github.com/mitchellh/mapstructure"
jww "github.com/spf13/jwalterweatherman"
"gopkg.in/yaml.v2"
)
const (
ignoreCase = `(?i)`
wordTemplate = `\b(?:%s)\b`
nonwordTemplate = `(?:%s)`
)
type ruleFn func(string, *core.File) []core.Alert
func init() {
var style, path string
loadedStyles := []string{}
loadDefaultChecks()
if core.Config.StylesPath == "" {
return
}
loadedStyles = append(loadedStyles, "vale")
baseDir := core.Config.StylesPath
for _, style = range core.Config.GBaseStyles {
if style == "vale" {
continue
}
loadExternalStyle(filepath.Join(baseDir, style))
loadedStyles = append(loadedStyles, style)
}
for _, styles := range core.Config.SBaseStyles {
for _, style := range styles {
if !core.StringInSlice(style, loadedStyles) {
loadExternalStyle(filepath.Join(baseDir, style))
loadedStyles = append(loadedStyles, style)
}
}
}
for _, chk := range core.Config.Checks {
if !strings.Contains(chk, ".") {
continue
}
check := strings.Split(chk, ".")
if !core.StringInSlice(check[0], loadedStyles) {
fName := check[1] + ".yml"
path = filepath.Join(baseDir, check[0], fName)
loadCheck(fName, path)
}
}
}
func checkRE(err error, rule string) bool {
return core.CheckError(err, fmt.Sprintf("bad regex in %s'!", rule))
}
func formatMessages(msg string, desc string, subs ...string) (string, string) {
return core.FormatMessage(msg, subs...), core.FormatMessage(desc, subs...)
}
func makeAlert(chk Definition, loc []int, txt string) core.Alert {
a := core.Alert{Check: chk.Name, Severity: chk.Level, Span: loc, Link: chk.Link}
a.Message, a.Description = formatMessages(chk.Message, chk.Description,
txt[loc[0]:loc[1]])
return a
}
func checkConditional(txt string, chk Conditional, f *core.File, r []*regexp.Regexp) []core.Alert {
alerts := []core.Alert{}
definitions := r[0].FindAllStringSubmatch(txt, -1)
for _, def := range definitions {
if len(def) > 1 {
f.Sequences = append(f.Sequences, def[1])
}
}
locs := r[1].FindAllStringIndex(txt, -1)
if locs != nil {
for _, loc := range locs {
s := txt[loc[0]:loc[1]]
if !core.StringInSlice(s, f.Sequences) && !core.StringInSlice(s, chk.Exceptions) {
alerts = append(alerts, makeAlert(chk.Definition, loc, txt))
}
}
}
return alerts
}
func checkExistence(txt string, chk Existence, f *core.File, r *regexp.Regexp) []core.Alert {
alerts := []core.Alert{}
locs := r.FindAllStringIndex(txt, -1)
if locs != nil {
for _, loc := range locs {
alerts = append(alerts, makeAlert(chk.Definition, loc, txt))
}
}
return alerts
}
func checkOccurrence(txt string, chk Occurrence, f *core.File, r *regexp.Regexp, lim int) []core.Alert {
var loc []int
alerts := []core.Alert{}
locs := r.FindAllStringIndex(txt, -1)
occurrences := len(locs)
if occurrences > lim {
loc = []int{locs[0][0], locs[occurrences-1][1]}
a := core.Alert{Check: chk.Name, Severity: chk.Level, Span: loc,
Link: chk.Link}
a.Message = chk.Message
a.Description = chk.Description
alerts = append(alerts, a)
}
return alerts
}
func checkRepetition(txt string, chk Repetition, f *core.File, r *regexp.Regexp) []core.Alert {
var curr, prev string
var hit bool
var ploc []int
var count int
alerts := []core.Alert{}
for _, loc := range r.FindAllStringIndex(txt, -1) {
curr = strings.TrimSpace(txt[loc[0]:loc[1]])
hit = curr == prev && curr != ""
if hit {
count++
}
if hit && count > chk.Max {
floc := []int{ploc[0], loc[1]}
a := core.Alert{Check: chk.Name, Severity: chk.Level, Span: floc,
Link: chk.Link}
a.Message, a.Description = formatMessages(chk.Message,
chk.Description, curr)
alerts = append(alerts, a)
count = 0
}
ploc = loc
prev = curr
}
return alerts
}
func checkSubstitution(txt string, chk Substitution, f *core.File, r *regexp.Regexp, repl []string) []core.Alert {
alerts := []core.Alert{}
if !r.MatchString(txt) {
return alerts
}
for _, submat := range r.FindAllStringSubmatchIndex(txt, -1) {
for idx, mat := range submat {
if mat != -1 && idx > 0 && idx%2 == 0 {
loc := []int{mat, submat[idx+1]}
a := core.Alert{Check: chk.Name, Severity: chk.Level, Span: loc,
Link: chk.Link}
a.Message, a.Description = formatMessages(chk.Message,
chk.Description, repl[(idx/2)-1], txt[loc[0]:loc[1]])
alerts = append(alerts, a)
}
}
}
return alerts
}
func checkConsistency(txt string, chk Consistency, f *core.File, r *regexp.Regexp, opts []string) []core.Alert {
alerts := []core.Alert{}
loc := []int{}
matches := r.FindAllStringSubmatchIndex(txt, -1)
for _, submat := range matches {
for idx, mat := range submat {
if mat != -1 && idx > 0 && idx%2 == 0 {
loc = []int{mat, submat[idx+1]}
f.Sequences = append(f.Sequences, r.SubexpNames()[idx/2])
}
}
}
if matches != nil && core.AllStringsInSlice(opts, f.Sequences) {
chk.Name = chk.Extends
alerts = append(alerts, makeAlert(chk.Definition, loc, txt))
}
return alerts
}
func checkScript(txt string, chkDef Script, exe string, f *core.File) []core.Alert {
alerts := []core.Alert{}
cmd := exec.Command(chkDef.Runtime, exe, txt)
out, err := cmd.Output()
if core.CheckError(err, exe) {
merr := json.Unmarshal(out, &alerts)
core.CheckError(merr, exe)
}
return alerts
}
func addScriptCheck(chkName string, chkDef Script) {
style := strings.Split(chkName, ".")[0]
exe := filepath.Join(core.Config.StylesPath, style, "scripts", chkDef.Exe)
if core.FileExists(exe) {
fn := func(text string, file *core.File) []core.Alert {
return checkScript(text, chkDef, exe, file)
}
updateAllChecks(chkDef.Definition, fn)
} else {
jww.WARN.Println(fmt.Sprintf("script '%s' not found!", chkName))
}
}
func addConsistencyCheck(chkName string, chkDef Consistency) {
var chkRE string
regex := ""
if chkDef.Ignorecase {
regex += ignoreCase
}
if !chkDef.Nonword {
regex += wordTemplate
} else {
regex += nonwordTemplate
}
count := 0
chkKey := strings.Split(chkName, ".")[1]
for v1, v2 := range chkDef.Either {
count += 2
subs := []string{
fmt.Sprintf("%s%d", chkKey, count), fmt.Sprintf("%s%d", chkKey, count+1)}
chkRE = fmt.Sprintf("(?P<%s>%s)|(?P<%s>%s)", subs[0], v1, subs[1], v2)
chkRE = fmt.Sprintf(regex, chkRE)
re, err := regexp.Compile(chkRE)
if checkRE(err, chkName) {
chkDef.Extends = chkName
chkDef.Name = fmt.Sprintf("%s.%s", chkName, v1)
fn := func(text string, file *core.File) []core.Alert {
return checkConsistency(text, chkDef, file, re, subs)
}
updateAllChecks(chkDef.Definition, fn)
}
}
}
func addExistenceCheck(chkName string, chkDef Existence) {
regex := ""
if chkDef.Ignorecase {
regex += ignoreCase
}
regex += strings.Join(chkDef.Raw, "")
if !chkDef.Nonword && len(chkDef.Tokens) > 0 {
regex += wordTemplate
} else {
regex += nonwordTemplate
}
regex = fmt.Sprintf(regex, strings.Join(chkDef.Tokens, "|"))
re, err := regexp.Compile(regex)
if checkRE(err, chkName) {
fn := func(text string, file *core.File) []core.Alert {
return checkExistence(text, chkDef, file, re)
}
updateAllChecks(chkDef.Definition, fn)
}
}
func addRepetitionCheck(chkName string, chkDef Repetition) {
regex := ""
if chkDef.Ignorecase {
regex += ignoreCase
}
regex += `(` + strings.Join(chkDef.Tokens, "|") + `)`
re, err := regexp.Compile(regex)
if checkRE(err, chkName) {
fn := func(text string, file *core.File) []core.Alert {
return checkRepetition(text, chkDef, file, re)
}
updateAllChecks(chkDef.Definition, fn)
}
}
func addOccurrenceCheck(chkName string, chkDef Occurrence) {
re, err := regexp.Compile(chkDef.Token)
if checkRE(err, chkName) && chkDef.Max >= 1 {
fn := func(text string, file *core.File) []core.Alert {
return checkOccurrence(text, chkDef, file, re, chkDef.Max)
}
updateAllChecks(chkDef.Definition, fn)
}
}
func addConditionalCheck(chkName string, chkDef Conditional) {
var re *regexp.Regexp
var expression []*regexp.Regexp
var err error
re, err = regexp.Compile(chkDef.Second)
if !checkRE(err, chkName) {
return
}
expression = append(expression, re)
re, err = regexp.Compile(chkDef.First)
if !checkRE(err, chkName) {
return
}
expression = append(expression, re)
fn := func(text string, file *core.File) []core.Alert {
return checkConditional(text, chkDef, file, expression)
}
updateAllChecks(chkDef.Definition, fn)
}
func addSubstitutionCheck(chkName string, chkDef Substitution) {
regex := ""
tokens := ""
if chkDef.Ignorecase {
regex += ignoreCase
}
if !chkDef.Nonword {
regex += wordTemplate
} else {
regex += nonwordTemplate
}
replacements := []string{}
for regexstr, replacement := range chkDef.Swap {
if strings.Count(regexstr, "(") != strings.Count(regexstr, "?:") {
continue
}
tokens += `(` + regexstr + `)|`
replacements = append(replacements, replacement)
}
regex = fmt.Sprintf(regex, strings.TrimRight(tokens, "|"))
re, err := regexp.Compile(regex)
if checkRE(err, chkName) {
fn := func(text string, file *core.File) []core.Alert {
return checkSubstitution(text, chkDef, file, re, replacements)
}
updateAllChecks(chkDef.Definition, fn)
}
}
func updateAllChecks(chkDef Definition, fn ruleFn) {
chk := Check{Rule: fn, Extends: chkDef.Extends}
chk.Level = core.LevelToInt[chkDef.Level]
chk.Scope = core.Selector{Value: chkDef.Scope}
AllChecks[chkDef.Name] = chk
}
func makeCheck(generic map[string]interface{}, extends string, chkName string) {
if extends == "existence" {
def := Existence{}
if err := mapstructure.Decode(generic, &def); err == nil {
addExistenceCheck(chkName, def)
}
} else if extends == "substitution" {
def := Substitution{}
if err := mapstructure.Decode(generic, &def); err == nil {
addSubstitutionCheck(chkName, def)
}
} else if extends == "occurrence" {
def := Occurrence{}
if err := mapstructure.Decode(generic, &def); err == nil {
addOccurrenceCheck(chkName, def)
}
} else if extends == "repetition" {
def := Repetition{}
if err := mapstructure.Decode(generic, &def); err == nil {
addRepetitionCheck(chkName, def)
}
} else if extends == "consistency" {
def := Consistency{}
if err := mapstructure.Decode(generic, &def); err == nil {
addConsistencyCheck(chkName, def)
}
} else if extends == "conditional" {
def := Conditional{}
if err := mapstructure.Decode(generic, &def); err == nil {
addConditionalCheck(chkName, def)
}
} else if extends == "script" {
def := Script{}
if err := mapstructure.Decode(generic, &def); err == nil {
addScriptCheck(chkName, def)
}
}
}
func addCheck(file []byte, chkName string) {
var extends string
// Load the rule definition.
generic := map[string]interface{}{}
err := yaml.Unmarshal(file, &generic)
if !core.CheckError(err, fmt.Sprintf("unable to read %s!", chkName)) {
return
}
// Ensure that we're given an extension point.
if point, ok := generic["extends"]; !ok {
return
} else if !core.StringInSlice(point.(string), extensionPoints) {
return
} else {
extends = point.(string)
}
// Set default values, if necessary.
generic["name"] = chkName
if level, ok := core.Config.RuleToLevel[chkName]; ok {
generic["level"] = level
} else if _, ok := generic["level"]; !ok {
generic["level"] = "suggestion"
}
if _, ok := generic["scope"]; !ok {
generic["scope"] = "text"
}
makeCheck(generic, extends, chkName)
}
func loadExternalStyle(path string) {
err := filepath.Walk(path,
func(fp string, fi os.FileInfo, err error) error {
if err != nil || fi.IsDir() {
return nil
}
loadCheck(fi.Name(), fp)
return nil
})
core.CheckError(err, path)
}
func loadCheck(fName string, fp string) {
if strings.HasSuffix(fName, ".yml") {
f, err := ioutil.ReadFile(fp)
if !core.CheckError(err, fmt.Sprintf("unable to read %s!", fp)) {
return
}
style := filepath.Base(filepath.Dir(fp))
chkName := style + "." + strings.Split(fName, ".")[0]
if _, ok := AllChecks[chkName]; ok {
jww.WARN.Println(fmt.Sprintf("(%s): duplicate check\n", chkName))
return
}
addCheck(f, chkName)
}
}
func loadDefaultChecks() {
for _, chk := range defaultChecks {
b, err := rule.Asset("rule/" + chk + ".yml")
if err != nil {
continue
}
addCheck(b, "vale."+chk)
}
}