| 1 | package derive |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "fmt" |
| 7 | "maps" |
| 8 | "os" |
| 9 | "os/exec" |
| 10 | "path/filepath" |
| 11 | "regexp" |
| 12 | "slices" |
| 13 | "sort" |
| 14 | "strconv" |
| 15 | "strings" |
| 16 | "testing" |
| 17 | |
| 18 | "the-valley/composed" |
| 19 | ) |
| 20 | |
| 21 | // The tests beside this file hold the Go deriver to bin/valley's, which is |
| 22 | // the deriver every caller runs. This file is what they share: the |
| 23 | // rig that runs both, the scratch repositories they run over, and the |
| 24 | // reading of what bin/valley derived. |
| 25 | // |
| 26 | // bin/valley derives in the C locale whatever its caller's locale is |
| 27 | // (derive_required), and this package matches bytes in every locale. The |
| 28 | // agreement tests run bin/valley under the C locale and under UTF-8 ones |
| 29 | // (locales), as an operator's shell and the integrator's unit may set them, |
| 30 | // so a deriver whose answer changes with the locale disagrees. |
| 31 | |
| 32 | // rig is what both derivers need: bin/valley, the schema, cue, and an |
| 33 | // environment of the test's own, with no configuration of the person |
| 34 | // running it. |
| 35 | type rig struct { |
| 36 | root, script, schema, cue string |
| 37 | lib string // bin/valley with its last line, which runs main, dropped |
| 38 | base []string // the environment, with no locale in it |
| 39 | env []string // base in the C locale |
| 40 | } |
| 41 | |
| 42 | func newRig(t *testing.T) *rig { |
| 43 | t.Helper() |
| 44 | for _, tool := range []string{"bash", "git", "cue"} { |
| 45 | if _, err := exec.LookPath(tool); err != nil { |
| 46 | if os.Getenv("VALLEY_TEST_TOOLS") == "required" { |
| 47 | t.Fatalf("no %s on PATH, and VALLEY_TEST_TOOLS=required", tool) |
| 48 | } |
| 49 | t.Skipf("no %s to run bin/valley's deriver with; the derive-unit check provides one", tool) |
| 50 | } |
| 51 | } |
| 52 | root, err := filepath.Abs("..") |
| 53 | if err != nil { |
| 54 | t.Fatal(err) |
| 55 | } |
| 56 | cue, _ := exec.LookPath("cue") |
| 57 | r := &rig{ |
| 58 | root: root, |
| 59 | script: filepath.Join(root, "bin", "valley"), |
| 60 | schema: filepath.Join(root, "schema", "verification.cue"), |
| 61 | cue: cue, |
| 62 | } |
| 63 | for _, f := range []string{r.script, r.schema} { |
| 64 | if _, err := os.Stat(f); err != nil { |
| 65 | t.Fatalf("the tests read %s, and it is not there: %v", f, err) |
| 66 | } |
| 67 | } |
| 68 | r.base = []string{ |
| 69 | "PATH=" + os.Getenv("PATH"), |
| 70 | "HOME=" + t.TempDir(), |
| 71 | "TMPDIR=" + os.TempDir(), |
| 72 | "GIT_CONFIG_NOSYSTEM=1", |
| 73 | "GIT_AUTHOR_NAME=derive-test", "GIT_AUTHOR_EMAIL=derive-test@localhost", |
| 74 | "GIT_COMMITTER_NAME=derive-test", "GIT_COMMITTER_EMAIL=derive-test@localhost", |
| 75 | "GIT_AUTHOR_DATE=2026-10-21T00:00:00Z", "GIT_COMMITTER_DATE=2026-10-21T00:00:00Z", |
| 76 | } |
| 77 | // Where nix's glibc finds the locales other than C and C.UTF-8. |
| 78 | if archive := os.Getenv("LOCALE_ARCHIVE"); archive != "" { |
| 79 | r.base = append(r.base, "LOCALE_ARCHIVE="+archive) |
| 80 | } |
| 81 | r.env = append(append([]string{}, r.base...), "LC_ALL=C") |
| 82 | |
| 83 | script, err := os.ReadFile(r.script) |
| 84 | if err != nil { |
| 85 | t.Fatal(err) |
| 86 | } |
| 87 | const last = "\nmain \"$@\"\n" |
| 88 | if !bytes.HasSuffix(script, []byte(last)) { |
| 89 | t.Fatalf("bin/valley does not end in %q, so the tests cannot run its verbs one by one", last) |
| 90 | } |
| 91 | r.lib = filepath.Join(t.TempDir(), "valley-lib.bash") |
| 92 | if err := os.WriteFile(r.lib, script[:len(script)-len(last)+1], 0o644); err != nil { |
| 93 | t.Fatal(err) |
| 94 | } |
| 95 | return r |
| 96 | } |
| 97 | |
| 98 | // locale is the locale a deriver is run in, and how its environment sets |
| 99 | // it. |
| 100 | type locale struct { |
| 101 | name string |
| 102 | env []string |
| 103 | utf8 bool // whether bash's regular expressions read characters in it |
| 104 | } |
| 105 | |
| 106 | // locales are those both derivers are held to agree under: C, C.UTF-8 set |
| 107 | // by LC_ALL, and en_US.UTF-8 set by LANG alone, as a unit that systemd |
| 108 | // gives the system's locale is run. |
| 109 | var locales = []locale{ |
| 110 | {"C", []string{"LC_ALL=C"}, false}, |
| 111 | {"LC_ALL=C.UTF-8", []string{"LC_ALL=C.UTF-8"}, true}, |
| 112 | {"LANG=en_US.UTF-8", []string{"LANG=en_US.UTF-8"}, true}, |
| 113 | } |
| 114 | |
| 115 | // locales are the locales this machine has, each shown to take: in a |
| 116 | // UTF-8 one, bash's `?` matches é, two bytes, and in C it does not. A |
| 117 | // UTF-8 locale that does not take would run bin/valley in C again and |
| 118 | // prove nothing, so it is skipped, or fails the test when |
| 119 | // VALLEY_TEST_TOOLS=required. |
| 120 | func (r *rig) locales(t *testing.T) []locale { |
| 121 | t.Helper() |
| 122 | var out []locale |
| 123 | for _, loc := range locales { |
| 124 | cmd := exec.Command("bash", "-c", `[[ $'\xc3\xa9' =~ ^[^/]$ ]]`) |
| 125 | cmd.Env = append(append([]string{}, r.base...), loc.env...) |
| 126 | chars := cmd.Run() == nil |
| 127 | switch { |
| 128 | case chars == loc.utf8: |
| 129 | out = append(out, loc) |
| 130 | case !loc.utf8: |
| 131 | t.Fatalf("bash reads characters in %s", loc.name) |
| 132 | case os.Getenv("VALLEY_TEST_TOOLS") == "required": |
| 133 | t.Fatalf("%s does not take here, and VALLEY_TEST_TOOLS=required; LOCALE_ARCHIVE is %q", loc.name, os.Getenv("LOCALE_ARCHIVE")) |
| 134 | default: |
| 135 | t.Logf("%s does not take here; the derivers are not held to agree under it", loc.name) |
| 136 | } |
| 137 | } |
| 138 | return out |
| 139 | } |
| 140 | |
| 141 | // path is a file of the repository the tests run in. |
| 142 | func (r *rig) path(rel string) string { return filepath.Join(r.root, rel) } |
| 143 | |
| 144 | // glob is every file of the repository a pattern names, sorted. |
| 145 | func (r *rig) glob(t *testing.T, pattern string) []string { |
| 146 | t.Helper() |
| 147 | found, err := filepath.Glob(r.path(pattern)) |
| 148 | if err != nil || len(found) == 0 { |
| 149 | t.Fatalf("no file matches %s", pattern) |
| 150 | } |
| 151 | return found |
| 152 | } |
| 153 | |
| 154 | // layers is a policy on disk: the floor's directory and the project |
| 155 | // layer's, as both derivers are given them. |
| 156 | type layers struct{ instance, project string } |
| 157 | |
| 158 | // naming is what a policy's layer directories are called, and the decoys |
| 159 | // beside them: directories a reader taking a layer's name as a pattern |
| 160 | // would read instead of it, or as well. |
| 161 | type naming struct { |
| 162 | instance, project string |
| 163 | decoys []string |
| 164 | } |
| 165 | |
| 166 | // namings are the layer directories the agreement tests rotate through: |
| 167 | // plain names, and names a glob reads as patterns. |
| 168 | var namings = []naming{ |
| 169 | {"instance", "project", nil}, |
| 170 | {"floor[1]", "proj*", []string{"floor1", "projX"}}, |
| 171 | {`fl\oor?`, "pro ject[a-z]", []string{"floorX", "pro jectq"}}, |
| 172 | } |
| 173 | |
| 174 | // notCUE is what every decoy and dotfile document holds. A deriver that |
| 175 | // composes one fails, so a deriver that reads the wrong documents cannot |
| 176 | // pass by reading them the same way as the other. |
| 177 | const notCUE = "package verification\nthis is not CUE, and no layer holds it\n" |
| 178 | |
| 179 | // newLayers copies the floor's documents and the project's into |
| 180 | // directories of their own, and writes extra, by name, beside the |
| 181 | // project's. A project with no documents is one that adds nothing. |
| 182 | func newLayers(t *testing.T, instance, project []string, extra map[string]string) layers { |
| 183 | t.Helper() |
| 184 | return newLayersAt(t, namings[0], instance, project, extra) |
| 185 | } |
| 186 | |
| 187 | // newLayersAt is newLayers with the directories named as n names them. Each |
| 188 | // directory also holds a dotfile, .shadow.cue, and each decoy a document, |
| 189 | // decoy.cue, neither of them CUE: neither is a document of the policy. |
| 190 | func newLayersAt(t *testing.T, n naming, instance, project []string, extra map[string]string) layers { |
| 191 | t.Helper() |
| 192 | dir := t.TempDir() |
| 193 | l := layers{instance: filepath.Join(dir, n.instance), project: filepath.Join(dir, n.project)} |
| 194 | for _, d := range []string{l.instance, l.project} { |
| 195 | if err := os.Mkdir(d, 0o755); err != nil { |
| 196 | t.Fatal(err) |
| 197 | } |
| 198 | if err := os.WriteFile(filepath.Join(d, ".shadow.cue"), []byte(notCUE), 0o644); err != nil { |
| 199 | t.Fatal(err) |
| 200 | } |
| 201 | } |
| 202 | for _, decoy := range n.decoys { |
| 203 | d := filepath.Join(dir, decoy) |
| 204 | if err := os.Mkdir(d, 0o755); err != nil { |
| 205 | t.Fatal(err) |
| 206 | } |
| 207 | if err := os.WriteFile(filepath.Join(d, "decoy.cue"), []byte(notCUE), 0o644); err != nil { |
| 208 | t.Fatal(err) |
| 209 | } |
| 210 | } |
| 211 | copyTo := func(dest string, files []string) { |
| 212 | for _, f := range files { |
| 213 | body, err := os.ReadFile(f) |
| 214 | if err != nil { |
| 215 | t.Fatal(err) |
| 216 | } |
| 217 | if err := os.WriteFile(filepath.Join(dest, filepath.Base(f)), body, 0o644); err != nil { |
| 218 | t.Fatal(err) |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | copyTo(l.instance, instance) |
| 223 | copyTo(l.project, project) |
| 224 | if len(project) == 0 && len(extra) == 0 { |
| 225 | extra = map[string]string{"adds-nothing.cue": "package verification\n"} |
| 226 | } |
| 227 | for name, body := range extra { |
| 228 | if err := os.WriteFile(filepath.Join(l.project, name), []byte(body), 0o644); err != nil { |
| 229 | t.Fatal(err) |
| 230 | } |
| 231 | } |
| 232 | return l |
| 233 | } |
| 234 | |
| 235 | // read is composed.Read of the layers under the rig's schema. |
| 236 | func (r *rig) read(l layers) (*composed.Model, error) { |
| 237 | return composed.Read(context.Background(), r.cue, r.schema, l.instance, l.project) |
| 238 | } |
| 239 | |
| 240 | // valley runs bin/valley's `checks` over two commits of the repository at |
| 241 | // dir, in the C locale, and reads what it derived. A run that fails returns |
| 242 | // what it said, and must print nothing on stdout. env is added to the |
| 243 | // rig's environment. |
| 244 | func (r *rig) valley(t *testing.T, dir, schema string, l layers, base, head string, env ...string) (*report, error) { |
| 245 | t.Helper() |
| 246 | return r.valleyIn(t, locales[0], dir, schema, l, base, head, env...) |
| 247 | } |
| 248 | |
| 249 | // derivation are the globals bin/valley's derive_required answers with, |
| 250 | // each with its kind: a list, a scalar or a map. Every one is read from |
| 251 | // each run and compared with the Go deriver's answer (agree), and |
| 252 | // TestEveryDerivationGlobal holds this list to the globals bin/valley |
| 253 | // declares. |
| 254 | var derivation = []struct { |
| 255 | name string |
| 256 | kind byte // 'L' a list, 'S' a scalar, 'M' a map |
| 257 | }{ |
| 258 | {"POLICY_LAYER", 'L'}, {"DERIVED_PATHS", 'L'}, {"DERIVED_MATCHED", 'L'}, |
| 259 | {"DERIVED_UNCOVERED", 'L'}, {"DERIVED_UNCLASSIFIED", 'S'}, {"DERIVED_CARRY", 'S'}, |
| 260 | {"DERIVED_REQUIRED", 'M'}, {"DERIVED_PINNED", 'M'}, {"CHECK_RUNNER", 'M'}, |
| 261 | {"CHECK_ATTRIBUTE", 'M'}, {"CHECK_COMMAND", 'M'}, {"CHECK_COST", 'M'}, |
| 262 | } |
| 263 | |
| 264 | // valleyIn is valley in a locale. bin/valley is run as `valley checks` |
| 265 | // runs: its verb, cmd_checks, called as main calls it, whose report is |
| 266 | // what it prints. Then every global of the derivation is written out, |
| 267 | // NUL-separated, so each is read whatever bytes it holds. |
| 268 | func (r *rig) valleyIn(t *testing.T, loc locale, dir, schema string, l layers, base, head string, env ...string) (*report, error) { |
| 269 | t.Helper() |
| 270 | var dump strings.Builder |
| 271 | for _, g := range derivation { |
| 272 | fmt.Fprintf(&dump, "rig_%c %s\n", g.kind, g.name) |
| 273 | } |
| 274 | program := `source "$1" |
| 275 | out="$2" |
| 276 | shift 2 |
| 277 | cmd_checks "$@" |
| 278 | rig_L() { local -n rig_l="$1"; printf 'L\0%s\0%d\0' "$1" "${#rig_l[@]}"; [ "${#rig_l[@]}" -eq 0 ] || printf '%s\0' "${rig_l[@]}"; } |
| 279 | rig_S() { printf 'S\0%s\0%s\0' "$1" "${!1}"; } |
| 280 | rig_M() { local -n rig_m="$1"; local k; printf 'M\0%s\0%d\0' "$1" "${#rig_m[@]}"; for k in "${!rig_m[@]}"; do printf '%s\0%s\0' "$k" "${rig_m[$k]}"; done; } |
| 281 | { |
| 282 | ` + dump.String() + `} > "$out" |
| 283 | ` |
| 284 | vars := filepath.Join(t.TempDir(), "derivation") |
| 285 | cmd := exec.Command("bash", "-c", program, "bash", r.lib, vars, "--schema", schema, |
| 286 | "--instance", l.instance, "--project", l.project, base, head) |
| 287 | cmd.Dir = dir |
| 288 | cmd.Env = append(append(append([]string{}, r.base...), loc.env...), env...) |
| 289 | var stdout, stderr bytes.Buffer |
| 290 | cmd.Stdout, cmd.Stderr = &stdout, &stderr |
| 291 | if err := cmd.Run(); err != nil { |
| 292 | if stdout.Len() > 0 { |
| 293 | t.Errorf("bin/valley failed and printed to stdout:\n%s", stdout.String()) |
| 294 | } |
| 295 | return nil, fmt.Errorf("%w: %s", err, strings.TrimSpace(stderr.String())) |
| 296 | } |
| 297 | rep, err := parseReport(stdout.String()) |
| 298 | if err != nil { |
| 299 | t.Fatalf("bin/valley's report does not read: %v\n%s", err, stdout.String()) |
| 300 | } |
| 301 | out, err := os.ReadFile(vars) |
| 302 | if err != nil { |
| 303 | t.Fatal(err) |
| 304 | } |
| 305 | if rep.vars, err = parseVars(out); err != nil { |
| 306 | t.Fatalf("bin/valley's derivation does not read: %v\n%q", err, out) |
| 307 | } |
| 308 | return rep, nil |
| 309 | } |
| 310 | |
| 311 | // derive is the Go deriver over the same two commits: Diff, then Derive. |
| 312 | func (r *rig) derive(m *composed.Model, dir, base, head string, env ...string) (*Result, error) { |
| 313 | paths, err := Diff(context.Background(), dir, append(append([]string{}, r.env...), env...), base, head) |
| 314 | if err != nil { |
| 315 | return nil, err |
| 316 | } |
| 317 | return Derive(m, paths) |
| 318 | } |
| 319 | |
| 320 | // report is what bin/valley's `checks` printed, as far as it says what a |
| 321 | // change requires, and the derivation it printed it from. |
| 322 | type report struct { |
| 323 | paths int // the count on the header line |
| 324 | classes []string // classes matched, unclassified included |
| 325 | carry string // the carry mode |
| 326 | required map[string]reportRow // check -> its row |
| 327 | unclassified []string // the paths listed as matching no class |
| 328 | vars *vars // the derivation's globals |
| 329 | } |
| 330 | |
| 331 | // vars are the globals of bin/valley's derivation, by name. |
| 332 | type vars struct { |
| 333 | lists map[string][]string |
| 334 | scalars map[string]string |
| 335 | maps map[string]map[string]string |
| 336 | } |
| 337 | |
| 338 | // parseVars reads the globals valleyIn writes: for each, its kind, its |
| 339 | // name, and for a list its length and its items, for a scalar its value, |
| 340 | // and for a map its length and its keys, each followed by its value. |
| 341 | func parseVars(out []byte) (*vars, error) { |
| 342 | v := &vars{lists: map[string][]string{}, scalars: map[string]string{}, maps: map[string]map[string]string{}} |
| 343 | fields := strings.Split(string(out), "\x00") |
| 344 | if len(fields) == 0 || fields[len(fields)-1] != "" { |
| 345 | return nil, fmt.Errorf("the output does not end in NUL") |
| 346 | } |
| 347 | fields = fields[:len(fields)-1] |
| 348 | next := func() (string, error) { |
| 349 | if len(fields) == 0 { |
| 350 | return "", fmt.Errorf("the output ends early") |
| 351 | } |
| 352 | f := fields[0] |
| 353 | fields = fields[1:] |
| 354 | return f, nil |
| 355 | } |
| 356 | count := func() (int, error) { |
| 357 | f, err := next() |
| 358 | if err != nil { |
| 359 | return 0, err |
| 360 | } |
| 361 | return strconv.Atoi(f) |
| 362 | } |
| 363 | for len(fields) > 0 { |
| 364 | kind, _ := next() |
| 365 | name, err := next() |
| 366 | if err != nil { |
| 367 | return nil, err |
| 368 | } |
| 369 | switch kind { |
| 370 | case "L": |
| 371 | n, err := count() |
| 372 | if err != nil { |
| 373 | return nil, err |
| 374 | } |
| 375 | list := []string{} |
| 376 | for range n { |
| 377 | item, err := next() |
| 378 | if err != nil { |
| 379 | return nil, err |
| 380 | } |
| 381 | list = append(list, item) |
| 382 | } |
| 383 | v.lists[name] = list |
| 384 | case "S": |
| 385 | if v.scalars[name], err = next(); err != nil { |
| 386 | return nil, err |
| 387 | } |
| 388 | case "M": |
| 389 | n, err := count() |
| 390 | if err != nil { |
| 391 | return nil, err |
| 392 | } |
| 393 | m := map[string]string{} |
| 394 | for range n { |
| 395 | k, err := next() |
| 396 | if err != nil { |
| 397 | return nil, err |
| 398 | } |
| 399 | if m[k], err = next(); err != nil { |
| 400 | return nil, err |
| 401 | } |
| 402 | } |
| 403 | v.maps[name] = m |
| 404 | default: |
| 405 | return nil, fmt.Errorf("a global of kind %q", kind) |
| 406 | } |
| 407 | } |
| 408 | for _, g := range derivation { |
| 409 | _, l := v.lists[g.name] |
| 410 | _, s := v.scalars[g.name] |
| 411 | _, m := v.maps[g.name] |
| 412 | if !l && !s && !m { |
| 413 | return nil, fmt.Errorf("no %s", g.name) |
| 414 | } |
| 415 | } |
| 416 | return v, nil |
| 417 | } |
| 418 | |
| 419 | type reportRow struct { |
| 420 | pin string |
| 421 | classes []string // the classes requiring it, unclassified included |
| 422 | cost string // from the quick: and slow: lines |
| 423 | } |
| 424 | |
| 425 | var reportHeader = regexp.MustCompile(`^[0-9a-f]+\.\.[0-9a-f]+: ([0-9]+) changed path\(s\)$`) |
| 426 | |
| 427 | func parseReport(out string) (*report, error) { |
| 428 | rep := &report{required: map[string]reportRow{}} |
| 429 | lines := strings.Split(strings.TrimSuffix(out, "\n"), "\n") |
| 430 | m := reportHeader.FindStringSubmatch(lines[0]) |
| 431 | if m == nil { |
| 432 | return nil, fmt.Errorf("no header line") |
| 433 | } |
| 434 | rep.paths, _ = strconv.Atoi(m[1]) |
| 435 | splitList := func(s string) []string { |
| 436 | if s == "none" { |
| 437 | return nil |
| 438 | } |
| 439 | return strings.Split(s, ", ") |
| 440 | } |
| 441 | for i := 1; i < len(lines); i++ { |
| 442 | line := lines[i] |
| 443 | switch { |
| 444 | case strings.HasPrefix(line, "classes matched: "): |
| 445 | rep.classes = splitList(strings.TrimPrefix(line, "classes matched: ")) |
| 446 | case strings.HasPrefix(line, "carry mode: "): |
| 447 | rep.carry = strings.TrimPrefix(line, "carry mode: ") |
| 448 | case line == "required checks:": |
| 449 | for i++; i < len(lines) && lines[i] != ""; i++ { |
| 450 | f := strings.Fields(lines[i]) |
| 451 | if len(f) < 3 { |
| 452 | return nil, fmt.Errorf("a required-check row %q", lines[i]) |
| 453 | } |
| 454 | rep.required[f[0]] = reportRow{pin: f[1], classes: splitList(strings.Join(f[2:], " "))} |
| 455 | } |
| 456 | case strings.HasPrefix(line, "unclassified: "): |
| 457 | for i++; i < len(lines) && lines[i] != ""; i++ { |
| 458 | if lines[i] == " the policy requires nothing of them — it is behind the tree" { |
| 459 | continue |
| 460 | } |
| 461 | rep.unclassified = append(rep.unclassified, strings.TrimPrefix(lines[i], " ")) |
| 462 | } |
| 463 | case strings.HasPrefix(line, "quick: "), strings.HasPrefix(line, "slow: "): |
| 464 | cost, list, _ := strings.Cut(line, ": ") |
| 465 | for _, name := range splitList(list) { |
| 466 | row, ok := rep.required[name] |
| 467 | if !ok { |
| 468 | return nil, fmt.Errorf("%s lists %s, which no row requires", cost, name) |
| 469 | } |
| 470 | row.cost = cost |
| 471 | rep.required[name] = row |
| 472 | } |
| 473 | } |
| 474 | } |
| 475 | if rep.carry == "" { |
| 476 | return nil, fmt.Errorf("no carry mode") |
| 477 | } |
| 478 | return rep, nil |
| 479 | } |
| 480 | |
| 481 | // agree reports every way the Go deriver's answer differs from what |
| 482 | // bin/valley derived: its report, and every global of its derivation, each |
| 483 | // compared whole and in order. bin/valley names the unclassified set as a |
| 484 | // class called unclassified, so that is how the Go answer is read here. |
| 485 | // |
| 486 | // A check's validity is the one field of the Go answer bin/valley does not |
| 487 | // read, so it is not compared. |
| 488 | func agree(rep *report, m *composed.Model, res *Result) []string { |
| 489 | var diffs []string |
| 490 | differ := func(what string, bash, gos any) { |
| 491 | diffs = append(diffs, fmt.Sprintf("%s: bin/valley %q, Go %q", what, bash, gos)) |
| 492 | } |
| 493 | agreeVars(rep.vars, m, res, differ) |
| 494 | if rep.paths != len(res.Paths) { |
| 495 | differ("changed paths", strconv.Itoa(rep.paths), strconv.Itoa(len(res.Paths))) |
| 496 | } |
| 497 | classes := append([]string{}, res.Classes...) |
| 498 | if len(res.Unclassified) > 0 { |
| 499 | classes = append(classes, "unclassified") |
| 500 | } |
| 501 | if !sameSet(rep.classes, classes) { |
| 502 | differ("classes matched", rep.classes, classes) |
| 503 | } |
| 504 | if rep.carry != res.Carry { |
| 505 | differ("carry mode", rep.carry, res.Carry) |
| 506 | } |
| 507 | if !sameSet(rep.unclassified, res.Unclassified) { |
| 508 | differ("unclassified paths", rep.unclassified, res.Unclassified) |
| 509 | } |
| 510 | got := map[string]Required{} |
| 511 | for _, q := range res.Required { |
| 512 | got[q.Name] = q |
| 513 | } |
| 514 | for name, row := range rep.required { |
| 515 | q, ok := got[name] |
| 516 | if !ok { |
| 517 | differ("required "+name, "required", "not required") |
| 518 | continue |
| 519 | } |
| 520 | by := append([]string{}, q.Classes...) |
| 521 | if q.Unclassified { |
| 522 | by = append(by, "unclassified") |
| 523 | } |
| 524 | if !sameSet(row.classes, by) { |
| 525 | differ(name+"'s classes", row.classes, by) |
| 526 | } |
| 527 | if row.pin != string(q.Pin) { |
| 528 | differ(name+"'s pin", row.pin, string(q.Pin)) |
| 529 | } |
| 530 | if row.cost != q.Cost { |
| 531 | differ(name+"'s cost", row.cost, q.Cost) |
| 532 | } |
| 533 | } |
| 534 | for name := range got { |
| 535 | if _, ok := rep.required[name]; !ok { |
| 536 | differ("required "+name, "not required", "required") |
| 537 | } |
| 538 | } |
| 539 | sort.Strings(diffs) |
| 540 | return diffs |
| 541 | } |
| 542 | |
| 543 | // agreeVars is agree for the globals of bin/valley's derivation. |
| 544 | func agreeVars(v *vars, m *composed.Model, res *Result, differ func(string, any, any)) { |
| 545 | list := func(name string, want []string) { |
| 546 | if !slices.Equal(v.lists[name], want) { |
| 547 | differ(name, v.lists[name], want) |
| 548 | } |
| 549 | } |
| 550 | scalar := func(name, want string) { |
| 551 | if v.scalars[name] != want { |
| 552 | differ(name, v.scalars[name], want) |
| 553 | } |
| 554 | } |
| 555 | dict := func(name string, want map[string]string) { |
| 556 | if !maps.Equal(v.maps[name], want) { |
| 557 | differ(name, v.maps[name], want) |
| 558 | } |
| 559 | } |
| 560 | |
| 561 | list("POLICY_LAYER", m.Documents) |
| 562 | list("DERIVED_PATHS", res.Paths) |
| 563 | matched := append([]string{}, res.Classes...) |
| 564 | if len(res.Unclassified) > 0 { |
| 565 | matched = append(matched, "unclassified") |
| 566 | } |
| 567 | sort.Strings(matched) |
| 568 | list("DERIVED_MATCHED", matched) |
| 569 | list("DERIVED_UNCOVERED", res.Unclassified) |
| 570 | scalar("DERIVED_CARRY", res.Carry) |
| 571 | |
| 572 | unclassified := "0" |
| 573 | required, pinned := map[string]string{}, map[string]string{} |
| 574 | runner, attribute, command, cost := map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{} |
| 575 | for _, q := range res.Required { |
| 576 | by := append([]string{}, q.Classes...) |
| 577 | if q.Unclassified { |
| 578 | by = append(by, "unclassified") |
| 579 | unclassified = "1" |
| 580 | } |
| 581 | sort.Strings(by) |
| 582 | required[q.Name] = strings.Join(by, ", ") |
| 583 | pinned[q.Name] = string(q.Pin) |
| 584 | // How each required check is run, as the Go answer gives it. |
| 585 | if q.Runner != v.maps["CHECK_RUNNER"][q.Name] || q.Attribute != v.maps["CHECK_ATTRIBUTE"][q.Name] || |
| 586 | q.Command != v.maps["CHECK_COMMAND"][q.Name] || q.Cost != v.maps["CHECK_COST"][q.Name] { |
| 587 | differ("how "+q.Name+" is run (runner, attribute, command, cost)", |
| 588 | []string{v.maps["CHECK_RUNNER"][q.Name], v.maps["CHECK_ATTRIBUTE"][q.Name], v.maps["CHECK_COMMAND"][q.Name], v.maps["CHECK_COST"][q.Name]}, |
| 589 | []string{q.Runner, q.Attribute, q.Command, q.Cost}) |
| 590 | } |
| 591 | } |
| 592 | scalar("DERIVED_UNCLASSIFIED", unclassified) |
| 593 | dict("DERIVED_REQUIRED", required) |
| 594 | dict("DERIVED_PINNED", pinned) |
| 595 | |
| 596 | // The whole catalogue, required or not: an attribute for the nix |
| 597 | // runner and a command for the command runner, as bin/valley renders |
| 598 | // them. |
| 599 | for name, c := range m.Checks { |
| 600 | runner[name], cost[name] = c.Runner, c.Cost |
| 601 | switch c.Runner { |
| 602 | case "nix": |
| 603 | attribute[name] = c.Attribute |
| 604 | case "command": |
| 605 | command[name] = c.Command |
| 606 | } |
| 607 | } |
| 608 | dict("CHECK_RUNNER", runner) |
| 609 | dict("CHECK_ATTRIBUTE", attribute) |
| 610 | dict("CHECK_COMMAND", command) |
| 611 | dict("CHECK_COST", cost) |
| 612 | } |
| 613 | |
| 614 | func sameSet(a, b []string) bool { |
| 615 | a, b = sortedSet(a), sortedSet(b) |
| 616 | if len(a) != len(b) { |
| 617 | return false |
| 618 | } |
| 619 | for i := range a { |
| 620 | if a[i] != b[i] { |
| 621 | return false |
| 622 | } |
| 623 | } |
| 624 | return true |
| 625 | } |
| 626 | |
| 627 | // names are the required checks' names, sorted. |
| 628 | func names(res *Result) []string { |
| 629 | var out []string |
| 630 | for _, q := range res.Required { |
| 631 | out = append(out, q.Name) |
| 632 | } |
| 633 | return out |
| 634 | } |
| 635 | |
| 636 | // entry is one file of a scratch tree: its mode and its content, which |
| 637 | // for a symbolic link is its target. |
| 638 | type entry struct{ mode, content string } |
| 639 | |
| 640 | // tree is a scratch commit's files, by path. |
| 641 | type tree map[string]entry |
| 642 | |
| 643 | // repo is a scratch repository whose commits are written straight into |
| 644 | // its object store, so a path may hold any byte a git path may, whatever |
| 645 | // the file system makes of it. |
| 646 | type repo struct { |
| 647 | t *testing.T |
| 648 | dir string |
| 649 | env []string |
| 650 | blobs map[string]string |
| 651 | n int |
| 652 | } |
| 653 | |
| 654 | func newRepo(t *testing.T, r *rig) *repo { |
| 655 | t.Helper() |
| 656 | rp := &repo{t: t, dir: t.TempDir(), env: r.env, blobs: map[string]string{}} |
| 657 | rp.git(nil, "init", "--quiet", "--initial-branch=main") |
| 658 | return rp |
| 659 | } |
| 660 | |
| 661 | func (rp *repo) git(stdin []byte, args ...string) string { |
| 662 | rp.t.Helper() |
| 663 | return rp.gitEnv(nil, stdin, args...) |
| 664 | } |
| 665 | |
| 666 | func (rp *repo) gitEnv(env []string, stdin []byte, args ...string) string { |
| 667 | rp.t.Helper() |
| 668 | cmd := exec.Command("git", args...) |
| 669 | cmd.Dir = rp.dir |
| 670 | cmd.Env = append(append([]string{}, rp.env...), env...) |
| 671 | cmd.Stdin = bytes.NewReader(stdin) |
| 672 | var stdout, stderr bytes.Buffer |
| 673 | cmd.Stdout, cmd.Stderr = &stdout, &stderr |
| 674 | if err := cmd.Run(); err != nil { |
| 675 | rp.t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, stderr.String()) |
| 676 | } |
| 677 | return strings.TrimSpace(stdout.String()) |
| 678 | } |
| 679 | |
| 680 | // commit writes files as one commit on parent, which may be "", and |
| 681 | // returns it. |
| 682 | func (rp *repo) commit(parent string, files tree) string { |
| 683 | rp.t.Helper() |
| 684 | var info bytes.Buffer |
| 685 | paths := make([]string, 0, len(files)) |
| 686 | for p := range files { |
| 687 | paths = append(paths, p) |
| 688 | } |
| 689 | sort.Strings(paths) |
| 690 | for _, p := range paths { |
| 691 | e := files[p] |
| 692 | blob, ok := rp.blobs[e.content] |
| 693 | if !ok { |
| 694 | blob = rp.git([]byte(e.content), "hash-object", "-w", "--stdin") |
| 695 | rp.blobs[e.content] = blob |
| 696 | } |
| 697 | fmt.Fprintf(&info, "%s %s\t%s\x00", e.mode, blob, p) |
| 698 | } |
| 699 | rp.n++ |
| 700 | index := []string{"GIT_INDEX_FILE=" + filepath.Join(rp.dir, ".git", fmt.Sprintf("scratch-index-%d", rp.n))} |
| 701 | rp.gitEnv(index, info.Bytes(), "update-index", "--add", "-z", "--index-info") |
| 702 | tr := rp.gitEnv(index, nil, "write-tree") |
| 703 | args := []string{"commit-tree", tr, "-m", fmt.Sprintf("commit %d", rp.n)} |
| 704 | if parent != "" { |
| 705 | args = append(args, "-p", parent) |
| 706 | } |
| 707 | return rp.git(nil, args...) |
| 708 | } |
| 709 | |
| 710 | // file is a regular file holding content. |
| 711 | func file(content string) entry { return entry{mode: "100644", content: content} } |