-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.go
More file actions
308 lines (289 loc) · 8.59 KB
/
Copy pathconfig.go
File metadata and controls
308 lines (289 loc) · 8.59 KB
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
package goago
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
yaml "go.yaml.in/yaml/v3"
)
// ConfigName is the file goago looks for when the command line names no
// configuration. ConfigNameAlt is an equivalent spelling.
const (
ConfigName = ".goago.yml"
ConfigNameAlt = ".goago.yaml"
// maxConfigBytes is the largest config file goago will load. A larger file
// is an attack or a mistake, not a rule policy.
maxConfigBytes = 1 << 20
// maxExcludePatterns caps Config.Exclude.
maxExcludePatterns = 1024
// maxExcludePatternLen caps one exclude pattern.
maxExcludePatternLen = 4096
// maxRuleNames caps Enable and Disable together.
maxRuleNames = 4096
)
// A Config is the on-disk rule policy for a repository. A committed policy
// means every developer, every CI job, and every coding agent enforces the
// same subset without extra instruction.
type Config struct {
// Version names the config schema. Zero accepts an unversioned config from
// ago v0.1. Version 1 is the current schema.
Version int `yaml:"version"`
// Enable lists rules to turn on. The special value "default" expands to
// the default rule set and "all" expands to every rule. An empty list
// means the default set.
Enable []string `yaml:"enable"`
// Disable lists rules to turn off after goago applies Enable.
Disable []string `yaml:"disable"`
// Tests reports whether goago checks _test.go files.
Tests bool `yaml:"tests"`
// Exclude lists path patterns. goago matches them with [path/filepath.Match]
// against each path element and skips those packages.
Exclude []string `yaml:"exclude"`
// path records where goago loaded the config, for error messages.
path string
}
// Path returns the file goago loaded the config from, or "" for a default
// config.
func (c *Config) Path() string { return c.path }
// Meta rule-set names accepted in Config.Enable.
const (
setDefault = "default"
setAll = "all"
)
// LoadConfig reads a config file. A path of "" searches dir and each parent
// directory for .goago.yml or .goago.yaml, including the legacy .ago names.
// Multiple policy files in one directory are an error. When the search
// finds no file it returns the default config and a nil error.
func LoadConfig(dir, path string) (*Config, error) {
if path == "" {
found, err := findConfig(dir)
if err != nil {
return nil, err
}
if found == "" {
return &Config{}, nil
}
path = found
}
b, err := readConfigBytes(path)
if err != nil {
return nil, err
}
cfg := &Config{path: path}
dec := yaml.NewDecoder(bytes.NewReader(b))
dec.KnownFields(true)
// A file that is empty or holds only comments decodes to io.EOF. That is a
// valid config meaning "every default", not an error.
if err := dec.Decode(cfg); err != nil && !errors.Is(err, io.EOF) {
return nil, fmt.Errorf("%s: %w", path, err)
}
if err := cfg.Validate(); err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
return cfg, nil
}
// readConfigBytes reads a config file. It fails when the file is larger than
// maxConfigBytes.
func readConfigBytes(path string) ([]byte, error) {
f, err := os.Open(path) //nolint:gosec // reading the config path the user named is the point
if err != nil {
return nil, err
}
b, err := io.ReadAll(io.LimitReader(f, maxConfigBytes+1))
if cerr := f.Close(); err == nil {
err = cerr
}
if err != nil {
return nil, err
}
if len(b) > maxConfigBytes {
return nil, fmt.Errorf("%s: config exceeds %d bytes", path, maxConfigBytes)
}
return b, nil
}
// findConfig walks up from dir looking for a config file.
func findConfig(dir string) (string, error) {
abs, err := filepath.Abs(dir)
if err != nil {
return "", err
}
for {
var found string
// Keep existing policies active after the command rename.
for _, name := range []string{ConfigName, ConfigNameAlt, ".ago.yml", ".ago.yaml"} {
p := filepath.Join(abs, name)
fi, err := os.Stat(p)
if os.IsNotExist(err) {
continue
}
if err != nil {
return "", err
}
if fi.IsDir() {
continue
}
if found != "" {
return "", fmt.Errorf("multiple policy files: %s and %s; keep one or use -config", found, p)
}
found = p
}
if found != "" {
return found, nil
}
parent := filepath.Dir(abs)
if parent == abs {
return "", nil
}
abs = parent
}
}
// Validate reports whether every name in Enable and Disable refers to a rule
// this build knows about. The meta-names "default" and "all" are valid in
// Enable only. Errors carry no path prefix. A caller that read the config from
// a file should prefix them with its path.
func (c *Config) Validate() error {
if c.Version != 0 && c.Version != 1 {
return fmt.Errorf("version: unsupported schema %d; want 1", c.Version)
}
check := func(field string, names []string) error {
for _, n := range names {
if n == setDefault || n == setAll {
if field == "disable" {
return fmt.Errorf("disable: %q is not a rule name", n)
}
continue
}
if _, ok := Lookup(n); !ok {
return fmt.Errorf("%s: unknown rule %q", field, n)
}
}
return nil
}
if err := check("enable", c.Enable); err != nil {
return err
}
if err := check("disable", c.Disable); err != nil {
return err
}
if n := len(c.Enable) + len(c.Disable); n > maxRuleNames {
return fmt.Errorf("enable/disable: %d names; want at most %d", n, maxRuleNames)
}
if len(c.Exclude) > maxExcludePatterns {
return fmt.Errorf("exclude: %d patterns; want at most %d", len(c.Exclude), maxExcludePatterns)
}
for _, p := range c.Exclude {
if p == "" {
return fmt.Errorf("exclude: empty pattern")
}
if len(p) > maxExcludePatternLen {
return fmt.Errorf("exclude: pattern exceeds %d bytes", maxExcludePatternLen)
}
if strings.ContainsRune(p, 0) {
return fmt.Errorf("exclude: pattern contains NUL")
}
if _, err := filepath.Match(p, ""); err != nil {
return fmt.Errorf("exclude: invalid pattern %q: %w", p, err)
}
}
return nil
}
// Enabled resolves the config into the set of rules to run, sorted in
// registration order. overrides, when non-empty, replaces Config.Enable and
// comes from the command line.
func (c *Config) Enabled(overrides []string) []Rule {
selected := map[string]bool{}
enable := c.Enable
if len(overrides) > 0 {
enable = overrides
}
if len(enable) == 0 {
enable = []string{setDefault}
}
for _, name := range enable {
switch name {
case setDefault:
for _, r := range registry {
if r.Default {
selected[r.Name] = true
}
}
case setAll:
for _, r := range registry {
selected[r.Name] = true
}
default:
if r, ok := Lookup(name); ok {
selected[r.Name] = true
}
}
}
for _, name := range c.Disable {
if r, ok := Lookup(name); ok {
delete(selected, r.Name)
}
}
var out []Rule
for _, r := range registry {
if selected[r.Name] {
out = append(out, r)
}
}
return out
}
// Skip reports whether a file path matches any exclude pattern.
//
// goago matches a pattern three ways, because each way catches a different
// surprise. It matches the whole slash-separated path, so "*.pb.go" works.
// It matches each path element, so "generated" excludes any directory with
// that name at any depth. It matches each leading path prefix, so
// "third_party/*" excludes the whole subtree rather than only the files
// directly inside it.
func (c *Config) Skip(path string) bool {
if len(c.Exclude) == 0 {
return false
}
slashed := filepath.ToSlash(path)
elems := strings.Split(slashed, "/")
candidates := make([]string, 0, 2*len(elems))
for i := range elems {
candidates = append(candidates, elems[i], strings.Join(elems[:i+1], "/"))
}
for _, pattern := range c.Exclude {
for _, candidate := range candidates {
if ok, _ := filepath.Match(pattern, candidate); ok {
return true
}
}
}
return false
}
// ExampleConfig returns the minimal policy that "goago -init" writes. The
// "default" meta-name follows the defaults in the pinned goago version.
func ExampleConfig() string {
return `# yaml-language-server: $schema=https://raw.githubusercontent.com/agentstation/goago/main/goago.schema.json
# goago uses its built-in defaults when this file is absent.
# "default" follows the defaults in the goago version pinned by go.mod.
# Run "go tool goago -list" to inspect the resolved policy.
version: 1
enable:
- default
disable: []
# Check _test.go files as well as production files.
tests: false
# Path patterns to skip. goago always skips vendor and testdata.
exclude: []
`
}
// sortedNames is a small helper used by the command's error messages.
func sortedNames(rules []Rule) []string {
out := make([]string, 0, len(rules))
for _, r := range rules {
out = append(out, r.Name)
}
sort.Strings(out)
return out
}