Repository navigation
Expand file tree
/
Copy pathrules.go
More file actions
425 lines (403 loc) · 12.5 KB
/
Copy pathrules.go
File metadata and controls
425 lines (403 loc) · 12.5 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
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
package dispatch
import (
"context"
"embed"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"slices"
"strings"
"text/tabwriter"
"github.com/kapetan-io/dispatch/internal/config"
"github.com/kapetan-io/dispatch/internal/rules"
"github.com/kapetan-io/dispatch/internal/world"
)
// shippedRules are the rules `dispatch rules init` writes, and the rules the
// tests run, so the repo's rules/ directory is the one place they live.
//
//go:embed rules
var shippedRules embed.FS
const rulesUsage = `usage: dispatch rules init [dir]
dispatch rules check [dir]
dispatch rules test [dir]
init write the shipped rules to dir, which defaults to [dispatch].rules in the config. It
refuses to overwrite a file that exists
check lint the rules, run one cycle against the world as it is now, and print what each rule
wants. Exits 1 on any finding
test run the *.test.ts scenarios in the same runtime a live run uses. Exits 1 when one fails`
const rulesEntry = "dispatch.ts"
// typesDir holds the generated declarations. They can't sit beside dispatch.ts,
// because tsc ignores a dispatch.d.ts that has a dispatch.ts next to it.
const typesDir = "types"
func rulesCommand(ctx context.Context, opts Options, args []string) error {
if len(args) == 0 || len(args) > 2 {
_, _ = fmt.Fprintln(opts.Stderr, rulesUsage)
return errors.New("rules takes init, check or test")
}
dir := ""
if len(args) == 2 {
dir = args[1]
}
switch args[0] {
case "init":
return rulesInit(opts, dir)
case "check":
return rulesCheck(ctx, opts, dir)
case "test":
return rulesTest(opts, dir)
}
_, _ = fmt.Fprintln(opts.Stderr, rulesUsage)
return fmt.Errorf("unknown rules command %q", args[0])
}
// rulesDir is where the rules live: the argument, else Options.RulesDir, else
// the config's [dispatch].rules.
func rulesDir(opts Options, arg string, cfg *config.Config) (string, error) {
switch {
case arg != "":
return opts.abs(opts.Env.ExpandHome(arg)), nil
case opts.RulesDir != "":
return opts.abs(opts.RulesDir), nil
case cfg != nil:
return opts.abs(cfg.Dispatch.Rules), nil
}
return opts.Env.ExpandHome("~/Development/dispatch/rules"), nil
}
func rulesInit(opts Options, arg string) error {
var cfg *config.Config
if c, err := loadConfig(opts); err == nil {
cfg = &c
} else if _, statErr := os.Stat(opts.ConfigPath); statErr == nil {
return err
}
dir, err := rulesDir(opts, arg, cfg)
if err != nil {
return err
}
files := map[string][]byte{}
err = fs.WalkDir(shippedRules, "rules", func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return err
}
b, err := shippedRules.ReadFile(path)
files[strings.TrimPrefix(path, "rules/")] = b
return err
})
if err != nil {
return err
}
rulesTable := config.ShippedRules()
if cfg != nil {
for k, v := range cfg.Rules {
rulesTable[k] = v
}
}
files[typesDir+"/dispatch.d.ts"] = []byte(rules.Declarations(rulesTable))
files[typesDir+"/testing.d.ts"] = []byte(rules.TestingDeclarations())
files["config.schema.json"] = config.JSONSchema()
names := make([]string, 0, len(files))
for name := range files {
names = append(names, name)
}
slices.Sort(names)
var exist []string
for _, name := range names {
if _, err := os.Stat(filepath.Join(dir, name)); err == nil {
exist = append(exist, name)
}
}
if len(exist) > 0 {
shown := exist
if len(shown) > 5 {
shown = append(slices.Clone(shown[:5]), fmt.Sprintf("and %d more", len(exist)-5))
}
return fmt.Errorf("%s already has %s. rules init never overwrites a file, so move them or pick another directory", dir, strings.Join(shown, ", "))
}
for _, name := range names {
path := filepath.Join(dir, name)
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
if err := os.WriteFile(path, files[name], 0o644); err != nil {
return err
}
}
_, _ = fmt.Fprintf(opts.Stdout, "wrote %d files to %s\nadd the [rules] keys in %s to your config.toml, then run dispatch rules check\n", len(names), dir, filepath.Join(dir, "config.example.toml"))
return nil
}
func rulesCheck(ctx context.Context, opts Options, arg string) error {
cfg, err := loadConfig(opts)
if err != nil {
return err
}
opts = withMultiplexer(opts, cfg, nil)
dir, err := rulesDir(opts, arg, &cfg)
if err != nil {
return err
}
var findings []string
// The types follow the config, so a rule reading a [rules] key the file lacks
// fails in tsc as well as when it runs.
if err := writeTypes(dir, cfg); err != nil {
return err
}
loaded, err := rules.Load(dir, rulesEntry, opts.ruleTimeouts())
if err != nil {
var lerr *rules.LoadError
if errors.As(err, &lerr) {
for _, p := range lerr.Problems {
_, _ = fmt.Fprintln(opts.Stdout, "finding:", p)
}
return fmt.Errorf("%d problems found, so no rule loaded", len(lerr.Problems))
}
return err
}
key, err := findLinearKey(ctx, opts, cfg)
if err != nil {
return err
}
lin := opts.Linear(key)
viewer, err := lin.Viewer(ctx)
if err != nil {
return err
}
src := sources(opts, cfg, lin, loaded, nil, nil)
src.Tolerant = true
db, err := trackedDatabase(ctx, opts, cfg)
if err != nil {
return err
}
db.into(&src)
snap := db.Local
w, err := world.Read(ctx, src, world.ScopeOf(cfg), opts.Clock.Now())
if err != nil {
return err
}
state := rules.FromWorld(w, cfg, nil, viewer.Name)
state.InboxRead = src.Inbox != nil
// A check acts on nothing, and a token_command can prompt to unlock a password manager,
// so it calls only services a caller gave it. A get otherwise reads as an unknown.
state.HTTP = opts.HTTP
if snap != nil {
state.Search = snap
}
result := loaded.Cycle(state, nil)
printCheck(opts, cfg, state, loaded, result)
for _, t := range result.Throws {
how := "threw"
if t.Timeout {
how = "ran out of time"
}
findings = append(findings, fmt.Sprintf("%s %s in its %s for %s: %s", t.Rule, how, t.Phase, t.Subject, t.Error))
}
findings = append(findings, typeCheck(ctx, opts, dir)...)
for _, f := range findings {
_, _ = fmt.Fprintln(opts.Stdout, "finding:", f)
}
if len(findings) > 0 {
return fmt.Errorf("%d problems found", len(findings))
}
return nil
}
// writeTypes writes the generated declarations the rules import.
func writeTypes(dir string, cfg config.Config) error {
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
for name, text := range map[string]string{
typesDir + "/dispatch.d.ts": rules.Declarations(cfg.Rules),
typesDir + "/testing.d.ts": rules.TestingDeclarations(),
} {
path := filepath.Join(dir, name)
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
if old, err := os.ReadFile(path); err == nil && string(old) == text {
continue
}
if err := os.WriteFile(path, []byte(text), 0o644); err != nil {
return err
}
}
return nil
}
// typeCheck runs tsc over the rules when it is installed. It is how a typo in
// a field name or a mixed-up type is found without waiting for the record to exist.
// It hands tsc a config of its own, because the flags that name files can't be
// mixed with a tsconfig.json on every tsc version, and "node" module resolution
// is gone from the newest ones.
func typeCheck(ctx context.Context, opts Options, dir string) []string {
tsc, err := opts.Env.LookPath("tsc")
if err != nil {
return nil
}
abs, err := filepath.Abs(dir)
if err != nil {
return []string{"tsc: " + err.Error()}
}
files := []string{filepath.Join(abs, typesDir, "dispatch.d.ts"), filepath.Join(abs, typesDir, "testing.d.ts"), filepath.Join(abs, rulesEntry)}
tests, _ := filepath.Glob(filepath.Join(abs, "*.test.ts"))
files = append(files, tests...)
conf, err := json.Marshal(map[string]any{
"compilerOptions": map[string]any{
"strict": true, "noEmit": true, "target": "ES2017", "lib": []string{"ES2017"}, "module": "ESNext",
"moduleResolution": "bundler", "skipLibCheck": true, "types": []string{},
},
"files": files,
})
if err != nil {
return []string{"tsc: " + err.Error()}
}
tmp, err := os.MkdirTemp(opts.Env.Get("TMPDIR"), "dispatch-tsc-")
if err != nil {
return []string{"tsc: " + err.Error()}
}
defer func() { _ = os.RemoveAll(tmp) }()
confPath := filepath.Join(tmp, "tsconfig.json")
if err := os.WriteFile(confPath, conf, 0o644); err != nil {
return []string{"tsc: " + err.Error()}
}
cmd := opts.Env.Command(ctx, tsc, "-p", confPath)
cmd.Dir = abs
out, err := cmd.CombinedOutput()
if err == nil {
return nil
}
var findings []string
for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
if line = strings.TrimSpace(line); line != "" {
findings = append(findings, "tsc: "+line)
}
}
if len(findings) == 0 {
findings = []string{"tsc failed: " + err.Error()}
}
return findings
}
func printCheck(opts Options, cfg config.Config, state *rules.State, loaded *rules.Rules, result rules.Result) {
tw := tabwriter.NewWriter(opts.Stdout, 0, 0, 2, ' ', 0)
defer func() { _ = tw.Flush() }()
statuses := cfg.Plugins.Linear.Statuses
for _, line := range state.Summary(statuses) {
_, _ = fmt.Fprintf(tw, "%s\t%s\n", line.Name, line.Text)
}
_, _ = fmt.Fprintln(tw, "\t")
for _, def := range loaded.Defs() {
desc := ""
switch {
case def.Shadow:
desc = "shadow: reports only"
if would := wantSummary(result.Shadow, def.Name); would != "" {
desc = "shadow: would " + would
}
default:
desc = "wants nothing now"
if wants := wantSummary(result.Wants, def.Name); wants != "" {
desc = "wants " + wants
}
}
if waiting := waitingSummary(result, def.Name); waiting != "" {
desc += "; " + waiting
}
if held := heldSummary(result, def.Name); held != "" {
desc += "; " + held
}
if exempt := exemptSummary(result, def.Name); exempt != "" {
desc += "; " + exempt
}
_, _ = fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", def.Name, def.Kind(), def.Target(), desc)
}
for _, ex := range loaded.Exemptions() {
_, _ = fmt.Fprintf(tw, "%s\texempt\t%s\texempts %s\n", ex.Name, ex.Each, strings.Join(slices.Concat(ex.Rules, ex.Actions), ", "))
}
}
// exemptSummary names the records an exemption stopped the rule for, such as "exempt for ENG-4 by stacked-pr-not-merged".
func exemptSummary(result rules.Result, rule string) string {
by := map[string][]string{}
var order []string
for _, e := range result.Exempted {
if e.Rule != rule {
continue
}
if _, ok := by[e.Exemption]; !ok {
order = append(order, e.Exemption)
}
// An exemption that names actions can take away several wants of one rule for a ticket.
if !slices.Contains(by[e.Exemption], e.Subject) {
by[e.Exemption] = append(by[e.Exemption], e.Subject)
}
}
parts := make([]string, len(order))
for i, name := range order {
parts[i] = fmt.Sprintf("exempt for %s by %s", strings.Join(by[name], ", "), name)
}
return strings.Join(parts, "; ")
}
// wantSummary names what a rule wants now, such as "launch now for ENG-12, ENG-15".
func wantSummary(wants []rules.Want, rule string) string {
by := map[string][]string{}
var order []string
for _, w := range wants {
if w.Rule != rule {
continue
}
verb := w.Receipt
if _, ok := by[verb]; !ok {
order = append(order, verb)
}
by[verb] = append(by[verb], w.Subject)
}
var parts []string
for _, verb := range order {
parts = append(parts, fmt.Sprintf("%s now for %s", verb, strings.Join(by[verb], ", ")))
}
return strings.Join(parts, "; ")
}
// waitingSummary names what a rule wants that waits, such as "waiting: launch for ENG-5 (4 of 4 in progress, 1st in line)".
func waitingSummary(result rules.Result, rule string) string {
var waiting []string
for _, w := range result.Waiting {
if w.Rule == rule {
waiting = append(waiting, fmt.Sprintf("%s for %s (%s)", w.Receipt, w.Subject, w.Reason))
}
}
if len(waiting) == 0 {
return ""
}
return "waiting: " + strings.Join(waiting, ", ")
}
func heldSummary(result rules.Result, rule string) string {
var held []string
for _, h := range result.Held {
if h.Rule == rule {
held = append(held, h.Subject)
}
}
if len(held) == 0 {
return ""
}
return "held for " + strings.Join(held, ", ")
}
func rulesTest(opts Options, arg string) error {
var cfgPtr *config.Config
if loaded, err := loadConfig(opts); err == nil {
cfgPtr = &loaded
}
dir, err := rulesDir(opts, arg, cfgPtr)
if err != nil {
return err
}
summary, err := rules.RunScenarios(dir, opts.ruleTimeouts())
for _, line := range summary.Lines {
_, _ = fmt.Fprintln(opts.Stdout, line)
}
if err != nil {
return err
}
if summary.Failed > 0 {
return fmt.Errorf("%d of %d scenarios failed", summary.Failed, summary.Passed+summary.Failed)
}
return nil
}