gunk-dev/the-valley

checks.go

source8ea96b8e18d0main's published tip history
6.9 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 // The schema ships with the package, which names it in
91 // VALLEY_VERIFICATION_SCHEMA; only the-valley's own tree carries one,
92 // as `valley checks` reads it.
93 if schema == "" {
94 schema = os.Getenv("VALLEY_VERIFICATION_SCHEMA")
95 }
96 if schema == "" {
97 root, err := g.output(true, "rev-parse", "--show-toplevel")
98 if err != nil {
99 return jsonChecks{}, failure("no schema: name one with --schema or VALLEY_VERIFICATION_SCHEMA")
100 }
101 schema = filepath.Join(root, "schema", "verification.cue")
102 }
103 var commits [2]string
104 for i, rev := range []string{baseRev, headRev} {
105 oid, err := g.output(true, "rev-parse", "--verify", "--quiet", "--end-of-options", rev+"^{commit}")
106 if err != nil || !isObjectID(oid) {
107 return jsonChecks{}, failure("no such commit: " + rev)
108 }
109 commits[i] = oid
110 }
111 base, head := commits[0], commits[1]
112 if _, err := exec.LookPath("cue"); err != nil {
113 return jsonChecks{}, failure("this verb needs the cue CLI; nix run .#valley bundles it")
114 }
115
116 ctx := context.Background()
117 model, err := composed.Read(ctx, "cue", schema, instance, project)
118 if err != nil {
119 return jsonChecks{}, failure(err.Error() + "; nothing derived")
120 }
121 paths, err := derive.Diff(ctx, g.dir, g.env, base, head)
122 if err != nil {
123 return jsonChecks{}, failure(err.Error() + "; nothing derived")
124 }
125 res, err := derive.Derive(model, paths)
126 if err != nil {
127 return jsonChecks{}, failure(err.Error() + "; nothing derived")
128 }
129 return checksDocument(base, head, model.Digest, res), nil
130}
131
132// The valley-checks/v1 document. docs/architecture.md documents it, and a
133// change to any field's name or meaning is a new schema version. Every
134// list is a list, empty rather than null.
135type jsonChecks struct {
136 Schema string `json:"schema"`
137 Base string `json:"base"`
138 Head string `json:"head"`
139 PolicyDigest string `json:"policy_digest"`
140 Paths []jsonPath `json:"paths"`
141 Classes []string `json:"classes"`
142 UnclassifiedPaths []jsonPath `json:"unclassified_paths"`
143 Carry string `json:"carry"`
144 Required []jsonRequired `json:"required"`
145}
146
147// jsonRequired is one required check. attribute is given for the nix
148// runner, command for the command runner, and validity only when the
149// policy declares a window.
150type jsonRequired struct {
151 Name string `json:"name"`
152 Classes []string `json:"classes"`
153 Unclassified bool `json:"unclassified"`
154 Pin string `json:"pin"`
155 Cost string `json:"cost"`
156 Runner string `json:"runner"`
157 Attribute string `json:"attribute,omitempty"`
158 Command string `json:"command,omitempty"`
159 Validity string `json:"validity,omitempty"`
160}
161
162func checksDocument(base, head, digest string, r *derive.Result) jsonChecks {
163 doc := jsonChecks{
164 Schema: "valley-checks/v1",
165 Base: base,
166 Head: head,
167 PolicyDigest: digest,
168 Paths: jsonPaths(r.Paths),
169 Classes: append([]string{}, r.Classes...),
170 UnclassifiedPaths: jsonPaths(r.Unclassified),
171 Carry: r.Carry,
172 Required: []jsonRequired{},
173 }
174 for _, q := range r.Required {
175 doc.Required = append(doc.Required, jsonRequired{
176 Name: q.Name,
177 Classes: append([]string{}, q.Classes...),
178 Unclassified: q.Unclassified,
179 Pin: string(q.Pin),
180 Cost: q.Cost,
181 Runner: q.Runner,
182 Attribute: q.Attribute,
183 Command: q.Command,
184 Validity: q.Validity,
185 })
186 }
187 return doc
188}
189
190// jsonPath is a path as git gave it, which is bytes that need not be
191// UTF-8. JSON holds only UTF-8, and json.Marshal writes each byte that is
192// not as U+FFFD, so such a path would not read back as git gave it. A path
193// that is UTF-8 is written as {"path": "…"}, and any other as {"base64":
194// "…"}, in standard base64, which reads back byte for byte.
195type jsonPath string
196
197func jsonPaths(paths []string) []jsonPath {
198 out := make([]jsonPath, len(paths))
199 for i, p := range paths {
200 out[i] = jsonPath(p)
201 }
202 return out
203}
204
205func (p jsonPath) MarshalJSON() ([]byte, error) {
206 var v any = struct {
207 Path string `json:"path"`
208 }{string(p)}
209 if !utf8.ValidString(string(p)) {
210 v = struct {
211 Base64 string `json:"base64"`
212 }{base64.StdEncoding.EncodeToString([]byte(p))}
213 }
214 var buf bytes.Buffer
215 enc := json.NewEncoder(&buf)
216 enc.SetEscapeHTML(false)
217 if err := enc.Encode(v); err != nil {
218 return nil, err
219 }
220 return bytes.TrimRight(buf.Bytes(), "\n"), nil
221}