gunk-dev/the-valley

checks.go

source499d9e61dfeemain's published tip history
16.0 KiB
1package main
2
3// checks prints which checks a change requires: the Go deriver's answer
4// (../derive) over the composed policy (../composed). It is the whole of
5// `valley checks`, which bin/valley hands to it.
6//
7// It selects checks over two commits, a base and a head, and never over a
8// working tree: what is derived is what a commit holds. A layer named with
9// --instance or --project is read as given, and nothing is fetched for it.
10// A layer left unnamed is read at the target's tip: main on origin as this
11// clone last fetched it, or else the local main. The base defaults to the
12// merge base of that tip and the head.
13//
14// It prints a report for a person, the required names alone with --names,
15// or the valley-checks/v1 JSON document with --json.
16
17import (
18 "bytes"
19 "context"
20 "encoding/base64"
21 "encoding/json"
22 "fmt"
23 "io"
24 "os"
25 "os/exec"
26 "path/filepath"
27 "sort"
28 "strings"
29 "unicode/utf8"
30
31 "the-valley/composed"
32 "the-valley/derive"
33)
34
35const checksUsage = "usage: valley checks [--schema <file>] [--instance <dir>] [--project <dir>] [--names [--cost quick|slow] | --json] [<base> [<head>]]"
36
37// checksTargets are the refs whose tip an unnamed layer and an unnamed
38// base are read at, first found first.
39var checksTargets = []string{"refs/remotes/origin/main", "refs/heads/main"}
40
41func runChecks(g git, args []string, w io.Writer) error {
42 var schema, instance, project, cost string
43 var names, asJSON, costed bool
44 needs := map[string]string{"--schema": "a file", "--instance": "a directory", "--project": "a directory", "--cost": "quick or slow"}
45 dests := map[string]*string{"--schema": &schema, "--instance": &instance, "--project": &project, "--cost": &cost}
46 i := 0
47options:
48 for ; i < len(args); i++ {
49 opt, value, inline := strings.Cut(args[i], "=")
50 switch {
51 case args[i] == "--":
52 i++
53 break options
54 case args[i] == "--names":
55 names = true
56 case args[i] == "--json":
57 asJSON = true
58 case dests[opt] != nil:
59 if !inline {
60 if i+1 >= len(args) {
61 return failure(opt + " needs " + needs[opt])
62 }
63 i++
64 value = args[i]
65 }
66 *dests[opt] = value
67 costed = costed || opt == "--cost"
68 case strings.HasPrefix(args[i], "-"):
69 return failure("unknown option: " + args[i])
70 default:
71 break options
72 }
73 }
74 revs := args[i:]
75 if len(revs) > 2 || (asJSON && (names || costed)) {
76 return failure(checksUsage)
77 }
78 if costed {
79 if cost != "quick" && cost != "slow" {
80 return failure("--cost takes quick or slow, not '" + cost + "'")
81 }
82 if !names {
83 return failure("--cost filters the --names list; pass --names too")
84 }
85 }
86 root, err := g.output(true, "rev-parse", "--show-toplevel")
87 if err != nil {
88 return failure("not a git repository")
89 }
90 if schema, err = schemaFile(g, schema); err != nil {
91 return err
92 }
93 headRev := "HEAD"
94 if len(revs) == 2 {
95 headRev = revs[1]
96 }
97 head, err := commitOf(g, headRev)
98 if err != nil {
99 return err
100 }
101
102 // The target is what the layers are read out of, so it is needed
103 // whenever either layer is left unnamed, and it is what an unnamed
104 // base is the merge base with.
105 var target, tip string
106 if instance == "" || project == "" || len(revs) == 0 {
107 // Only a ref that is not there falls through to the next. A read
108 // of origin's that failed ends here: falling through would read
109 // the policy out of the local main, which may be older.
110 for _, ref := range checksTargets {
111 oid, ok, err := g.ref(ref)
112 if err != nil {
113 return failure("could not read the main branch; nothing derived")
114 } else if ok {
115 target, tip = ref, oid
116 break
117 }
118 }
119 if target == "" {
120 return failure("no main branch: the target's tip is where the policy layers are read from, and there is none here")
121 }
122 }
123 var base string
124 if len(revs) > 0 {
125 if base, err = commitOf(g, revs[0]); err != nil {
126 return err
127 }
128 } else if base, err = g.output(true, "merge-base", tip, head); err != nil || !isObjectID(base) {
129 return failure(fmt.Sprintf("%s and %s do not share history — name a base", head, strings.TrimPrefix(target, "refs/")))
130 }
131
132 src, done, err := resolveLayers(g, tip, instance, project)
133 defer done()
134 if err != nil {
135 return failure(err.Error() + "; nothing derived")
136 }
137 model, err := policyModel(schema, src.instance, src.project, !names)
138 if err != nil {
139 return err
140 }
141 ctx := context.Background()
142 paths, err := derive.Diff(ctx, g.dir, g.env, base, head)
143 if err != nil {
144 return failure(err.Error() + "; nothing derived")
145 }
146 res, err := derive.Derive(model, paths)
147 if err != nil {
148 return failure(err.Error() + "; nothing derived")
149 }
150
151 // Each form is written whole once it is made, so a reader gets the
152 // answer or nothing.
153 var buf bytes.Buffer
154 switch {
155 case asJSON:
156 enc := json.NewEncoder(&buf)
157 enc.SetEscapeHTML(false)
158 enc.SetIndent("", " ")
159 if err := enc.Encode(checksDocument(base, head, model.Digest, res)); err != nil {
160 return fmt.Errorf("could not encode the checks: %w", err)
161 }
162 case names:
163 for _, q := range res.Required {
164 if cost == "" || costOf(q) == cost {
165 fmt.Fprintln(&buf, q.Name)
166 }
167 }
168 default:
169 at := ""
170 if tip != "" {
171 short, err := g.output(true, "rev-parse", "--short", tip)
172 if err != nil {
173 return failure("could not read " + target + "; nothing derived")
174 }
175 at = strings.TrimPrefix(strings.TrimPrefix(target, "refs/remotes/"), "refs/heads/") + " " + short
176 }
177 label, plabel := src.labels(root, instance, project, at)
178 shortBase, err1 := g.output(true, "rev-parse", "--short", base)
179 shortHead, err2 := g.output(true, "rev-parse", "--short", head)
180 if err1 != nil || err2 != nil {
181 return failure("could not read the commits; nothing derived")
182 }
183 checksReport(&buf, shortBase+".."+shortHead, label+" + "+plabel, res)
184 }
185 _, err = w.Write(buf.Bytes())
186 return err
187}
188
189// commitOf is the object ID of the commit rev names.
190func commitOf(g git, rev string) (string, error) {
191 oid, err := g.output(true, "rev-parse", "--verify", "--quiet", "--end-of-options", rev+"^{commit}")
192 if err != nil || !isObjectID(oid) {
193 return "", failure("no such commit: " + rev)
194 }
195 return oid, nil
196}
197
198// costOf is a required check's cost as the report groups it: slow, or
199// else quick.
200func costOf(q derive.Required) string {
201 if q.Cost == "slow" {
202 return "slow"
203 }
204 return "quick"
205}
206
207// labels say where each layer was read from, as a reader can check it: a
208// layer named is named as given, relative to the top level when it is
209// under it, and a layer read at the target names the ref and the commit
210// it stood at.
211func (src layerSource) labels(root, instance, project, at string) (label, plabel string) {
212 switch {
213 case instance != "":
214 label = strings.TrimPrefix(instance, root+"/")
215 case src.ownValley:
216 label = instanceLayer + "@" + at + " (this repository is its own valley)"
217 default:
218 label = src.valley + " " + instanceLayer + "@refs/heads/main"
219 }
220 switch {
221 case project != "":
222 plabel = strings.TrimPrefix(project, root+"/")
223 case src.noProject:
224 plabel = "no " + projectLayer + "@" + at + " — the floor alone"
225 default:
226 plabel = projectLayer + "@" + at
227 }
228 return label, plabel
229}
230
231// checksReport writes the report for a person: the change, the policy it
232// was read under, what it matched, and each required check with its pin
233// and the classes requiring it. A class requiring a check is listed with
234// the unclassified set, which requires checks of a path no class covers.
235func checksReport(w io.Writer, change, policy string, r *derive.Result) {
236 fmt.Fprintf(w, "%s: %d changed path(s)\n", change, len(r.Paths))
237 fmt.Fprintf(w, "policy: %s\n", policy)
238 matched := append([]string{}, r.Classes...)
239 if len(r.Unclassified) > 0 {
240 matched = append(matched, "unclassified")
241 }
242 sort.Strings(matched)
243 fmt.Fprintf(w, "classes matched: %s\n", joinOrNone(matched))
244 // How far an approval of this change carries across a rebase. Nothing
245 // here acts on it.
246 fmt.Fprintf(w, "carry mode: %s\n\n", r.Carry)
247
248 width, unclassified := 0, false
249 var quick, slow []string
250 for _, q := range r.Required {
251 width = max(width, len(q.Name))
252 unclassified = unclassified || q.Unclassified
253 if costOf(q) == "slow" {
254 slow = append(slow, q.Name)
255 } else {
256 quick = append(quick, q.Name)
257 }
258 }
259 if len(r.Required) == 0 {
260 fmt.Fprintln(w, "required checks: none")
261 } else {
262 fmt.Fprintln(w, "required checks:")
263 for _, q := range r.Required {
264 by := append([]string{}, q.Classes...)
265 if q.Unclassified {
266 by = append(by, "unclassified")
267 }
268 sort.Strings(by)
269 fmt.Fprintf(w, " %-*s %-9s %s\n", width, q.Name, q.Pin, strings.Join(by, ", "))
270 }
271 }
272
273 if len(r.Unclassified) > 0 {
274 fmt.Fprintf(w, "\nunclassified: %d path(s) matched no class\n", len(r.Unclassified))
275 for _, p := range r.Unclassified {
276 fmt.Fprintf(w, " %s\n", p)
277 }
278 // The failure the unclassified set exists to prevent: paths
279 // outside every class that the policy then asks nothing of.
280 if !unclassified {
281 fmt.Fprintln(w, " the policy requires nothing of them — it is behind the tree")
282 }
283 }
284
285 // Below every row, and unindented, so neither line reads as a
286 // required check. The grouping changes nothing required: approve runs
287 // every required check, and the integrator requires evidence for every
288 // one, whatever it costs.
289 if len(r.Required) > 0 {
290 fmt.Fprintf(w, "\nquick: %s\n", joinOrNone(quick))
291 fmt.Fprintf(w, "slow: %s\n", joinOrNone(slow))
292 }
293}
294
295func joinOrNone(list []string) string {
296 if len(list) == 0 {
297 return "none"
298 }
299 return strings.Join(list, ", ")
300}
301
302// derivedChecks is the valley-checks/v1 document for the change between
303// two commits, under the schema and the two layers named. An empty schema
304// is the packaged one, or else the one in this repository's tree. The
305// check worker (worker.go) calls it as checks does.
306func derivedChecks(g git, schema, instance, project, baseRev, headRev string) (jsonChecks, error) {
307 if !g.succeeds(true, "rev-parse", "--git-dir") {
308 return jsonChecks{}, failure("not a git repository")
309 }
310 schema, err := schemaFile(g, schema)
311 if err != nil {
312 return jsonChecks{}, err
313 }
314 var commits [2]string
315 for i, rev := range []string{baseRev, headRev} {
316 oid, err := g.output(true, "rev-parse", "--verify", "--quiet", "--end-of-options", rev+"^{commit}")
317 if err != nil || !isObjectID(oid) {
318 return jsonChecks{}, failure("no such commit: " + rev)
319 }
320 commits[i] = oid
321 }
322 model, err := policyModel(schema, instance, project, true)
323 if err != nil {
324 return jsonChecks{}, err
325 }
326 return deriveUnder(g, model, commits[0], commits[1])
327}
328
329// schemaFile is the verification schema named, or when none is, the
330// packaged one, or else the one in this repository's tree.
331func schemaFile(g git, schema string) (string, error) {
332 // The schema ships with the package, which names it in
333 // VALLEY_VERIFICATION_SCHEMA; only the-valley's own tree carries one,
334 // as `valley checks` reads it.
335 if schema == "" {
336 schema = os.Getenv("VALLEY_VERIFICATION_SCHEMA")
337 }
338 if schema == "" {
339 root, err := g.output(true, "rev-parse", "--show-toplevel")
340 if err != nil {
341 return "", failure("no schema: name one with --schema or VALLEY_VERIFICATION_SCHEMA")
342 }
343 schema = filepath.Join(root, "schema", "verification.cue")
344 }
345 return schema, nil
346}
347
348// policyModel is the policy the schema and the two layers compose, read
349// once for every change derived under it. pinned asks cue which
350// requirements are mandatory (composed.Read); a reader of paths and
351// follows alone leaves them unknown (composed.ReadUnpinned), which is
352// much quicker.
353func policyModel(schema, instance, project string, pinned bool) (*composed.Model, error) {
354 if _, err := exec.LookPath("cue"); err != nil {
355 return nil, failure("this verb needs the cue CLI; nix run .#valley bundles it")
356 }
357 read := composed.Read
358 if !pinned {
359 read = composed.ReadUnpinned
360 }
361 model, err := read(context.Background(), "cue", schema, instance, project)
362 if err != nil {
363 return nil, failure(err.Error() + "; nothing derived")
364 }
365 return model, nil
366}
367
368// deriveUnder is the valley-checks/v1 document for the change between two
369// commits, given as object IDs, under a policy read.
370func deriveUnder(g git, model *composed.Model, base, head string) (jsonChecks, error) {
371 ctx := context.Background()
372 paths, err := derive.Diff(ctx, g.dir, g.env, base, head)
373 if err != nil {
374 return jsonChecks{}, failure(err.Error() + "; nothing derived")
375 }
376 res, err := derive.Derive(model, paths)
377 if err != nil {
378 return jsonChecks{}, failure(err.Error() + "; nothing derived")
379 }
380 return checksDocument(base, head, model.Digest, res), nil
381}
382
383// The valley-checks/v1 document. docs/architecture.md documents it, and a
384// change to any field's name or meaning is a new schema version. Every
385// list is a list, empty rather than null.
386type jsonChecks struct {
387 Schema string `json:"schema"`
388 Base string `json:"base"`
389 Head string `json:"head"`
390 PolicyDigest string `json:"policy_digest"`
391 Paths []jsonPath `json:"paths"`
392 Classes []string `json:"classes"`
393 UnclassifiedPaths []jsonPath `json:"unclassified_paths"`
394 Carry string `json:"carry"`
395 Required []jsonRequired `json:"required"`
396 Follows []jsonFollow `json:"follows"`
397}
398
399// jsonRequired is one required check. attribute is given for the nix
400// runner, command for the command runner, and validity only when the
401// policy declares a window.
402type jsonRequired struct {
403 Name string `json:"name"`
404 Classes []string `json:"classes"`
405 Unclassified bool `json:"unclassified"`
406 Pin string `json:"pin"`
407 Cost string `json:"cost"`
408 Runner string `json:"runner"`
409 Attribute string `json:"attribute,omitempty"`
410 Command string `json:"command,omitempty"`
411 Validity string `json:"validity,omitempty"`
412}
413
414// jsonFollow is one check the change sets due on main without requiring
415// it, with the matched classes it follows.
416type jsonFollow struct {
417 Name string `json:"name"`
418 Classes []string `json:"classes"`
419 Cost string `json:"cost"`
420 Runner string `json:"runner"`
421 Attribute string `json:"attribute,omitempty"`
422 Command string `json:"command,omitempty"`
423}
424
425func checksDocument(base, head, digest string, r *derive.Result) jsonChecks {
426 doc := jsonChecks{
427 Schema: "valley-checks/v1",
428 Base: base,
429 Head: head,
430 PolicyDigest: digest,
431 Paths: jsonPaths(r.Paths),
432 Classes: append([]string{}, r.Classes...),
433 UnclassifiedPaths: jsonPaths(r.Unclassified),
434 Carry: r.Carry,
435 Required: []jsonRequired{},
436 Follows: []jsonFollow{},
437 }
438 for _, q := range r.Required {
439 doc.Required = append(doc.Required, jsonRequired{
440 Name: q.Name,
441 Classes: append([]string{}, q.Classes...),
442 Unclassified: q.Unclassified,
443 Pin: string(q.Pin),
444 Cost: q.Cost,
445 Runner: q.Runner,
446 Attribute: q.Attribute,
447 Command: q.Command,
448 Validity: q.Validity,
449 })
450 }
451 for _, f := range r.Follows {
452 doc.Follows = append(doc.Follows, jsonFollow{
453 Name: f.Name,
454 Classes: append([]string{}, f.Classes...),
455 Cost: f.Cost,
456 Runner: f.Runner,
457 Attribute: f.Attribute,
458 Command: f.Command,
459 })
460 }
461 return doc
462}
463
464// jsonPath is a path as git gave it, which is bytes that need not be
465// UTF-8. JSON holds only UTF-8, and json.Marshal writes each byte that is
466// not as U+FFFD, so such a path would not read back as git gave it. A path
467// that is UTF-8 is written as {"path": "…"}, and any other as {"base64":
468// "…"}, in standard base64, which reads back byte for byte.
469type jsonPath string
470
471func jsonPaths(paths []string) []jsonPath {
472 out := make([]jsonPath, len(paths))
473 for i, p := range paths {
474 out[i] = jsonPath(p)
475 }
476 return out
477}
478
479func (p jsonPath) MarshalJSON() ([]byte, error) {
480 var v any = struct {
481 Path string `json:"path"`
482 }{string(p)}
483 if !utf8.ValidString(string(p)) {
484 v = struct {
485 Base64 string `json:"base64"`
486 }{base64.StdEncoding.EncodeToString([]byte(p))}
487 }
488 var buf bytes.Buffer
489 enc := json.NewEncoder(&buf)
490 enc.SetEscapeHTML(false)
491 if err := enc.Encode(v); err != nil {
492 return nil, err
493 }
494 return bytes.TrimRight(buf.Bytes(), "\n"), nil
495}