gunk-dev/the-valley

checks.go

source818bd30431eamain's published tip history
8.5 KiB
1package main
2
3// checks prints which checks a change requires, as the valley-checks/v1
4// JSON document: the Go deriver's answer (../derive) over the composed
5// policy (../composed).
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. The policy is
9// three things named on the command line, the schema and the floor's and
10// the project layer's directories of *.cue, so whoever calls it decides
11// where each layer is read from. `valley checks` resolves the layers
12// itself and does not run this verb.
13
14import (
15 "bytes"
16 "context"
17 "encoding/base64"
18 "encoding/json"
19 "fmt"
20 "io"
21 "os"
22 "os/exec"
23 "path/filepath"
24 "strings"
25 "unicode/utf8"
26
27 "the-valley/composed"
28 "the-valley/derive"
29)
30
31const checksUsage = "usage: valley-go checks [--schema <file>] --instance <dir> --project <dir> <base> <head>"
32
33func runChecks(g git, args []string, w io.Writer) error {
34 var schema, instance, project string
35 var rest []string
36 for i := 0; i < len(args); i++ {
37 opt, value, inline := strings.Cut(args[i], "=")
38 var dest *string
39 switch opt {
40 case "--schema":
41 dest = &schema
42 case "--instance":
43 dest = &instance
44 case "--project":
45 dest = &project
46 }
47 switch {
48 case dest == nil && strings.HasPrefix(args[i], "-"):
49 return failure(checksUsage)
50 case dest == nil:
51 rest = append(rest, args[i])
52 case inline:
53 *dest = value
54 case i+1 < len(args):
55 *dest = args[i+1]
56 i++
57 default:
58 return failure(checksUsage)
59 }
60 }
61 if len(rest) != 2 || instance == "" || project == "" {
62 return failure(checksUsage)
63 }
64 doc, err := derivedChecks(g, schema, instance, project, rest[0], rest[1])
65 if err != nil {
66 return err
67 }
68
69 // Encoded whole before anything is written, so a reader gets the
70 // document or nothing.
71 var buf bytes.Buffer
72 enc := json.NewEncoder(&buf)
73 enc.SetEscapeHTML(false)
74 enc.SetIndent("", " ")
75 if err := enc.Encode(doc); err != nil {
76 return fmt.Errorf("could not encode the checks: %w", err)
77 }
78 _, err = w.Write(buf.Bytes())
79 return err
80}
81
82// derivedChecks is the valley-checks/v1 document for the change between
83// two commits, under the schema and the two layers named. An empty schema
84// is the packaged one, or else the one in this repository's tree. The
85// check worker (worker.go) calls it as checks does.
86func derivedChecks(g git, schema, instance, project, baseRev, headRev string) (jsonChecks, error) {
87 if !g.succeeds(true, "rev-parse", "--git-dir") {
88 return jsonChecks{}, failure("not a git repository")
89 }
90 schema, err := schemaFile(g, schema)
91 if err != nil {
92 return jsonChecks{}, err
93 }
94 var commits [2]string
95 for i, rev := range []string{baseRev, headRev} {
96 oid, err := g.output(true, "rev-parse", "--verify", "--quiet", "--end-of-options", rev+"^{commit}")
97 if err != nil || !isObjectID(oid) {
98 return jsonChecks{}, failure("no such commit: " + rev)
99 }
100 commits[i] = oid
101 }
102 model, err := policyModel(schema, instance, project)
103 if err != nil {
104 return jsonChecks{}, err
105 }
106 return deriveUnder(g, model, commits[0], commits[1])
107}
108
109// schemaFile is the verification schema named, or when none is, the
110// packaged one, or else the one in this repository's tree.
111func schemaFile(g git, schema string) (string, error) {
112 // The schema ships with the package, which names it in
113 // VALLEY_VERIFICATION_SCHEMA; only the-valley's own tree carries one,
114 // as `valley checks` reads it.
115 if schema == "" {
116 schema = os.Getenv("VALLEY_VERIFICATION_SCHEMA")
117 }
118 if schema == "" {
119 root, err := g.output(true, "rev-parse", "--show-toplevel")
120 if err != nil {
121 return "", failure("no schema: name one with --schema or VALLEY_VERIFICATION_SCHEMA")
122 }
123 schema = filepath.Join(root, "schema", "verification.cue")
124 }
125 return schema, nil
126}
127
128// policyModel is the policy the schema and the two layers compose, read
129// once for every change derived under it.
130func policyModel(schema, instance, project string) (*composed.Model, error) {
131 if _, err := exec.LookPath("cue"); err != nil {
132 return nil, failure("this verb needs the cue CLI; nix run .#valley bundles it")
133 }
134 model, err := composed.Read(context.Background(), "cue", schema, instance, project)
135 if err != nil {
136 return nil, failure(err.Error() + "; nothing derived")
137 }
138 return model, nil
139}
140
141// deriveUnder is the valley-checks/v1 document for the change between two
142// commits, given as object IDs, under a policy read.
143func deriveUnder(g git, model *composed.Model, base, head string) (jsonChecks, error) {
144 ctx := context.Background()
145 paths, err := derive.Diff(ctx, g.dir, g.env, base, head)
146 if err != nil {
147 return jsonChecks{}, failure(err.Error() + "; nothing derived")
148 }
149 res, err := derive.Derive(model, paths)
150 if err != nil {
151 return jsonChecks{}, failure(err.Error() + "; nothing derived")
152 }
153 return checksDocument(base, head, model.Digest, res), nil
154}
155
156// The valley-checks/v1 document. docs/architecture.md documents it, and a
157// change to any field's name or meaning is a new schema version. Every
158// list is a list, empty rather than null.
159type jsonChecks struct {
160 Schema string `json:"schema"`
161 Base string `json:"base"`
162 Head string `json:"head"`
163 PolicyDigest string `json:"policy_digest"`
164 Paths []jsonPath `json:"paths"`
165 Classes []string `json:"classes"`
166 UnclassifiedPaths []jsonPath `json:"unclassified_paths"`
167 Carry string `json:"carry"`
168 Required []jsonRequired `json:"required"`
169 Follows []jsonFollow `json:"follows"`
170}
171
172// jsonRequired is one required check. attribute is given for the nix
173// runner, command for the command runner, and validity only when the
174// policy declares a window.
175type jsonRequired struct {
176 Name string `json:"name"`
177 Classes []string `json:"classes"`
178 Unclassified bool `json:"unclassified"`
179 Pin string `json:"pin"`
180 Cost string `json:"cost"`
181 Runner string `json:"runner"`
182 Attribute string `json:"attribute,omitempty"`
183 Command string `json:"command,omitempty"`
184 Validity string `json:"validity,omitempty"`
185}
186
187// jsonFollow is one check the change sets due on main without requiring
188// it, with the matched classes it follows.
189type jsonFollow struct {
190 Name string `json:"name"`
191 Classes []string `json:"classes"`
192 Cost string `json:"cost"`
193 Runner string `json:"runner"`
194 Attribute string `json:"attribute,omitempty"`
195 Command string `json:"command,omitempty"`
196}
197
198func checksDocument(base, head, digest string, r *derive.Result) jsonChecks {
199 doc := jsonChecks{
200 Schema: "valley-checks/v1",
201 Base: base,
202 Head: head,
203 PolicyDigest: digest,
204 Paths: jsonPaths(r.Paths),
205 Classes: append([]string{}, r.Classes...),
206 UnclassifiedPaths: jsonPaths(r.Unclassified),
207 Carry: r.Carry,
208 Required: []jsonRequired{},
209 Follows: []jsonFollow{},
210 }
211 for _, q := range r.Required {
212 doc.Required = append(doc.Required, jsonRequired{
213 Name: q.Name,
214 Classes: append([]string{}, q.Classes...),
215 Unclassified: q.Unclassified,
216 Pin: string(q.Pin),
217 Cost: q.Cost,
218 Runner: q.Runner,
219 Attribute: q.Attribute,
220 Command: q.Command,
221 Validity: q.Validity,
222 })
223 }
224 for _, f := range r.Follows {
225 doc.Follows = append(doc.Follows, jsonFollow{
226 Name: f.Name,
227 Classes: append([]string{}, f.Classes...),
228 Cost: f.Cost,
229 Runner: f.Runner,
230 Attribute: f.Attribute,
231 Command: f.Command,
232 })
233 }
234 return doc
235}
236
237// jsonPath is a path as git gave it, which is bytes that need not be
238// UTF-8. JSON holds only UTF-8, and json.Marshal writes each byte that is
239// not as U+FFFD, so such a path would not read back as git gave it. A path
240// that is UTF-8 is written as {"path": "…"}, and any other as {"base64":
241// "…"}, in standard base64, which reads back byte for byte.
242type jsonPath string
243
244func jsonPaths(paths []string) []jsonPath {
245 out := make([]jsonPath, len(paths))
246 for i, p := range paths {
247 out[i] = jsonPath(p)
248 }
249 return out
250}
251
252func (p jsonPath) MarshalJSON() ([]byte, error) {
253 var v any = struct {
254 Path string `json:"path"`
255 }{string(p)}
256 if !utf8.ValidString(string(p)) {
257 v = struct {
258 Base64 string `json:"base64"`
259 }{base64.StdEncoding.EncodeToString([]byte(p))}
260 }
261 var buf bytes.Buffer
262 enc := json.NewEncoder(&buf)
263 enc.SetEscapeHTML(false)
264 if err := enc.Encode(v); err != nil {
265 return nil, err
266 }
267 return bytes.TrimRight(buf.Bytes(), "\n"), nil
268}