/
manager.go
executable file
·243 lines (205 loc) · 5.72 KB
/
manager.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
package check
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/errata-ai/vale/config"
"github.com/errata-ai/vale/core"
"github.com/errata-ai/vale/rule"
)
const (
ignoreCase = `(?i)`
wordTemplate = `(?m)\b(?:%s)\b`
nonwordTemplate = `(?m)(?:%s)`
)
// Manager controls the loading and validating of the check extension points.
type Manager struct {
Config *config.Config
scopes map[string]struct{}
rules map[string]Rule
styles []string
}
// NewManager creates a new Manager and loads the rule definitions (that is,
// extended checks) specified by configuration.
func NewManager(config *config.Config) (*Manager, error) {
var path string
mgr := Manager{
Config: config,
rules: make(map[string]Rule),
scopes: make(map[string]struct{}),
}
err := mgr.loadDefaultRules()
if mgr.Config.StylesPath == "" {
// If we're not given a StylesPath, there's nothing left to look for.
return &mgr, err
}
// Load our styles ...
err = mgr.loadStyles(mgr.Config.Styles)
if err != nil {
return &mgr, err
}
for _, chk := range mgr.Config.Checks {
// Load any remaining individual rules.
if !strings.Contains(chk, ".") {
// A rule must be associated with a style (i.e., "Style[.]Rule").
continue
}
parts := strings.Split(chk, ".")
if !mgr.hasStyle(parts[0]) {
// If this rule isn't part of an already-loaded style, we load it
// individually.
fName := parts[1] + ".yml"
path = filepath.Join(mgr.Config.StylesPath, parts[0], fName)
if err = mgr.AddRuleFromSource(fName, path); err != nil {
return &mgr, err
}
}
}
return &mgr, err
}
// AddRule adds the given rule to the manager.
func (mgr *Manager) AddRule(name string, rule Rule) error {
if _, found := mgr.rules[name]; !found {
mgr.rules[name] = rule
return nil
}
return fmt.Errorf("the rule '%s' has already been added", name)
}
// AddRuleFromSource adds the given rule to the manager.
func (mgr *Manager) AddRuleFromSource(name, path string) error {
if strings.HasSuffix(name, ".yml") {
f, err := mgr.Config.FsWrapper.ReadFile(path)
if err != nil {
return fmt.Errorf("failed to load rule '%s'.\n\n%v", name, err)
}
style := filepath.Base(filepath.Dir(path))
chkName := style + "." + strings.Split(name, ".")[0]
if _, ok := mgr.rules[chkName]; !ok {
if err = mgr.addCheck(f, chkName, path); err != nil {
return err
}
}
}
return nil
}
// Rules are all of the Manager's compiled `Rule`s.
func (mgr *Manager) Rules() map[string]Rule {
return mgr.rules
}
// HasScope returns `true` if the manager has a rule that applies to `scope`.
func (mgr *Manager) HasScope(scope string) bool {
_, found := mgr.scopes[scope]
return found
}
func (mgr *Manager) addStyle(path string) error {
return mgr.Config.FsWrapper.Walk(path,
func(fp string, fi os.FileInfo, err error) error {
if err != nil || fi.IsDir() {
return err
}
return mgr.AddRuleFromSource(fi.Name(), fp)
})
}
func (mgr *Manager) addCheck(file []byte, chkName, path string) error {
// Load the rule definition.
generic, err := parse(file, path)
if err != nil {
return err
}
// Set default values, if necessary.
generic["name"] = chkName
generic["path"] = path
if level, ok := mgr.Config.RuleToLevel[chkName]; ok {
generic["level"] = level
} else if _, ok := generic["level"]; !ok {
generic["level"] = "warning"
}
if _, ok := generic["scope"]; !ok {
generic["scope"] = "text"
}
rule, err := buildRule(mgr.Config, generic)
if err != nil {
return err
}
base := strings.Split(generic["scope"].(string), ".")[0]
mgr.scopes[base] = struct{}{}
return mgr.AddRule(chkName, rule)
}
func (mgr *Manager) loadDefaultRules() error {
for _, style := range defaultStyles {
if core.StringInSlice(style, mgr.styles) {
// The user has a style on their `StylesPath` with the same
// name as a built-in style.
//
// TODO: Should this be considered an error?
continue
}
rules, err := rule.AssetDir(filepath.Join("rule", style))
if err != nil {
return err
}
for _, name := range rules {
b, err := rule.Asset(filepath.Join("rule", style, name))
if err != nil {
return err
}
identifier := strings.Join([]string{
style, strings.Split(name, ".")[0]}, ".")
if err = mgr.addCheck(b, identifier, ""); err != nil {
return err
}
}
}
// TODO: where should this go?
mgr.loadVocabRules()
return nil
}
func (mgr *Manager) loadStyles(styles []string) error {
var found []string
baseDir := mgr.Config.StylesPath
for _, style := range styles {
p := filepath.Join(baseDir, style)
if mgr.hasStyle(style) {
// We've already loaded this style.
continue
} else if has, _ := mgr.Config.FsWrapper.DirExists(p); !has {
return errors.New("missing style: '" + style + "'")
}
if err := mgr.addStyle(p); err != nil {
return err
}
found = append(found, style)
}
mgr.styles = append(mgr.styles, found...)
return nil
}
func (mgr *Manager) loadVocabRules() {
if len(mgr.Config.AcceptedTokens) > 0 {
vocab := defaultRules["Terms"]
for term := range mgr.Config.AcceptedTokens {
if core.IsPhrase(term) {
vocab["swap"].(map[string]string)[strings.ToLower(term)] = term
}
}
rule, _ := buildRule(mgr.Config, vocab)
mgr.rules["Vale.Terms"] = rule
}
if len(mgr.Config.RejectedTokens) > 0 {
avoid := defaultRules["Avoid"]
for term := range mgr.Config.RejectedTokens {
avoid["tokens"] = append(avoid["tokens"].([]string), term)
}
rule, _ := buildRule(mgr.Config, avoid)
mgr.rules["Vale.Avoid"] = rule
}
if mgr.Config.LTPath != "" {
rule, _ := buildRule(mgr.Config, defaultRules["Grammar"])
mgr.rules["LanguageTool.Grammar"] = rule
}
}
func (mgr *Manager) hasStyle(name string) bool {
styles := append(mgr.styles, defaultStyles...)
return core.StringInSlice(name, styles)
}