-
-
Notifications
You must be signed in to change notification settings - Fork 145
/
ini.go
334 lines (300 loc) · 9.86 KB
/
ini.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
package core
import (
"errors"
"fmt"
"path/filepath"
"strings"
"github.com/errata-ai/ini"
"github.com/karrick/godirwalk"
"github.com/errata-ai/vale/v3/internal/glob"
)
func determinePath(configPath string, keyPath string) string {
// expand tilde at this point as this is where user-provided paths are provided
keyPath = normalizePath(keyPath)
if !IsDir(configPath) {
configPath = filepath.Dir(configPath)
}
sep := string(filepath.Separator)
abs, _ := filepath.Abs(keyPath)
rel := strings.TrimRight(keyPath, sep)
if abs != rel || !strings.Contains(keyPath, sep) {
// The path was relative
return filepath.Join(configPath, keyPath)
}
return abs
}
func mergeValues(shadows []string) []string {
values := []string{}
for _, v := range shadows {
entry := strings.TrimSpace(v)
if entry != "" && !StringInSlice(entry, values) {
values = append(values, entry)
}
}
return values
}
func loadVocab(root string, cfg *Config) error {
target := ""
for _, p := range cfg.SearchPaths() {
opt := filepath.Join(p, VocabDir, root)
if IsDir(opt) {
target = opt
break
}
}
if target == "" {
return NewE100("vocab", fmt.Errorf(
"'%s/%s' directory does not exist", VocabDir, root))
}
err := godirwalk.Walk(target, &godirwalk.Options{
Callback: func(fp string, de *godirwalk.Dirent) error {
name := de.Name()
if name == "accept.txt" {
return cfg.AddWordListFile(fp, true)
} else if name == "reject.txt" {
return cfg.AddWordListFile(fp, false)
}
return nil
},
Unsorted: true,
AllowNonDirectory: true,
FollowSymbolicLinks: true})
return err
}
func validateLevel(key, val string, cfg *Config) bool {
options := []string{"YES", "suggestion", "warning", "error"}
if val == "NO" || !StringInSlice(val, options) {
return false
} else if val != "YES" {
cfg.RuleToLevel[key] = val
}
return true
}
var syntaxOpts = map[string]func(string, *ini.Section, *Config) error{
"BasedOnStyles": func(lbl string, sec *ini.Section, cfg *Config) error {
pat, err := glob.Compile(lbl)
if err != nil {
return NewE201FromTarget(
fmt.Sprintf("The glob pattern '%s' could not be compiled.", lbl),
lbl,
cfg.Flags.Path)
} else if _, found := cfg.SecToPat[lbl]; !found {
cfg.SecToPat[lbl] = pat
}
sStyles := mergeValues(sec.Key("BasedOnStyles").StringsWithShadows(","))
cfg.Styles = append(cfg.Styles, sStyles...)
cfg.StyleKeys = append(cfg.StyleKeys, lbl)
cfg.SBaseStyles[lbl] = sStyles
return nil
},
"IgnorePatterns": func(label string, sec *ini.Section, cfg *Config) error { //nolint:unparam
cfg.BlockIgnores[label] = sec.Key("IgnorePatterns").Strings(",")
return nil
},
"BlockIgnores": func(label string, sec *ini.Section, cfg *Config) error { //nolint:unparam
cfg.BlockIgnores[label] = mergeValues(sec.Key("BlockIgnores").StringsWithShadows(","))
return nil
},
"TokenIgnores": func(label string, sec *ini.Section, cfg *Config) error { //nolint:unparam
cfg.TokenIgnores[label] = mergeValues(sec.Key("TokenIgnores").StringsWithShadows(","))
return nil
},
"Transform": func(label string, sec *ini.Section, cfg *Config) error { //nolint:unparam
candidate := sec.Key("Transform").String()
cfg.Stylesheets[label] = determinePath(cfg.Flags.Path, candidate)
return nil
},
"Lang": func(label string, sec *ini.Section, cfg *Config) error { //nolint:unparam
cfg.FormatToLang[label] = sec.Key("Lang").String()
return nil
},
}
var globalOpts = map[string]func(*ini.Section, *Config){
"BasedOnStyles": func(sec *ini.Section, cfg *Config) {
cfg.GBaseStyles = mergeValues(sec.Key("BasedOnStyles").StringsWithShadows(","))
cfg.Styles = append(cfg.Styles, cfg.GBaseStyles...)
},
"IgnorePatterns": func(sec *ini.Section, cfg *Config) {
cfg.BlockIgnores["*"] = sec.Key("IgnorePatterns").Strings(",")
},
"BlockIgnores": func(sec *ini.Section, cfg *Config) {
cfg.BlockIgnores["*"] = mergeValues(sec.Key("BlockIgnores").StringsWithShadows(","))
},
"TokenIgnores": func(sec *ini.Section, cfg *Config) {
cfg.TokenIgnores["*"] = mergeValues(sec.Key("TokenIgnores").StringsWithShadows(","))
},
"Lang": func(sec *ini.Section, cfg *Config) {
cfg.FormatToLang["*"] = sec.Key("Lang").String()
},
}
var coreOpts = map[string]func(*ini.Section, *Config) error{
"StylesPath": func(sec *ini.Section, cfg *Config) error {
// NOTE: The order of these paths is important. They represent the load
// order of the configuration files -- not `cfg.Paths`.
paths := sec.Key("StylesPath").ValueWithShadows()
files := cfg.ConfigFiles
if cfg.Flags.Local && len(files) == 2 {
// This represents the case where we have a default `.vale.ini`
// file and a local `.vale.ini` file.
//
// In such a case, there are three options: (1) both files define a
// `StylesPath`, (2) only one file defines a `StylesPath`, or (3)
// neither file defines a `StylesPath`.
basePath := determinePath(files[0], filepath.FromSlash(paths[0]))
mockPath := determinePath(files[1], filepath.FromSlash(paths[0]))
// ^ This case handles the situation where both configs define the
// same StylesPath (e.g., `StylesPath = styles`).
if len(paths) == 2 {
basePath = determinePath(files[0], filepath.FromSlash(paths[0]))
mockPath = determinePath(files[1], filepath.FromSlash(paths[1]))
}
cfg.AddStylesPath(basePath)
cfg.AddStylesPath(mockPath)
} else if len(paths) > 0 {
// In this case, we have a local configuration file (no default)
// that defines a `StylesPath`.
candidate := filepath.FromSlash(paths[len(paths)-1])
path := determinePath(cfg.ConfigFile(), candidate)
cfg.AddStylesPath(path)
if !FileExists(path) {
return NewE201FromTarget(
fmt.Sprintf("The path '%s' does not exist.", path),
candidate,
cfg.Flags.Path)
}
}
return nil
},
"MinAlertLevel": func(sec *ini.Section, cfg *Config) error {
if !StringInSlice(cfg.Flags.AlertLevel, AlertLevels) {
level := sec.Key("MinAlertLevel").String() // .In("suggestion", AlertLevels)
if index, found := LevelToInt[level]; found {
cfg.MinAlertLevel = index
} else {
return NewE201FromTarget(
"MinAlertLevel must be 'suggestion', 'warning', or 'error'.",
level,
cfg.Flags.Path)
}
}
return nil
},
"IgnoredScopes": func(sec *ini.Section, cfg *Config) error { //nolint:unparam
cfg.IgnoredScopes = mergeValues(sec.Key("IgnoredScopes").StringsWithShadows(","))
return nil
},
"WordTemplate": func(sec *ini.Section, cfg *Config) error { //nolint:unparam
cfg.WordTemplate = sec.Key("WordTemplate").String()
return nil
},
"SkippedScopes": func(sec *ini.Section, cfg *Config) error { //nolint:unparam
cfg.SkippedScopes = mergeValues(sec.Key("SkippedScopes").StringsWithShadows(","))
return nil
},
"IgnoredClasses": func(sec *ini.Section, cfg *Config) error { //nolint:unparam
cfg.IgnoredClasses = mergeValues(sec.Key("IgnoredClasses").StringsWithShadows(","))
return nil
},
"Vocab": func(sec *ini.Section, cfg *Config) error {
cfg.Vocab = mergeValues(sec.Key("Vocab").StringsWithShadows(","))
for _, v := range cfg.Vocab {
if err := loadVocab(v, cfg); err != nil {
return err
}
}
return nil
},
"NLPEndpoint": func(sec *ini.Section, cfg *Config) error { //nolint:unparam
cfg.NLPEndpoint = sec.Key("NLPEndpoint").MustString("")
return nil
},
}
func shadowLoad(source interface{}, others ...interface{}) (*ini.File, error) {
return ini.LoadSources(ini.LoadOptions{
AllowShadows: true,
SpaceBeforeInlineComment: true}, source, others...)
}
func processSources(cfg *Config, sources []string) (*ini.File, error) {
var err error
uCfg := ini.Empty(ini.LoadOptions{
AllowShadows: true,
Loose: true,
SpaceBeforeInlineComment: true,
})
if len(sources) == 0 {
return uCfg, errors.New("no sources provided")
} else if len(sources) == 1 {
cfg.Flags.Path = sources[0]
return shadowLoad(cfg.Flags.Path)
}
t := sources[1:]
s := make([]interface{}, len(t))
for i, v := range t {
s[i] = v
}
uCfg, err = shadowLoad(sources[0], s...)
cfg.Flags.Path = sources[len(sources)-1]
return uCfg, err
}
func processConfig(uCfg *ini.File, cfg *Config, dry bool) (*ini.File, error) {
core := uCfg.Section("")
global := uCfg.Section("*")
formats := uCfg.Section("formats")
adoc := uCfg.Section("asciidoctor")
// Default settings
for _, k := range core.KeyStrings() {
if f, found := coreOpts[k]; found {
if err := f(core, cfg); err != nil && !dry {
return nil, err
}
} else if _, found = syntaxOpts[k]; found {
msg := fmt.Sprintf("'%s' is a syntax-specific option", k)
return nil, NewE201FromTarget(msg, k, cfg.RootINI)
}
}
// Format mappings
for _, k := range formats.KeyStrings() {
cfg.Formats[k] = formats.Key(k).String()
}
// Asciidoctor attributes
for _, k := range adoc.KeyStrings() {
cfg.Asciidoctor[k] = adoc.Key(k).String()
}
// Global settings
for _, k := range global.KeyStrings() {
if f, found := globalOpts[k]; found {
f(global, cfg)
} else if _, found = syntaxOpts[k]; found {
msg := fmt.Sprintf("'%s' is a syntax-specific option", k)
return nil, NewE201FromTarget(msg, k, cfg.RootINI)
} else {
cfg.GChecks[k] = validateLevel(k, global.Key(k).String(), cfg)
cfg.Checks = append(cfg.Checks, k)
}
}
// Syntax-specific settings
for _, sec := range uCfg.SectionStrings() {
if StringInSlice(sec, []string{"*", "DEFAULT", "formats", "asciidoctor"}) {
continue
}
pat, err := glob.Compile(sec)
if err != nil {
return nil, err
}
cfg.SecToPat[sec] = pat
syntaxMap := make(map[string]bool)
for _, k := range uCfg.Section(sec).KeyStrings() {
if f, found := syntaxOpts[k]; found {
if err = f(sec, uCfg.Section(sec), cfg); err != nil && !dry {
return nil, err
}
} else {
syntaxMap[k] = validateLevel(k, uCfg.Section(sec).Key(k).String(), cfg)
cfg.Checks = append(cfg.Checks, k)
}
}
cfg.RuleKeys = append(cfg.RuleKeys, sec)
cfg.SChecks[sec] = syntaxMap
}
return uCfg, nil
}