gunk-dev/the-valley

checks.go

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