| 1 | package 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 | |
| 14 | import ( |
| 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 | |
| 31 | const checksUsage = "usage: valley-go checks [--schema <file>] --instance <dir> --project <dir> <base> <head>" |
| 32 | |
| 33 | func 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. |
| 86 | func 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. |
| 111 | func 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. |
| 130 | func 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. |
| 143 | func 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. |
| 159 | type 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 | } |
| 170 | |
| 171 | // jsonRequired is one required check. attribute is given for the nix |
| 172 | // runner, command for the command runner, and validity only when the |
| 173 | // policy declares a window. |
| 174 | type jsonRequired struct { |
| 175 | Name string `json:"name"` |
| 176 | Classes []string `json:"classes"` |
| 177 | Unclassified bool `json:"unclassified"` |
| 178 | Pin string `json:"pin"` |
| 179 | Cost string `json:"cost"` |
| 180 | Runner string `json:"runner"` |
| 181 | Attribute string `json:"attribute,omitempty"` |
| 182 | Command string `json:"command,omitempty"` |
| 183 | Validity string `json:"validity,omitempty"` |
| 184 | } |
| 185 | |
| 186 | func checksDocument(base, head, digest string, r *derive.Result) jsonChecks { |
| 187 | doc := jsonChecks{ |
| 188 | Schema: "valley-checks/v1", |
| 189 | Base: base, |
| 190 | Head: head, |
| 191 | PolicyDigest: digest, |
| 192 | Paths: jsonPaths(r.Paths), |
| 193 | Classes: append([]string{}, r.Classes...), |
| 194 | UnclassifiedPaths: jsonPaths(r.Unclassified), |
| 195 | Carry: r.Carry, |
| 196 | Required: []jsonRequired{}, |
| 197 | } |
| 198 | for _, q := range r.Required { |
| 199 | doc.Required = append(doc.Required, jsonRequired{ |
| 200 | Name: q.Name, |
| 201 | Classes: append([]string{}, q.Classes...), |
| 202 | Unclassified: q.Unclassified, |
| 203 | Pin: string(q.Pin), |
| 204 | Cost: q.Cost, |
| 205 | Runner: q.Runner, |
| 206 | Attribute: q.Attribute, |
| 207 | Command: q.Command, |
| 208 | Validity: q.Validity, |
| 209 | }) |
| 210 | } |
| 211 | return doc |
| 212 | } |
| 213 | |
| 214 | // jsonPath is a path as git gave it, which is bytes that need not be |
| 215 | // UTF-8. JSON holds only UTF-8, and json.Marshal writes each byte that is |
| 216 | // not as U+FFFD, so such a path would not read back as git gave it. A path |
| 217 | // that is UTF-8 is written as {"path": "…"}, and any other as {"base64": |
| 218 | // "…"}, in standard base64, which reads back byte for byte. |
| 219 | type jsonPath string |
| 220 | |
| 221 | func jsonPaths(paths []string) []jsonPath { |
| 222 | out := make([]jsonPath, len(paths)) |
| 223 | for i, p := range paths { |
| 224 | out[i] = jsonPath(p) |
| 225 | } |
| 226 | return out |
| 227 | } |
| 228 | |
| 229 | func (p jsonPath) MarshalJSON() ([]byte, error) { |
| 230 | var v any = struct { |
| 231 | Path string `json:"path"` |
| 232 | }{string(p)} |
| 233 | if !utf8.ValidString(string(p)) { |
| 234 | v = struct { |
| 235 | Base64 string `json:"base64"` |
| 236 | }{base64.StdEncoding.EncodeToString([]byte(p))} |
| 237 | } |
| 238 | var buf bytes.Buffer |
| 239 | enc := json.NewEncoder(&buf) |
| 240 | enc.SetEscapeHTML(false) |
| 241 | if err := enc.Encode(v); err != nil { |
| 242 | return nil, err |
| 243 | } |
| 244 | return bytes.TrimRight(buf.Bytes(), "\n"), nil |
| 245 | } |