| 1 | package derive |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "fmt" |
| 6 | "math/rand/v2" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "path/filepath" |
| 10 | "sort" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | |
| 14 | "the-valley/composed" |
| 15 | ) |
| 16 | |
| 17 | // fixture is one policy both derivers are run under, and how many cases |
| 18 | // are drawn for it. |
| 19 | type fixture struct { |
| 20 | name string |
| 21 | instance, project []string |
| 22 | cases int |
| 23 | } |
| 24 | |
| 25 | // fixtures are the policies this repository carries: its own project |
| 26 | // layer, under the example floor and template own-policy composes it with |
| 27 | // because the owning valley's floor is not in this tree; the scratch policy |
| 28 | // policy-deriver drives; the worked example; the policy self-update's |
| 29 | // smoke test ships; and each carry case cue-vet vets, as a floor under a |
| 30 | // project that adds nothing. |
| 31 | func fixtures(t *testing.T, r *rig) []fixture { |
| 32 | fs := []fixture{ |
| 33 | {"own", []string{r.path("examples/policy/instance/floor-format.cue"), r.path("examples/policy/instance/template-docs.cue")}, r.glob(t, "policy/project/*.cue"), 16}, |
| 34 | {"deriver", r.glob(t, "examples/policy/deriver/[ft]*.cue"), []string{r.path("examples/policy/deriver/project.cue")}, 30}, |
| 35 | {"example", r.glob(t, "examples/policy/instance/*.cue"), r.glob(t, "examples/policy/project/*.cue"), 16}, |
| 36 | {"smoke", r.glob(t, "examples/policy/smoke/instance/*.cue"), r.glob(t, "examples/policy/smoke/project/*.cue"), 10}, |
| 37 | } |
| 38 | for _, f := range r.glob(t, "examples/policy/carry/*.cue") { |
| 39 | fs = append(fs, fixture{"carry-" + strings.TrimSuffix(filepath.Base(f), ".cue"), []string{f}, nil, 6}) |
| 40 | } |
| 41 | return fs |
| 42 | } |
| 43 | |
| 44 | // TestDeriversAgree runs both derivers over every fixture policy and cases |
| 45 | // drawn from a fixed seed, and requires the same answer from each: the |
| 46 | // same changed paths, classes, carry mode and unclassified paths, and the |
| 47 | // same required checks with the same classes, pins and costs. |
| 48 | // |
| 49 | // A case is a change from one base tree: files modified, added, deleted, |
| 50 | // renamed and turned into symbolic links, at paths drawn from instances of |
| 51 | // every glob the policy names, near misses of each, and names chosen to be |
| 52 | // awkward. A newline in a path is the one thing no case holds, because |
| 53 | // bin/valley splits such a path in two (TestKnownDivergences). |
| 54 | func TestDeriversAgree(t *testing.T) { |
| 55 | r := newRig(t) |
| 56 | for i, f := range fixtures(t, r) { |
| 57 | t.Run(f.name, func(t *testing.T) { |
| 58 | l := newLayers(t, f.instance, f.project, nil) |
| 59 | m, err := r.read(l) |
| 60 | if err != nil { |
| 61 | t.Fatalf("the Go deriver cannot read the policy: %v", err) |
| 62 | } |
| 63 | rng := rand.New(rand.NewPCG(20261021, uint64(i))) |
| 64 | pool := pathPool(m, rng) |
| 65 | rp := newRepo(t, r) |
| 66 | base := baseTree(rng, pool) |
| 67 | baseCommit := rp.commit("", base) |
| 68 | heads := []string{baseCommit, rp.commit(baseCommit, tree{})} |
| 69 | for range f.cases { |
| 70 | heads = append(heads, rp.commit(baseCommit, change(rng, base, pool))) |
| 71 | } |
| 72 | for n, head := range heads { |
| 73 | t.Run(fmt.Sprintf("case-%02d", n), func(t *testing.T) { |
| 74 | t.Parallel() |
| 75 | rep, err := r.valley(t, rp.dir, r.schema, l, baseCommit, head) |
| 76 | if err != nil { |
| 77 | t.Fatalf("bin/valley refused: %v", err) |
| 78 | } |
| 79 | res, err := r.derive(m, rp.dir, baseCommit, head) |
| 80 | if err != nil { |
| 81 | t.Fatalf("the Go deriver refused: %v", err) |
| 82 | } |
| 83 | if diffs := agree(rep, res); len(diffs) > 0 { |
| 84 | t.Errorf("the derivers disagree over %q:\n %s", res.Paths, strings.Join(diffs, "\n ")) |
| 85 | } |
| 86 | }) |
| 87 | } |
| 88 | }) |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | // TestReplacementRefsChangeNothing holds both derivers to reading the |
| 93 | // commits they are given, with replacement refs on in git's configuration |
| 94 | // and a replacement standing the uncovered case's head in for another. |
| 95 | func TestReplacementRefsChangeNothing(t *testing.T) { |
| 96 | r := newRig(t) |
| 97 | l := newLayers(t, r.glob(t, "examples/policy/deriver/[ft]*.cue"), []string{r.path("examples/policy/deriver/project.cue")}, nil) |
| 98 | m, err := r.read(l) |
| 99 | if err != nil { |
| 100 | t.Fatal(err) |
| 101 | } |
| 102 | rp := newRepo(t, r) |
| 103 | base := rp.commit("", tree{"Makefile": file("seed\n"), "src/one.rs": file("seed\n")}) |
| 104 | uncovered := rp.commit(base, tree{"Makefile": file("edit\n"), "src/one.rs": file("seed\n")}) |
| 105 | flat := rp.commit(base, tree{"Makefile": file("seed\n"), "src/one.rs": file("edit\n")}) |
| 106 | rp.git(nil, "update-ref", "refs/replace/"+uncovered, flat) |
| 107 | on := "GIT_CONFIG_PARAMETERS='core.usereplacerefs'='true'" |
| 108 | if got := rp.gitEnv([]string{on}, nil, "diff", "--name-only", base, uncovered); got != "src/one.rs" { |
| 109 | t.Fatalf("the replacement did not take, so this case proves nothing: %q", got) |
| 110 | } |
| 111 | rep, err := r.valley(t, rp.dir, r.schema, l, base, uncovered, on) |
| 112 | if err != nil { |
| 113 | t.Fatal(err) |
| 114 | } |
| 115 | res, err := r.derive(m, rp.dir, base, uncovered, on) |
| 116 | if err != nil { |
| 117 | t.Fatal(err) |
| 118 | } |
| 119 | if diffs := agree(rep, res); len(diffs) > 0 { |
| 120 | t.Errorf("the derivers disagree:\n %s", strings.Join(diffs, "\n ")) |
| 121 | } |
| 122 | if got := names(res); !sameSet(got, []string{"c-uncovered"}) { |
| 123 | t.Errorf("a replacement ref changed what is required: %q", got) |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | // TestKnownDivergences records each place bin/valley's deriver is wrong |
| 128 | // (bug bd-11e0e4d) and the Go deriver is not: what each one answers. When |
| 129 | // bin/valley's answer changes, so must this test. |
| 130 | func TestKnownDivergences(t *testing.T) { |
| 131 | r := newRig(t) |
| 132 | floor := r.glob(t, "examples/policy/deriver/[ft]*.cue") |
| 133 | project := []string{r.path("examples/policy/deriver/project.cue")} |
| 134 | rp := newRepo(t, r) |
| 135 | seed := tree{"docs/kept.md": file("seed\n"), "Makefile": file("seed\n")} |
| 136 | base := rp.commit("", seed) |
| 137 | with := func(path string) string { |
| 138 | files := tree{path: file("added\n")} |
| 139 | for p, e := range seed { |
| 140 | files[p] = e |
| 141 | } |
| 142 | return rp.commit(base, files) |
| 143 | } |
| 144 | bash := func(t *testing.T, l layers, head string) (*report, error) { |
| 145 | t.Helper() |
| 146 | return r.valley(t, rp.dir, r.schema, l, base, head) |
| 147 | } |
| 148 | gos := func(t *testing.T, l layers, head string) *Result { |
| 149 | t.Helper() |
| 150 | m, err := r.read(l) |
| 151 | if err != nil { |
| 152 | t.Fatalf("the Go deriver cannot read the policy: %v", err) |
| 153 | } |
| 154 | res, err := r.derive(m, rp.dir, base, head) |
| 155 | if err != nil { |
| 156 | t.Fatalf("the Go deriver refused: %v", err) |
| 157 | } |
| 158 | return res |
| 159 | } |
| 160 | requires := func(t *testing.T, who string, got, want []string) { |
| 161 | t.Helper() |
| 162 | if !sameSet(got, want) { |
| 163 | t.Errorf("%s requires %q, and this test records %q", who, got, want) |
| 164 | } |
| 165 | } |
| 166 | reportNames := func(rep *report) []string { |
| 167 | var out []string |
| 168 | for name := range rep.required { |
| 169 | out = append(out, name) |
| 170 | } |
| 171 | return out |
| 172 | } |
| 173 | |
| 174 | // diff_paths prints each path on a line of its own, so a path holding a |
| 175 | // newline is read as two. src/a<newline>b.rs matches the flat and deep |
| 176 | // classes whole; its two halves match no class. |
| 177 | t.Run("a newline in a path", func(t *testing.T) { |
| 178 | l := newLayers(t, floor, project, nil) |
| 179 | head := with("src/a\nb.rs") |
| 180 | rep, err := bash(t, l, head) |
| 181 | if err != nil { |
| 182 | t.Fatal(err) |
| 183 | } |
| 184 | if rep.paths != 2 || !sameSet(rep.unclassified, []string{"src/a", "b.rs"}) { |
| 185 | t.Errorf("bin/valley read %d paths, %q unclassified; this test records 2, src/a and b.rs", rep.paths, rep.unclassified) |
| 186 | } |
| 187 | requires(t, "bin/valley", reportNames(rep), []string{"c-uncovered"}) |
| 188 | res := gos(t, l, head) |
| 189 | if !sameSet(res.Paths, []string{"src/a\nb.rs"}) || len(res.Unclassified) != 0 { |
| 190 | t.Errorf("the Go deriver read %q, %q unclassified", res.Paths, res.Unclassified) |
| 191 | } |
| 192 | requires(t, "the Go deriver", names(res), []string{"c-deep", "c-flat"}) |
| 193 | }) |
| 194 | |
| 195 | // The schema's cross-check reads the layers' composition, not `policy`, |
| 196 | // so a class added by refining `policy` may require a check nobody |
| 197 | // defines, and cue vet passes. bin/valley derives as usual until a change |
| 198 | // touches that class, and then fails on an unbound variable while it |
| 199 | // groups the checks by cost. The Go deriver refuses the policy. |
| 200 | t.Run("a class added at policy requires an undefined check", func(t *testing.T) { |
| 201 | l := newLayers(t, floor, project, map[string]string{"ghost.cue": "package verification\n" + |
| 202 | `policy: classes: sneaky: {paths: "sneak/**": true, requires: ghost: true}` + "\n"}) |
| 203 | if _, err := r.read(l); err == nil || !strings.Contains(err.Error(), "class sneaky requires check ghost, which the composed policy does not define") { |
| 204 | t.Errorf("the Go deriver read the policy: %v", err) |
| 205 | } |
| 206 | _, err := bash(t, l, with("sneak/x")) |
| 207 | if err == nil || !strings.Contains(err.Error(), "unbound variable") { |
| 208 | t.Errorf("bin/valley did not fail on an unbound variable for a change touching the class: %v", err) |
| 209 | } |
| 210 | rep, err := bash(t, l, with("docs/new.md")) |
| 211 | if err != nil { |
| 212 | t.Fatalf("bin/valley refused a change outside the class: %v", err) |
| 213 | } |
| 214 | requires(t, "bin/valley", reportNames(rep), []string{"c-docs", "c-tmpl"}) |
| 215 | }) |
| 216 | |
| 217 | // bin/valley renders the unclassified set's requirements as a class |
| 218 | // named unclassified, so a real class of that name shares them. Each |
| 219 | // requires the other's checks, and the class's requirement is pinned by |
| 220 | // probing the set. When both require one check, the render states it |
| 221 | // twice, and bin/valley refuses every derivation. |
| 222 | t.Run("a class named unclassified", func(t *testing.T) { |
| 223 | l := newLayers(t, floor, project, map[string]string{"odd.cue": "package verification\n" + |
| 224 | `project: classes: unclassified: {paths: "odd/**": true, requires: "c-notes": true}` + "\n"}) |
| 225 | odd, uncovered := with("odd/x"), with("Makefile.new") |
| 226 | |
| 227 | rep, err := bash(t, l, odd) |
| 228 | if err != nil { |
| 229 | t.Fatal(err) |
| 230 | } |
| 231 | requires(t, "bin/valley, for a path in the class,", reportNames(rep), []string{"c-notes", "c-uncovered"}) |
| 232 | if pin := rep.required["c-notes"].pin; pin != "default" { |
| 233 | t.Errorf("bin/valley pins the class's c-notes %s; this test records default", pin) |
| 234 | } |
| 235 | res := gos(t, l, odd) |
| 236 | requires(t, "the Go deriver, for a path in the class,", names(res), []string{"c-notes"}) |
| 237 | if q := res.Required[0]; q.Pin != composed.Mandatory || !sameSet(q.Classes, []string{"unclassified"}) || q.Unclassified { |
| 238 | t.Errorf("the Go deriver requires c-notes as %+v", q) |
| 239 | } |
| 240 | |
| 241 | rep, err = bash(t, l, uncovered) |
| 242 | if err != nil { |
| 243 | t.Fatal(err) |
| 244 | } |
| 245 | requires(t, "bin/valley, for an uncovered path,", reportNames(rep), []string{"c-notes", "c-uncovered"}) |
| 246 | res = gos(t, l, uncovered) |
| 247 | requires(t, "the Go deriver, for an uncovered path,", names(res), []string{"c-uncovered"}) |
| 248 | if len(res.Classes) != 0 || !res.Required[0].Unclassified { |
| 249 | t.Errorf("the Go deriver matched %q and required %+v", res.Classes, res.Required) |
| 250 | } |
| 251 | |
| 252 | shared := newLayers(t, floor, project, map[string]string{"odd.cue": "package verification\n" + |
| 253 | `project: classes: unclassified: {paths: "odd/**": true, requires: "c-uncovered": true}` + "\n"}) |
| 254 | if _, err := bash(t, shared, odd); err == nil || !strings.Contains(err.Error(), "rendered 'requires unclassified c-uncovered' twice") { |
| 255 | t.Errorf("bin/valley did not refuse a class sharing the unclassified set's check: %v", err) |
| 256 | } |
| 257 | res = gos(t, shared, odd) |
| 258 | requires(t, "the Go deriver, for a class sharing the set's check,", names(res), []string{"c-uncovered"}) |
| 259 | if q := res.Required[0]; !sameSet(q.Classes, []string{"unclassified"}) || q.Unclassified { |
| 260 | t.Errorf("the Go deriver requires c-uncovered as %+v", q) |
| 261 | } |
| 262 | }) |
| 263 | } |
| 264 | |
| 265 | // TestBothRefuse holds both derivers to refusing what neither may derive |
| 266 | // from: a policy cue-vet rejects, and a schema older than either deriver, |
| 267 | // with no cost or no carry modes to read. Read as a policy, either would |
| 268 | // be one whose checks cost nothing or whose classes carry everywhere. |
| 269 | func TestBothRefuse(t *testing.T) { |
| 270 | r := newRig(t) |
| 271 | rp := newRepo(t, r) |
| 272 | base := rp.commit("", tree{"src/one.rs": file("seed\n")}) |
| 273 | head := rp.commit(base, tree{"src/one.rs": file("edit\n"), "a/b": file("new\n")}) |
| 274 | refuse := func(t *testing.T, schema string, l layers) { |
| 275 | t.Helper() |
| 276 | if rep, err := r.valley(t, rp.dir, schema, l, base, head); err == nil { |
| 277 | t.Errorf("bin/valley derived %+v", rep) |
| 278 | } |
| 279 | if m, err := composed.Read(t.Context(), r.cue, schema, l.instance, l.project); err == nil { |
| 280 | t.Errorf("the Go deriver read %+v", m) |
| 281 | } |
| 282 | } |
| 283 | for _, f := range r.glob(t, "examples/policy/carry/rejected/*.cue") { |
| 284 | t.Run(filepath.Base(f), func(t *testing.T) { refuse(t, r.schema, newLayers(t, []string{f}, nil, nil)) }) |
| 285 | } |
| 286 | deriver := newLayers(t, r.glob(t, "examples/policy/deriver/[ft]*.cue"), []string{r.path("examples/policy/deriver/project.cue")}, nil) |
| 287 | body, err := os.ReadFile(r.schema) |
| 288 | if err != nil { |
| 289 | t.Fatal(err) |
| 290 | } |
| 291 | for name, line := range map[string]string{"costless": "\tcost: *\"quick\" | \"slow\"\n", "modeless": "\n_mode: "} { |
| 292 | t.Run(name, func(t *testing.T) { |
| 293 | at := bytes.Index(body, []byte(line)) |
| 294 | if at < 0 { |
| 295 | t.Fatalf("the schema has no %q, so this case proves nothing", line) |
| 296 | } |
| 297 | end := at + 1 + bytes.IndexByte(body[at+1:], '\n') |
| 298 | older := filepath.Join(t.TempDir(), "verification.cue") |
| 299 | if err := os.WriteFile(older, append(append([]byte{}, body[:at+1]...), body[end+1:]...), 0o644); err != nil { |
| 300 | t.Fatal(err) |
| 301 | } |
| 302 | refuse(t, older, deriver) |
| 303 | }) |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | // TestGlobsAgree holds Match to bin/valley's glob_ere, run by bash in the |
| 308 | // C locale, over every glob the fixture policies name, globs drawn from the |
| 309 | // characters a glob or a regular expression treats specially, and paths |
| 310 | // drawn for each. |
| 311 | func TestGlobsAgree(t *testing.T) { |
| 312 | r := newRig(t) |
| 313 | rng := rand.New(rand.NewPCG(20261021, 1000)) |
| 314 | globs := map[string]bool{"docs/": true, "docs//": true, "": true, "**": true, "a**b": true, "**/**/x": true} |
| 315 | for _, f := range fixtures(t, r) { |
| 316 | m, err := r.read(newLayers(t, f.instance, f.project, nil)) |
| 317 | if err != nil { |
| 318 | t.Fatal(err) |
| 319 | } |
| 320 | for _, c := range m.Classes { |
| 321 | for _, g := range c.Paths { |
| 322 | globs[g] = true |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | pieces := []string{"a", "b", ".", "*", "?", "/", "**", "\\", "(", ")", "[", "]", "{", "}", "+", "^", "$", "|", "é", " ", "x"} |
| 327 | for range 150 { |
| 328 | var g strings.Builder |
| 329 | for range 1 + rng.IntN(6) { |
| 330 | g.WriteString(pieces[rng.IntN(len(pieces))]) |
| 331 | } |
| 332 | globs[g.String()] = true |
| 333 | } |
| 334 | sorted := make([]string, 0, len(globs)) |
| 335 | for g := range globs { |
| 336 | sorted = append(sorted, g) |
| 337 | } |
| 338 | sort.Strings(sorted) |
| 339 | |
| 340 | chars := []string{"a", "b", "x", ".", "/", "é", "\xff", "\n", " ", "*", "?", "\\", "md", "("} |
| 341 | type pair struct{ glob, path string } |
| 342 | var pairs []pair |
| 343 | var input bytes.Buffer |
| 344 | var want strings.Builder |
| 345 | for _, g := range sorted { |
| 346 | fmt.Fprintf(&input, "G\x00%s\x00", g) |
| 347 | paths := map[string]bool{} |
| 348 | for range 8 { |
| 349 | paths[instance(g, rng)] = true |
| 350 | } |
| 351 | for range 24 { |
| 352 | var p strings.Builder |
| 353 | for range rng.IntN(9) { |
| 354 | p.WriteString(chars[rng.IntN(len(chars))]) |
| 355 | } |
| 356 | paths[p.String()] = true |
| 357 | } |
| 358 | for _, p := range sortedKeys(paths) { |
| 359 | fmt.Fprintf(&input, "P\x00%s\x00", p) |
| 360 | pairs = append(pairs, pair{g, p}) |
| 361 | if Match(g, p) { |
| 362 | want.WriteByte('0') |
| 363 | } else { |
| 364 | want.WriteByte('1') |
| 365 | } |
| 366 | } |
| 367 | } |
| 368 | program := r.functions(t, "segment_ere", "glob_ere") + ` |
| 369 | while IFS= read -r -d '' kind && IFS= read -r -d '' value; do |
| 370 | case "$kind" in |
| 371 | G) ere="$(glob_ere "$value")" ;; |
| 372 | P) if [[ $value =~ $ere ]]; then printf 0; else printf '%d' "$?"; fi ;; |
| 373 | esac |
| 374 | done |
| 375 | ` |
| 376 | got := r.bash(t, program, input.Bytes()) |
| 377 | if len(got) != len(pairs) { |
| 378 | t.Fatalf("glob_ere answered %d pairs of %d", len(got), len(pairs)) |
| 379 | } |
| 380 | failed := 0 |
| 381 | for i, p := range pairs { |
| 382 | if got[i] == want.String()[i] { |
| 383 | continue |
| 384 | } |
| 385 | if failed++; failed <= 10 { |
| 386 | t.Errorf("glob %q, path %q: glob_ere answers %c, Match %c (0 is a match)", p.glob, p.path, got[i], want.String()[i]) |
| 387 | } |
| 388 | } |
| 389 | t.Logf("%d globs, %d pairs, %d disagree", len(sorted), len(pairs), failed) |
| 390 | } |
| 391 | |
| 392 | // TestDiffReadersAgree holds Changed to bin/valley's diff_paths over the |
| 393 | // output git diff -z --name-status could give, and over every cut of some |
| 394 | // of it. Each must read the same paths in the same order, or both must |
| 395 | // refuse. diff_paths writes a path on a line of its own, so where a path |
| 396 | // holds a newline, its lines are the path split at each, and that is the |
| 397 | // divergence this records. Changed also refuses two records git never |
| 398 | // writes, which diff_paths reads: an unknown status, and an empty path. |
| 399 | func TestDiffReadersAgree(t *testing.T) { |
| 400 | r := newRig(t) |
| 401 | rng := rand.New(rand.NewPCG(20261021, 2000)) |
| 402 | statuses := []string{"A", "M", "D", "T", "R100", "R075", "C050"} |
| 403 | chars := []string{"a", "b/", "x.md", "é", "\xff", " ", "\t", "*", "\\", "-"} |
| 404 | pathOf := func(newline bool) string { |
| 405 | var p strings.Builder |
| 406 | for range 1 + rng.IntN(5) { |
| 407 | p.WriteString(chars[rng.IntN(len(chars))]) |
| 408 | } |
| 409 | if newline { |
| 410 | p.WriteString("\nmore") |
| 411 | } |
| 412 | return p.String() |
| 413 | } |
| 414 | var streams [][]byte |
| 415 | for n := range 200 { |
| 416 | var s bytes.Buffer |
| 417 | for range 1 + rng.IntN(4) { |
| 418 | status := statuses[rng.IntN(len(statuses))] |
| 419 | fmt.Fprintf(&s, "%s\x00%s\x00", status, pathOf(n%10 == 0)) |
| 420 | if status[0] == 'R' || status[0] == 'C' { |
| 421 | fmt.Fprintf(&s, "%s\x00", pathOf(false)) |
| 422 | } |
| 423 | } |
| 424 | streams = append(streams, s.Bytes()) |
| 425 | } |
| 426 | for _, s := range streams[:6] { |
| 427 | for cut := range len(s) { |
| 428 | streams = append(streams, s[:cut]) |
| 429 | } |
| 430 | } |
| 431 | unwritten := [][]byte{[]byte("Z\x00a\x00"), []byte("M\x00\x00")} |
| 432 | streams = append(streams, unwritten...) |
| 433 | |
| 434 | dir := t.TempDir() |
| 435 | for i, s := range streams { |
| 436 | if err := os.WriteFile(filepath.Join(dir, fmt.Sprintf("%05d.in", i)), s, 0o644); err != nil { |
| 437 | t.Fatal(err) |
| 438 | } |
| 439 | } |
| 440 | program := r.functions(t, "diff_paths") + ` |
| 441 | for f in "$1"/*.in; do |
| 442 | if diff_paths < "$f" > "${f%.in}.out"; then echo ok; else echo refused; fi |
| 443 | done |
| 444 | ` |
| 445 | verdicts := strings.Fields(r.bash(t, program, nil, dir)) |
| 446 | if len(verdicts) != len(streams) { |
| 447 | t.Fatalf("diff_paths read %d streams of %d", len(verdicts), len(streams)) |
| 448 | } |
| 449 | agreed, divergent := 0, 0 |
| 450 | for i, s := range streams { |
| 451 | paths, err := Changed(s) |
| 452 | out, rerr := os.ReadFile(filepath.Join(dir, fmt.Sprintf("%05d.out", i))) |
| 453 | if rerr != nil { |
| 454 | t.Fatal(rerr) |
| 455 | } |
| 456 | isUnwritten := i >= len(streams)-len(unwritten) |
| 457 | switch { |
| 458 | case isUnwritten: |
| 459 | if err == nil || verdicts[i] != "ok" { |
| 460 | t.Errorf("stream %q: Changed %v, diff_paths %s; this test records a refusal and a reading", s, err, verdicts[i]) |
| 461 | } |
| 462 | divergent++ |
| 463 | case (err == nil) != (verdicts[i] == "ok"): |
| 464 | t.Errorf("stream %q: Changed says %v, diff_paths %s", s, err, verdicts[i]) |
| 465 | case err != nil: |
| 466 | agreed++ |
| 467 | default: |
| 468 | lines := string(out) |
| 469 | want := "" |
| 470 | if len(paths) > 0 { |
| 471 | want = strings.Join(paths, "\n") + "\n" |
| 472 | } |
| 473 | if lines != want { |
| 474 | t.Errorf("stream %q: Changed read %q, diff_paths wrote %q", s, paths, lines) |
| 475 | } |
| 476 | if strings.Count(want, "\n") > len(paths) { |
| 477 | divergent++ |
| 478 | } else { |
| 479 | agreed++ |
| 480 | } |
| 481 | } |
| 482 | } |
| 483 | t.Logf("%d streams agree; %d hold a newline path or a record git never writes", agreed, divergent) |
| 484 | } |
| 485 | |
| 486 | // functions are bin/valley's definitions of the named functions, to be run |
| 487 | // on their own. |
| 488 | func (r *rig) functions(t *testing.T, names ...string) string { |
| 489 | t.Helper() |
| 490 | script, err := os.ReadFile(r.script) |
| 491 | if err != nil { |
| 492 | t.Fatal(err) |
| 493 | } |
| 494 | var out strings.Builder |
| 495 | for _, name := range names { |
| 496 | start := bytes.Index(script, []byte("\n"+name+"() {\n")) |
| 497 | if start < 0 { |
| 498 | t.Fatalf("bin/valley defines no %s", name) |
| 499 | } |
| 500 | body := script[start+1:] |
| 501 | end := bytes.Index(body, []byte("\n}\n")) |
| 502 | out.Write(body[:end+3]) |
| 503 | } |
| 504 | return out.String() |
| 505 | } |
| 506 | |
| 507 | // bash runs a program with stdin, in the rig's environment, and returns |
| 508 | // what it printed. |
| 509 | func (r *rig) bash(t *testing.T, program string, stdin []byte, args ...string) string { |
| 510 | t.Helper() |
| 511 | cmd := exec.Command("bash", append([]string{"-c", program, "bash"}, args...)...) |
| 512 | cmd.Env = r.env |
| 513 | cmd.Stdin = bytes.NewReader(stdin) |
| 514 | var stdout, stderr bytes.Buffer |
| 515 | cmd.Stdout, cmd.Stderr = &stdout, &stderr |
| 516 | if err := cmd.Run(); err != nil { |
| 517 | t.Fatalf("bash: %v\n%s", err, stderr.String()) |
| 518 | } |
| 519 | return stdout.String() |
| 520 | } |
| 521 | |
| 522 | func sortedKeys(set map[string]bool) []string { |
| 523 | out := make([]string, 0, len(set)) |
| 524 | for k := range set { |
| 525 | out = append(out, k) |
| 526 | } |
| 527 | sort.Strings(out) |
| 528 | return out |
| 529 | } |
| 530 | |
| 531 | // instance is a path made from a glob, which mostly matches it: each `**` |
| 532 | // segment made none, one or two segments, each `*` some bytes, and each `?` |
| 533 | // one character. That character is two bytes when it is é, so `?` meets a |
| 534 | // character that is not one byte. A `*` or a `?` is sometimes made a `/`, |
| 535 | // which neither may match. |
| 536 | func instance(glob string, rng *rand.Rand) string { |
| 537 | segs := strings.Split(glob, "/") |
| 538 | if segs[len(segs)-1] == "" { |
| 539 | segs = segs[:len(segs)-1] |
| 540 | } |
| 541 | stars := []string{"", "x", "x.y", "ü", "\xff", " ", "*", "q.md", "", "x", "x/y"} |
| 542 | ones := []string{"q", "é", "\xfe", "?", "q", "/"} |
| 543 | var out []string |
| 544 | for _, seg := range segs { |
| 545 | if seg == "**" { |
| 546 | out = append(out, []string{"d", "e.md", "ü"}[:rng.IntN(3)]...) |
| 547 | continue |
| 548 | } |
| 549 | var s strings.Builder |
| 550 | for i := 0; i < len(seg); i++ { |
| 551 | switch seg[i] { |
| 552 | case '*': |
| 553 | s.WriteString(stars[rng.IntN(len(stars))]) |
| 554 | case '?': |
| 555 | s.WriteString(ones[rng.IntN(len(ones))]) |
| 556 | default: |
| 557 | s.WriteByte(seg[i]) |
| 558 | } |
| 559 | } |
| 560 | out = append(out, s.String()) |
| 561 | } |
| 562 | return strings.Join(out, "/") |
| 563 | } |
| 564 | |
| 565 | // awkward are names chosen for what a reader of paths might get wrong. |
| 566 | var awkward = []string{ |
| 567 | "README.md", "a b.md", "-dash.md", "naïve.md", "caf\xe9.md", "tab\there.md", |
| 568 | "quote\"d.md", "back\\slash.md", "star*.md", "q?.md", "[br].md", "{x}.md", |
| 569 | "deep/a/b/c/d/e.txt", ".hidden", "dir.md/inner", "\xff\xfe/x", "research/notes.txt", |
| 570 | "src/x.rs.bak", "docs", "bin/valley", "flake.nix", "nix/checks/derive-unit.sh", |
| 571 | } |
| 572 | |
| 573 | // validPath reports whether git would hold p as a path. |
| 574 | func validPath(p string) bool { |
| 575 | if p == "" || strings.ContainsAny(p, "\x00\n") { |
| 576 | return false |
| 577 | } |
| 578 | for _, seg := range strings.Split(p, "/") { |
| 579 | if seg == "" || seg == "." || seg == ".." || strings.EqualFold(seg, ".git") { |
| 580 | return false |
| 581 | } |
| 582 | } |
| 583 | return true |
| 584 | } |
| 585 | |
| 586 | // pathPool is what a fixture's cases are drawn from: instances of every |
| 587 | // glob the policy names, near misses of each, and the awkward names. |
| 588 | func pathPool(m *composed.Model, rng *rand.Rand) []string { |
| 589 | set := map[string]bool{} |
| 590 | add := func(p string) { |
| 591 | if validPath(p) { |
| 592 | set[p] = true |
| 593 | } |
| 594 | } |
| 595 | classes := make([]string, 0, len(m.Classes)) |
| 596 | for name := range m.Classes { |
| 597 | classes = append(classes, name) |
| 598 | } |
| 599 | sort.Strings(classes) |
| 600 | for _, name := range classes { |
| 601 | for _, g := range m.Classes[name].Paths { |
| 602 | for range 3 { |
| 603 | p := instance(g, rng) |
| 604 | add(p) |
| 605 | add("zz/" + p) |
| 606 | add(p + "x") |
| 607 | if i := strings.LastIndexByte(p, '/'); i > 0 { |
| 608 | add(p[:i] + "/zz" + p[i:]) |
| 609 | } |
| 610 | } |
| 611 | } |
| 612 | } |
| 613 | for _, p := range awkward { |
| 614 | add(p) |
| 615 | } |
| 616 | return sortedKeys(set) |
| 617 | } |
| 618 | |
| 619 | // fits reports whether p can join t: no path of t is a directory of p's, |
| 620 | // and p is no directory of a path of t. |
| 621 | func fits(t tree, p string) bool { |
| 622 | if _, ok := t[p]; ok { |
| 623 | return false |
| 624 | } |
| 625 | for q := range t { |
| 626 | if strings.HasPrefix(p, q+"/") || strings.HasPrefix(q, p+"/") { |
| 627 | return false |
| 628 | } |
| 629 | } |
| 630 | return true |
| 631 | } |
| 632 | |
| 633 | // baseTree is about half the pool. |
| 634 | func baseTree(rng *rand.Rand, pool []string) tree { |
| 635 | t := tree{} |
| 636 | for _, p := range pool { |
| 637 | if rng.IntN(2) == 0 && fits(t, p) { |
| 638 | t[p] = file("base " + p + "\n") |
| 639 | } |
| 640 | } |
| 641 | return t |
| 642 | } |
| 643 | |
| 644 | // change is base with one to six changes made to it. |
| 645 | func change(rng *rand.Rand, base tree, pool []string) tree { |
| 646 | t := tree{} |
| 647 | for p, e := range base { |
| 648 | t[p] = e |
| 649 | } |
| 650 | existing := func() string { |
| 651 | paths := make([]string, 0, len(t)) |
| 652 | for p := range t { |
| 653 | paths = append(paths, p) |
| 654 | } |
| 655 | sort.Strings(paths) |
| 656 | if len(paths) == 0 { |
| 657 | return "" |
| 658 | } |
| 659 | return paths[rng.IntN(len(paths))] |
| 660 | } |
| 661 | fresh := func() string { |
| 662 | for range 20 { |
| 663 | if p := pool[rng.IntN(len(pool))]; fits(t, p) { |
| 664 | return p |
| 665 | } |
| 666 | } |
| 667 | return "" |
| 668 | } |
| 669 | for n := range 1 + rng.IntN(6) { |
| 670 | switch rng.IntN(5) { |
| 671 | case 0: // modify |
| 672 | if p := existing(); p != "" { |
| 673 | t[p] = file(fmt.Sprintf("edit %d of %s\n", n, p)) |
| 674 | } |
| 675 | case 1: // delete |
| 676 | if p := existing(); p != "" { |
| 677 | delete(t, p) |
| 678 | } |
| 679 | case 2: // add |
| 680 | if p := fresh(); p != "" { |
| 681 | t[p] = file("added " + p + "\n") |
| 682 | } |
| 683 | case 3: // rename |
| 684 | if from := existing(); from != "" { |
| 685 | e := t[from] |
| 686 | delete(t, from) |
| 687 | if to := fresh(); to != "" { |
| 688 | t[to] = e |
| 689 | } else { |
| 690 | t[from] = e |
| 691 | } |
| 692 | } |
| 693 | case 4: // turn into a symbolic link |
| 694 | if p := existing(); p != "" { |
| 695 | t[p] = entry{mode: "120000", content: "target-of-" + p} |
| 696 | } |
| 697 | } |
| 698 | } |
| 699 | return t |
| 700 | } |