gunk-dev/the-valley

checks.go

source795c933f9c5emain's published tip history
8.7 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, true)
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. pinned asks cue which
130// requirements are mandatory (composed.Read); a reader of paths and
131// follows alone leaves them unknown (composed.ReadUnpinned), which is
132// much quicker.
133func policyModel(schema, instance, project string, pinned bool) (*composed.Model, error) {
134 if _, err := exec.LookPath("cue"); err != nil {
135 return nil, failure("this verb needs the cue CLI; nix run .#valley bundles it")
136 }
137 read := composed.Read
138 if !pinned {
139 read = composed.ReadUnpinned
140 }
141 model, err := read(context.Background(), "cue", schema, instance, project)
142 if err != nil {
143 return nil, failure(err.Error() + "; nothing derived")
144 }
145 return model, nil
146}
147
148// deriveUnder is the valley-checks/v1 document for the change between two
149// commits, given as object IDs, under a policy read.
150func deriveUnder(g git, model *composed.Model, base, head string) (jsonChecks, error) {
151 ctx := context.Background()
152 paths, err := derive.Diff(ctx, g.dir, g.env, base, head)
153 if err != nil {
154 return jsonChecks{}, failure(err.Error() + "; nothing derived")
155 }
156 res, err := derive.Derive(model, paths)
157 if err != nil {
158 return jsonChecks{}, failure(err.Error() + "; nothing derived")
159 }
160 return checksDocument(base, head, model.Digest, res), nil
161}
162
163// The valley-checks/v1 document. docs/architecture.md documents it, and a
164// change to any field's name or meaning is a new schema version. Every
165// list is a list, empty rather than null.
166type jsonChecks struct {
167 Schema string `json:"schema"`
168 Base string `json:"base"`
169 Head string `json:"head"`
170 PolicyDigest string `json:"policy_digest"`
171 Paths []jsonPath `json:"paths"`
172 Classes []string `json:"classes"`
173 UnclassifiedPaths []jsonPath `json:"unclassified_paths"`
174 Carry string `json:"carry"`
175 Required []jsonRequired `json:"required"`
176 Follows []jsonFollow `json:"follows"`
177}
178
179// jsonRequired is one required check. attribute is given for the nix
180// runner, command for the command runner, and validity only when the
181// policy declares a window.
182type jsonRequired struct {
183 Name string `json:"name"`
184 Classes []string `json:"classes"`
185 Unclassified bool `json:"unclassified"`
186 Pin string `json:"pin"`
187 Cost string `json:"cost"`
188 Runner string `json:"runner"`
189 Attribute string `json:"attribute,omitempty"`
190 Command string `json:"command,omitempty"`
191 Validity string `json:"validity,omitempty"`
192}
193
194// jsonFollow is one check the change sets due on main without requiring
195// it, with the matched classes it follows.
196type jsonFollow struct {
197 Name string `json:"name"`
198 Classes []string `json:"classes"`
199 Cost string `json:"cost"`
200 Runner string `json:"runner"`
201 Attribute string `json:"attribute,omitempty"`
202 Command string `json:"command,omitempty"`
203}
204
205func checksDocument(base, head, digest string, r *derive.Result) jsonChecks {
206 doc := jsonChecks{
207 Schema: "valley-checks/v1",
208 Base: base,
209 Head: head,
210 PolicyDigest: digest,
211 Paths: jsonPaths(r.Paths),
212 Classes: append([]string{}, r.Classes...),
213 UnclassifiedPaths: jsonPaths(r.Unclassified),
214 Carry: r.Carry,
215 Required: []jsonRequired{},
216 Follows: []jsonFollow{},
217 }
218 for _, q := range r.Required {
219 doc.Required = append(doc.Required, jsonRequired{
220 Name: q.Name,
221 Classes: append([]string{}, q.Classes...),
222 Unclassified: q.Unclassified,
223 Pin: string(q.Pin),
224 Cost: q.Cost,
225 Runner: q.Runner,
226 Attribute: q.Attribute,
227 Command: q.Command,
228 Validity: q.Validity,
229 })
230 }
231 for _, f := range r.Follows {
232 doc.Follows = append(doc.Follows, jsonFollow{
233 Name: f.Name,
234 Classes: append([]string{}, f.Classes...),
235 Cost: f.Cost,
236 Runner: f.Runner,
237 Attribute: f.Attribute,
238 Command: f.Command,
239 })
240 }
241 return doc
242}
243
244// jsonPath is a path as git gave it, which is bytes that need not be
245// UTF-8. JSON holds only UTF-8, and json.Marshal writes each byte that is
246// not as U+FFFD, so such a path would not read back as git gave it. A path
247// that is UTF-8 is written as {"path": "…"}, and any other as {"base64":
248// "…"}, in standard base64, which reads back byte for byte.
249type jsonPath string
250
251func jsonPaths(paths []string) []jsonPath {
252 out := make([]jsonPath, len(paths))
253 for i, p := range paths {
254 out[i] = jsonPath(p)
255 }
256 return out
257}
258
259func (p jsonPath) MarshalJSON() ([]byte, error) {
260 var v any = struct {
261 Path string `json:"path"`
262 }{string(p)}
263 if !utf8.ValidString(string(p)) {
264 v = struct {
265 Base64 string `json:"base64"`
266 }{base64.StdEncoding.EncodeToString([]byte(p))}
267 }
268 var buf bytes.Buffer
269 enc := json.NewEncoder(&buf)
270 enc.SetEscapeHTML(false)
271 if err := enc.Encode(v); err != nil {
272 return nil, err
273 }
274 return bytes.TrimRight(buf.Bytes(), "\n"), nil
275}