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