| 1 | package derive |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "fmt" |
| 6 | "maps" |
| 7 | "math/rand/v2" |
| 8 | "os" |
| 9 | "os/exec" |
| 10 | "path/filepath" |
| 11 | "regexp" |
| 12 | "slices" |
| 13 | "sort" |
| 14 | "strings" |
| 15 | "testing" |
| 16 | |
| 17 | "the-valley/composed" |
| 18 | ) |
| 19 | |
| 20 | // fixture is one policy both derivers are run under, and how many cases |
| 21 | // are drawn for it. |
| 22 | type fixture struct { |
| 23 | name string |
| 24 | instance, project []string |
| 25 | cases int |
| 26 | } |
| 27 | |
| 28 | // fixtures are the policies this repository carries: its own project |
| 29 | // layer, under the example floor and template own-policy composes it with |
| 30 | // because the owning valley's floor is not in this tree; the scratch policy |
| 31 | // policy-deriver drives; the worked example; the policy self-update's |
| 32 | // smoke test ships; and each carry case cue-vet vets, as a floor under a |
| 33 | // project that adds nothing. |
| 34 | func fixtures(t *testing.T, r *rig) []fixture { |
| 35 | fs := []fixture{ |
| 36 | {"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}, |
| 37 | {"deriver", r.glob(t, "examples/policy/deriver/[ft]*.cue"), []string{r.path("examples/policy/deriver/project.cue")}, 30}, |
| 38 | {"example", r.glob(t, "examples/policy/instance/*.cue"), r.glob(t, "examples/policy/project/*.cue"), 16}, |
| 39 | {"smoke", r.glob(t, "examples/policy/smoke/instance/*.cue"), r.glob(t, "examples/policy/smoke/project/*.cue"), 10}, |
| 40 | } |
| 41 | for _, f := range r.glob(t, "examples/policy/carry/*.cue") { |
| 42 | fs = append(fs, fixture{"carry-" + strings.TrimSuffix(filepath.Base(f), ".cue"), []string{f}, nil, 6}) |
| 43 | } |
| 44 | return fs |
| 45 | } |
| 46 | |
| 47 | // TestDeriversAgree runs both derivers over every fixture policy and cases |
| 48 | // drawn from a fixed seed, and requires the same answer from each: the |
| 49 | // same documents composed, the same changed paths in the same order, the |
| 50 | // same classes, carry mode and unclassified paths, and the same required |
| 51 | // checks with the same classes, pins, runners, attributes, commands and |
| 52 | // costs. bin/valley is run under every locale (locales), and the fixtures' |
| 53 | // layer directories are named in turn as each of namings names them. |
| 54 | // |
| 55 | // A case is a change from one base tree: files modified, added, deleted, |
| 56 | // renamed and turned into symbolic links, at paths drawn from instances of |
| 57 | // every glob the policy names, near misses of each, and names chosen to be |
| 58 | // awkward. A newline in a path is the one thing no case holds, because |
| 59 | // bin/valley splits such a path in two (TestKnownDivergences). |
| 60 | func TestDeriversAgree(t *testing.T) { |
| 61 | r := newRig(t) |
| 62 | locs := r.locales(t) |
| 63 | for i, f := range fixtures(t, r) { |
| 64 | t.Run(f.name, func(t *testing.T) { |
| 65 | l := newLayersAt(t, namings[i%len(namings)], f.instance, f.project, nil) |
| 66 | m, err := r.read(l) |
| 67 | if err != nil { |
| 68 | t.Fatalf("the Go deriver cannot read the policy: %v", err) |
| 69 | } |
| 70 | rng := rand.New(rand.NewPCG(20261021, uint64(i))) |
| 71 | pool := pathPool(m, rng) |
| 72 | rp := newRepo(t, r) |
| 73 | base := baseTree(rng, pool) |
| 74 | baseCommit := rp.commit("", base) |
| 75 | heads := []string{baseCommit, rp.commit(baseCommit, tree{})} |
| 76 | for range f.cases { |
| 77 | heads = append(heads, rp.commit(baseCommit, change(rng, base, pool))) |
| 78 | } |
| 79 | for n, head := range heads { |
| 80 | t.Run(fmt.Sprintf("case-%02d", n), func(t *testing.T) { |
| 81 | t.Parallel() |
| 82 | res, err := r.derive(m, rp.dir, baseCommit, head) |
| 83 | if err != nil { |
| 84 | t.Fatalf("the Go deriver refused: %v", err) |
| 85 | } |
| 86 | for _, loc := range locs { |
| 87 | rep, err := r.valleyIn(t, loc, rp.dir, r.schema, l, baseCommit, head) |
| 88 | if err != nil { |
| 89 | t.Fatalf("bin/valley refused in %s: %v", loc.name, err) |
| 90 | } |
| 91 | if diffs := agree(rep, m, res); len(diffs) > 0 { |
| 92 | t.Errorf("the derivers disagree in %s over %q:\n %s", loc.name, res.Paths, strings.Join(diffs, "\n ")) |
| 93 | } |
| 94 | } |
| 95 | }) |
| 96 | } |
| 97 | }) |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | // TestReplacementRefsChangeNothing holds both derivers to reading the |
| 102 | // commits they are given, with replacement refs on in git's configuration |
| 103 | // and a replacement standing the uncovered case's head in for another. |
| 104 | func TestReplacementRefsChangeNothing(t *testing.T) { |
| 105 | r := newRig(t) |
| 106 | l := newLayers(t, r.glob(t, "examples/policy/deriver/[ft]*.cue"), []string{r.path("examples/policy/deriver/project.cue")}, nil) |
| 107 | m, err := r.read(l) |
| 108 | if err != nil { |
| 109 | t.Fatal(err) |
| 110 | } |
| 111 | rp := newRepo(t, r) |
| 112 | base := rp.commit("", tree{"Makefile": file("seed\n"), "src/one.rs": file("seed\n")}) |
| 113 | uncovered := rp.commit(base, tree{"Makefile": file("edit\n"), "src/one.rs": file("seed\n")}) |
| 114 | flat := rp.commit(base, tree{"Makefile": file("seed\n"), "src/one.rs": file("edit\n")}) |
| 115 | rp.git(nil, "update-ref", "refs/replace/"+uncovered, flat) |
| 116 | on := "GIT_CONFIG_PARAMETERS='core.usereplacerefs'='true'" |
| 117 | if got := rp.gitEnv([]string{on}, nil, "diff", "--name-only", base, uncovered); got != "src/one.rs" { |
| 118 | t.Fatalf("the replacement did not take, so this case proves nothing: %q", got) |
| 119 | } |
| 120 | rep, err := r.valley(t, rp.dir, r.schema, l, base, uncovered, on) |
| 121 | if err != nil { |
| 122 | t.Fatal(err) |
| 123 | } |
| 124 | res, err := r.derive(m, rp.dir, base, uncovered, on) |
| 125 | if err != nil { |
| 126 | t.Fatal(err) |
| 127 | } |
| 128 | if diffs := agree(rep, m, res); len(diffs) > 0 { |
| 129 | t.Errorf("the derivers disagree:\n %s", strings.Join(diffs, "\n ")) |
| 130 | } |
| 131 | if got := names(res); !sameSet(got, []string{"c-uncovered"}) { |
| 132 | t.Errorf("a replacement ref changed what is required: %q", got) |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | // TestLocaleChangesNothing holds both derivers to one answer in every |
| 137 | // locale, for the paths a locale reads differently, and holds that answer |
| 138 | // to bytes. A glob matches bytes: `?` is one byte, so `?.md` covers x.md |
| 139 | // and not é.md, whose é is two, and `**` and `*` cover bytes that are not |
| 140 | // UTF-8, which a UTF-8 locale's regular expressions match nothing of. Two |
| 141 | // paths that differ in one such byte are two paths, which sort -u under |
| 142 | // en_US.UTF-8 would merge. |
| 143 | func TestLocaleChangesNothing(t *testing.T) { |
| 144 | r := newRig(t) |
| 145 | l := newLayers(t, r.glob(t, "examples/policy/deriver/[ft]*.cue"), []string{r.path("examples/policy/deriver/project.cue")}, |
| 146 | map[string]string{"bytes.cue": "package verification\n" + |
| 147 | `project: classes: one: {paths: "?.md": true, requires: "c-notes": true}` + "\n" + |
| 148 | `project: classes: raw: {paths: "raw/**": true, requires: "c-nested": true}` + "\n"}) |
| 149 | m, err := r.read(l) |
| 150 | if err != nil { |
| 151 | t.Fatal(err) |
| 152 | } |
| 153 | rp := newRepo(t, r) |
| 154 | base := rp.commit("", tree{"Makefile": file("seed\n")}) |
| 155 | head := rp.commit(base, tree{ |
| 156 | "Makefile": file("seed\n"), "x.md": file("x\n"), "\xc3\xa9.md": file("e\n"), |
| 157 | "raw/\xff.bin": file("ff\n"), "src/caf\xe9.rs": file("latin-1\n"), |
| 158 | "a\xffb": file("ff\n"), "a\xfeb": file("fe\n"), |
| 159 | }) |
| 160 | res, err := r.derive(m, rp.dir, base, head) |
| 161 | if err != nil { |
| 162 | t.Fatal(err) |
| 163 | } |
| 164 | if want := []string{"deep", "flat", "one", "raw"}; !slices.Equal(res.Classes, want) { |
| 165 | t.Errorf("the Go deriver matched %q; bytes match %q", res.Classes, want) |
| 166 | } |
| 167 | if want := []string{"a\xfeb", "a\xffb", "\xc3\xa9.md"}; !slices.Equal(res.Unclassified, want) { |
| 168 | t.Errorf("the Go deriver left %q unclassified; bytes leave %q", res.Unclassified, want) |
| 169 | } |
| 170 | locs := r.locales(t) |
| 171 | if len(locs) < 2 { |
| 172 | t.Skip("no UTF-8 locale takes here, so this case proves nothing") |
| 173 | } |
| 174 | for _, loc := range locs { |
| 175 | rep, err := r.valleyIn(t, loc, rp.dir, r.schema, l, base, head) |
| 176 | if err != nil { |
| 177 | t.Fatalf("bin/valley refused in %s: %v", loc.name, err) |
| 178 | } |
| 179 | if diffs := agree(rep, m, res); len(diffs) > 0 { |
| 180 | t.Errorf("the derivers disagree in %s:\n %s", loc.name, strings.Join(diffs, "\n ")) |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | // TestLayerDiscovery holds both derivers to reading a layer as bin/valley's |
| 186 | // `"$dir"/*.cue` does. The directory is a name, so one named like a pattern |
| 187 | // is read and the directories the pattern names are not. A name beginning |
| 188 | // with a dot is not a document. And a layer whose first document is not a |
| 189 | // file holds none, so both refuse it. |
| 190 | func TestLayerDiscovery(t *testing.T) { |
| 191 | r := newRig(t) |
| 192 | floor := r.glob(t, "examples/policy/deriver/[ft]*.cue") |
| 193 | project := []string{r.path("examples/policy/deriver/project.cue")} |
| 194 | rp := newRepo(t, r) |
| 195 | base := rp.commit("", tree{"docs/a.md": file("seed\n")}) |
| 196 | head := rp.commit(base, tree{"docs/a.md": file("edit\n"), "src/b.rs": file("new\n")}) |
| 197 | |
| 198 | for _, n := range namings { |
| 199 | t.Run(n.instance+" and "+n.project, func(t *testing.T) { |
| 200 | l := newLayersAt(t, n, floor, project, nil) |
| 201 | m, err := r.read(l) |
| 202 | if err != nil { |
| 203 | t.Fatalf("the Go deriver cannot read the policy: %v", err) |
| 204 | } |
| 205 | want := []string{r.schema, filepath.Join(l.instance, "floor.cue"), filepath.Join(l.instance, "template.cue"), filepath.Join(l.project, "project.cue")} |
| 206 | if !slices.Equal(m.Documents, want) { |
| 207 | t.Errorf("the Go deriver composed %q; the layers' documents are %q", m.Documents, want) |
| 208 | } |
| 209 | rep, err := r.valley(t, rp.dir, r.schema, l, base, head) |
| 210 | if err != nil { |
| 211 | t.Fatalf("bin/valley refused: %v", err) |
| 212 | } |
| 213 | res, err := r.derive(m, rp.dir, base, head) |
| 214 | if err != nil { |
| 215 | t.Fatal(err) |
| 216 | } |
| 217 | if diffs := agree(rep, m, res); len(diffs) > 0 { |
| 218 | t.Errorf("the derivers disagree:\n %s", strings.Join(diffs, "\n ")) |
| 219 | } |
| 220 | }) |
| 221 | } |
| 222 | |
| 223 | refuse := func(t *testing.T, l layers) { |
| 224 | t.Helper() |
| 225 | if rep, err := r.valley(t, rp.dir, r.schema, l, base, head); err == nil || !strings.Contains(err.Error(), "no project policy layer") { |
| 226 | t.Errorf("bin/valley did not refuse the project layer: %v, %+v", err, rep) |
| 227 | } |
| 228 | if m, err := r.read(l); err == nil || !strings.Contains(err.Error(), "no policy layer at "+l.project) { |
| 229 | t.Errorf("the Go deriver did not refuse the project layer: %v, %q", err, m.Documents) |
| 230 | } |
| 231 | } |
| 232 | t.Run("a dotfile alone", func(t *testing.T) { |
| 233 | l := newLayers(t, floor, nil, map[string]string{".only.cue": "package verification\n"}) |
| 234 | refuse(t, l) |
| 235 | }) |
| 236 | t.Run("a directory first", func(t *testing.T) { |
| 237 | l := newLayers(t, floor, project, nil) |
| 238 | if err := os.Mkdir(filepath.Join(l.project, "a.cue"), 0o755); err != nil { |
| 239 | t.Fatal(err) |
| 240 | } |
| 241 | refuse(t, l) |
| 242 | }) |
| 243 | } |
| 244 | |
| 245 | // TestLayerReadersAgree holds composed.Project to bin/valley's copy_layer, |
| 246 | // which approve reads a layer out of git with, over one tree: what each |
| 247 | // copies, and whether the layer is present, absent, or refused. copy_layer |
| 248 | // returns 0 for present, 1 for a directory holding no *.cue, which is the |
| 249 | // floor alone, and 2 for a read that failed. A present layer is then |
| 250 | // composed by both derivers, which agree on what it requires or both |
| 251 | // refuse it: a layer of dotfiles alone is present, and holds no document |
| 252 | // either composes. |
| 253 | func TestLayerReadersAgree(t *testing.T) { |
| 254 | r := newRig(t) |
| 255 | floor := newLayers(t, r.glob(t, "examples/policy/deriver/[ft]*.cue"), nil, nil).instance |
| 256 | project, err := os.ReadFile(r.path("examples/policy/deriver/project.cue")) |
| 257 | if err != nil { |
| 258 | t.Fatal(err) |
| 259 | } |
| 260 | rp := newRepo(t, r) |
| 261 | // The layers are the same in both commits, so the diff between them |
| 262 | // never reads policy/lost, whose tree is removed. Its document is its |
| 263 | // own, so no other layer shares that tree. |
| 264 | commit := func(parent string, files tree) string { |
| 265 | maps.Copy(files, tree{ |
| 266 | "policy/project/project.cue": file(string(project)), |
| 267 | "policy/project/.shadow.cue": file(notCUE), |
| 268 | "policy/proj*/project.cue": file(string(project)), |
| 269 | "policy/projX/decoy.cue": file(notCUE), |
| 270 | "policy/dotted/.only.cue": file("package verification\n"), |
| 271 | "policy/odd/x.cue/project.cue": file(string(project)), |
| 272 | "policy/prose/notes.md": file("not a document\n"), |
| 273 | "policy/lost/project.cue": file("package verification\n// lost\n"), |
| 274 | }) |
| 275 | return rp.commit(parent, files) |
| 276 | } |
| 277 | base := commit("", tree{"docs/a.md": file("seed\n")}) |
| 278 | head := commit(base, tree{"docs/a.md": file("edit\n"), "src/b.rs": file("new\n")}) |
| 279 | lost := rp.git(nil, "rev-parse", head+":policy/lost") |
| 280 | if err := os.Remove(filepath.Join(rp.dir, ".git", "objects", lost[:2], lost[2:])); err != nil { |
| 281 | t.Fatal(err) |
| 282 | } |
| 283 | copyLayer := r.functions(t, "copy_layer") + `copy_layer "$@" && rc=0 || rc=$? |
| 284 | printf %d "$rc"` |
| 285 | |
| 286 | for _, c := range []struct { |
| 287 | dir string |
| 288 | rc string |
| 289 | docs []string // what a present layer holds |
| 290 | }{ |
| 291 | {"policy/project", "0", []string{".shadow.cue", "project.cue"}}, |
| 292 | {"policy/proj*", "0", []string{"project.cue"}}, |
| 293 | {"policy/dotted", "0", []string{".only.cue"}}, |
| 294 | {"policy/odd", "2", nil}, |
| 295 | {"policy/lost", "2", nil}, |
| 296 | {"policy/prose", "1", nil}, |
| 297 | {"policy/missing", "1", nil}, |
| 298 | } { |
| 299 | t.Run(c.dir, func(t *testing.T) { |
| 300 | dest := t.TempDir() |
| 301 | if rc := r.bash(t, copyLayer, nil, rp.dir, head, c.dir, dest); rc != c.rc { |
| 302 | t.Fatalf("copy_layer returned %s, not %s", rc, c.rc) |
| 303 | } |
| 304 | dir, note, done, err := composed.Project(t.Context(), rp.dir, head, c.dir, "derive-test-") |
| 305 | defer done() |
| 306 | switch c.rc { |
| 307 | case "2": |
| 308 | if err == nil { |
| 309 | t.Fatalf("copy_layer refused the layer, and composed.Project resolved it to %s", dir) |
| 310 | } |
| 311 | return |
| 312 | case "1": |
| 313 | if err != nil || note == "" { |
| 314 | t.Fatalf("copy_layer found no layer, and composed.Project answered %q, %v", note, err) |
| 315 | } |
| 316 | return |
| 317 | } |
| 318 | if err != nil || note != "" { |
| 319 | t.Fatalf("copy_layer copied the layer, and composed.Project answered %q, %v", note, err) |
| 320 | } |
| 321 | for _, d := range []string{dest, dir} { |
| 322 | if got := entries(t, d); !slices.Equal(got, c.docs) { |
| 323 | t.Errorf("%s holds %q, not %q", d, got, c.docs) |
| 324 | } |
| 325 | } |
| 326 | for _, doc := range c.docs { |
| 327 | bash, _ := os.ReadFile(filepath.Join(dest, doc)) |
| 328 | goes, _ := os.ReadFile(filepath.Join(dir, doc)) |
| 329 | if !bytes.Equal(bash, goes) { |
| 330 | t.Errorf("%s reads %q from copy_layer and %q from composed.Project", doc, bash, goes) |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | // The two copies are the same documents, so both derivers |
| 335 | // compose one of them, and name the same paths. |
| 336 | l := layers{instance: floor, project: dir} |
| 337 | rep, bashErr := r.valley(t, rp.dir, r.schema, l, base, head) |
| 338 | m, goErr := r.read(l) |
| 339 | if (bashErr == nil) != (goErr == nil) { |
| 340 | t.Fatalf("bin/valley answered %v and the Go deriver %v", bashErr, goErr) |
| 341 | } |
| 342 | if c.dir == "policy/dotted" && goErr == nil { |
| 343 | t.Fatal("a layer of dotfiles alone was composed; both derivers leave dotfiles out, and refuse a layer with no document") |
| 344 | } |
| 345 | if goErr != nil { |
| 346 | return |
| 347 | } |
| 348 | res, err := r.derive(m, rp.dir, base, head) |
| 349 | if err != nil { |
| 350 | t.Fatal(err) |
| 351 | } |
| 352 | if diffs := agree(rep, m, res); len(diffs) > 0 { |
| 353 | t.Errorf("the derivers disagree:\n %s", strings.Join(diffs, "\n ")) |
| 354 | } |
| 355 | }) |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | // entries are the names in dir, sorted. |
| 360 | func entries(t *testing.T, dir string) []string { |
| 361 | t.Helper() |
| 362 | list, err := os.ReadDir(dir) |
| 363 | if err != nil { |
| 364 | t.Fatal(err) |
| 365 | } |
| 366 | var names []string |
| 367 | for _, e := range list { |
| 368 | names = append(names, e.Name()) |
| 369 | } |
| 370 | return names |
| 371 | } |
| 372 | |
| 373 | // TestEveryDerivationGlobal holds the globals agree compares to the ones |
| 374 | // bin/valley declares for its derivation, so a global added there is one |
| 375 | // these tests compare. |
| 376 | func TestEveryDerivationGlobal(t *testing.T) { |
| 377 | r := newRig(t) |
| 378 | script, err := os.ReadFile(r.script) |
| 379 | if err != nil { |
| 380 | t.Fatal(err) |
| 381 | } |
| 382 | declared := []string{"POLICY_LAYER"} |
| 383 | for _, m := range regexp.MustCompile(`(?m)^(?:declare -A )?((?:DERIVED|CHECK)_[A-Z_]+)=`).FindAllSubmatch(script, -1) { |
| 384 | declared = append(declared, string(m[1])) |
| 385 | } |
| 386 | var compared []string |
| 387 | for _, g := range derivation { |
| 388 | compared = append(compared, g.name) |
| 389 | } |
| 390 | if !sameSet(declared, compared) { |
| 391 | t.Errorf("bin/valley declares %q, and the tests compare %q", sortedSet(declared), sortedSet(compared)) |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | // TestKnownDivergences records each place bin/valley's deriver is wrong |
| 396 | // (bug bd-11e0e4d) and the Go deriver is not: what each one answers. When |
| 397 | // bin/valley's answer changes, so must this test. |
| 398 | func TestKnownDivergences(t *testing.T) { |
| 399 | r := newRig(t) |
| 400 | floor := r.glob(t, "examples/policy/deriver/[ft]*.cue") |
| 401 | project := []string{r.path("examples/policy/deriver/project.cue")} |
| 402 | rp := newRepo(t, r) |
| 403 | seed := tree{"docs/kept.md": file("seed\n"), "Makefile": file("seed\n")} |
| 404 | base := rp.commit("", seed) |
| 405 | with := func(path string) string { |
| 406 | files := tree{path: file("added\n")} |
| 407 | for p, e := range seed { |
| 408 | files[p] = e |
| 409 | } |
| 410 | return rp.commit(base, files) |
| 411 | } |
| 412 | bash := func(t *testing.T, l layers, head string) (*vars, error) { |
| 413 | t.Helper() |
| 414 | return r.valley(t, rp.dir, r.schema, l, base, head) |
| 415 | } |
| 416 | gos := func(t *testing.T, l layers, head string) *Result { |
| 417 | t.Helper() |
| 418 | m, err := r.read(l) |
| 419 | if err != nil { |
| 420 | t.Fatalf("the Go deriver cannot read the policy: %v", err) |
| 421 | } |
| 422 | res, err := r.derive(m, rp.dir, base, head) |
| 423 | if err != nil { |
| 424 | t.Fatalf("the Go deriver refused: %v", err) |
| 425 | } |
| 426 | return res |
| 427 | } |
| 428 | requires := func(t *testing.T, who string, got, want []string) { |
| 429 | t.Helper() |
| 430 | if !sameSet(got, want) { |
| 431 | t.Errorf("%s requires %q, and this test records %q", who, got, want) |
| 432 | } |
| 433 | } |
| 434 | bashNames := func(v *vars) []string { |
| 435 | var out []string |
| 436 | for name := range v.maps["DERIVED_REQUIRED"] { |
| 437 | out = append(out, name) |
| 438 | } |
| 439 | return out |
| 440 | } |
| 441 | |
| 442 | // diff_paths prints each path on a line of its own, so a path holding a |
| 443 | // newline is read as two. src/a<newline>b.rs matches the flat and deep |
| 444 | // classes whole; its two halves match no class. |
| 445 | t.Run("a newline in a path", func(t *testing.T) { |
| 446 | l := newLayers(t, floor, project, nil) |
| 447 | head := with("src/a\nb.rs") |
| 448 | rep, err := bash(t, l, head) |
| 449 | if err != nil { |
| 450 | t.Fatal(err) |
| 451 | } |
| 452 | if paths, uncovered := rep.lists["DERIVED_PATHS"], rep.lists["DERIVED_UNCOVERED"]; len(paths) != 2 || !sameSet(uncovered, []string{"src/a", "b.rs"}) { |
| 453 | t.Errorf("bin/valley read %q, %q unclassified; this test records src/a and b.rs, both unclassified", paths, uncovered) |
| 454 | } |
| 455 | requires(t, "bin/valley", bashNames(rep), []string{"c-uncovered"}) |
| 456 | res := gos(t, l, head) |
| 457 | if !sameSet(res.Paths, []string{"src/a\nb.rs"}) || len(res.Unclassified) != 0 { |
| 458 | t.Errorf("the Go deriver read %q, %q unclassified", res.Paths, res.Unclassified) |
| 459 | } |
| 460 | requires(t, "the Go deriver", names(res), []string{"c-deep", "c-flat"}) |
| 461 | }) |
| 462 | |
| 463 | // The schema's cross-check reads the layers' composition, not `policy`, |
| 464 | // so a class added by refining `policy` may require a check nobody |
| 465 | // defines, and cue vet passes. bin/valley derives a change touching that |
| 466 | // class as requiring the check, which it has no definition of, so no |
| 467 | // runner, attribute or cost. The Go deriver refuses the policy. |
| 468 | t.Run("a class added at policy requires an undefined check", func(t *testing.T) { |
| 469 | l := newLayers(t, floor, project, map[string]string{"ghost.cue": "package verification\n" + |
| 470 | `policy: classes: sneaky: {paths: "sneak/**": true, requires: ghost: true}` + "\n"}) |
| 471 | if _, err := r.read(l); err == nil || !strings.Contains(err.Error(), "class sneaky requires check ghost, which the composed policy does not define") { |
| 472 | t.Errorf("the Go deriver read the policy: %v", err) |
| 473 | } |
| 474 | rep, err := bash(t, l, with("sneak/x")) |
| 475 | if err != nil { |
| 476 | t.Fatalf("bin/valley refused a change touching the class: %v", err) |
| 477 | } |
| 478 | requires(t, "bin/valley, for a change touching the class,", bashNames(rep), []string{"ghost"}) |
| 479 | if runner, ok := rep.maps["CHECK_RUNNER"]["ghost"]; ok { |
| 480 | t.Errorf("bin/valley defines ghost to run under %q; this test records no definition", runner) |
| 481 | } |
| 482 | rep, err = bash(t, l, with("docs/new.md")) |
| 483 | if err != nil { |
| 484 | t.Fatalf("bin/valley refused a change outside the class: %v", err) |
| 485 | } |
| 486 | requires(t, "bin/valley", bashNames(rep), []string{"c-docs", "c-tmpl"}) |
| 487 | }) |
| 488 | |
| 489 | // bin/valley renders the unclassified set's requirements as a class |
| 490 | // named unclassified, so a real class of that name shares them. Each |
| 491 | // requires the other's checks, and the class's requirement is pinned by |
| 492 | // probing the set. When both require one check, the render states it |
| 493 | // twice, and bin/valley refuses every derivation. |
| 494 | t.Run("a class named unclassified", func(t *testing.T) { |
| 495 | l := newLayers(t, floor, project, map[string]string{"odd.cue": "package verification\n" + |
| 496 | `project: classes: unclassified: {paths: "odd/**": true, requires: "c-notes": true}` + "\n"}) |
| 497 | odd, uncovered := with("odd/x"), with("Makefile.new") |
| 498 | |
| 499 | rep, err := bash(t, l, odd) |
| 500 | if err != nil { |
| 501 | t.Fatal(err) |
| 502 | } |
| 503 | requires(t, "bin/valley, for a path in the class,", bashNames(rep), []string{"c-notes", "c-uncovered"}) |
| 504 | if pin := rep.maps["DERIVED_PINNED"]["c-notes"]; pin != "default" { |
| 505 | t.Errorf("bin/valley pins the class's c-notes %s; this test records default", pin) |
| 506 | } |
| 507 | res := gos(t, l, odd) |
| 508 | requires(t, "the Go deriver, for a path in the class,", names(res), []string{"c-notes"}) |
| 509 | if q := res.Required[0]; q.Pin != composed.Mandatory || !sameSet(q.Classes, []string{"unclassified"}) || q.Unclassified { |
| 510 | t.Errorf("the Go deriver requires c-notes as %+v", q) |
| 511 | } |
| 512 | |
| 513 | rep, err = bash(t, l, uncovered) |
| 514 | if err != nil { |
| 515 | t.Fatal(err) |
| 516 | } |
| 517 | requires(t, "bin/valley, for an uncovered path,", bashNames(rep), []string{"c-notes", "c-uncovered"}) |
| 518 | res = gos(t, l, uncovered) |
| 519 | requires(t, "the Go deriver, for an uncovered path,", names(res), []string{"c-uncovered"}) |
| 520 | if len(res.Classes) != 0 || !res.Required[0].Unclassified { |
| 521 | t.Errorf("the Go deriver matched %q and required %+v", res.Classes, res.Required) |
| 522 | } |
| 523 | |
| 524 | shared := newLayers(t, floor, project, map[string]string{"odd.cue": "package verification\n" + |
| 525 | `project: classes: unclassified: {paths: "odd/**": true, requires: "c-uncovered": true}` + "\n"}) |
| 526 | if _, err := bash(t, shared, odd); err == nil || !strings.Contains(err.Error(), "rendered 'requires unclassified c-uncovered' twice") { |
| 527 | t.Errorf("bin/valley did not refuse a class sharing the unclassified set's check: %v", err) |
| 528 | } |
| 529 | res = gos(t, shared, odd) |
| 530 | requires(t, "the Go deriver, for a class sharing the set's check,", names(res), []string{"c-uncovered"}) |
| 531 | if q := res.Required[0]; !sameSet(q.Classes, []string{"unclassified"}) || q.Unclassified { |
| 532 | t.Errorf("the Go deriver requires c-uncovered as %+v", q) |
| 533 | } |
| 534 | }) |
| 535 | } |
| 536 | |
| 537 | // TestBothRefuse holds both derivers to refusing what neither may derive |
| 538 | // from: a policy cue-vet rejects, and a schema older than either deriver, |
| 539 | // with no cost or no carry modes to read. Read as a policy, either would |
| 540 | // be one whose checks cost nothing or whose classes carry everywhere. |
| 541 | func TestBothRefuse(t *testing.T) { |
| 542 | r := newRig(t) |
| 543 | rp := newRepo(t, r) |
| 544 | base := rp.commit("", tree{"src/one.rs": file("seed\n")}) |
| 545 | head := rp.commit(base, tree{"src/one.rs": file("edit\n"), "a/b": file("new\n")}) |
| 546 | refuse := func(t *testing.T, schema string, l layers) { |
| 547 | t.Helper() |
| 548 | if rep, err := r.valley(t, rp.dir, schema, l, base, head); err == nil { |
| 549 | t.Errorf("bin/valley derived %+v", rep) |
| 550 | } |
| 551 | if m, err := composed.Read(t.Context(), r.cue, schema, l.instance, l.project); err == nil { |
| 552 | t.Errorf("the Go deriver read %+v", m) |
| 553 | } |
| 554 | } |
| 555 | for _, f := range r.glob(t, "examples/policy/carry/rejected/*.cue") { |
| 556 | t.Run(filepath.Base(f), func(t *testing.T) { refuse(t, r.schema, newLayers(t, []string{f}, nil, nil)) }) |
| 557 | } |
| 558 | deriver := newLayers(t, r.glob(t, "examples/policy/deriver/[ft]*.cue"), []string{r.path("examples/policy/deriver/project.cue")}, nil) |
| 559 | body, err := os.ReadFile(r.schema) |
| 560 | if err != nil { |
| 561 | t.Fatal(err) |
| 562 | } |
| 563 | for name, line := range map[string]string{"costless": "\tcost: *\"quick\" | \"slow\"\n", "modeless": "\n_mode: "} { |
| 564 | t.Run(name, func(t *testing.T) { |
| 565 | at := bytes.Index(body, []byte(line)) |
| 566 | if at < 0 { |
| 567 | t.Fatalf("the schema has no %q, so this case proves nothing", line) |
| 568 | } |
| 569 | end := at + 1 + bytes.IndexByte(body[at+1:], '\n') |
| 570 | older := filepath.Join(t.TempDir(), "verification.cue") |
| 571 | if err := os.WriteFile(older, append(append([]byte{}, body[:at+1]...), body[end+1:]...), 0o644); err != nil { |
| 572 | t.Fatal(err) |
| 573 | } |
| 574 | refuse(t, older, deriver) |
| 575 | }) |
| 576 | } |
| 577 | } |
| 578 | |
| 579 | // TestGlobsAgree holds Match to bin/valley's glob_ere, run by bash in the |
| 580 | // C locale that derive_required derives in, over every glob the fixture |
| 581 | // policies name, globs drawn from the characters a glob or a regular |
| 582 | // expression treats specially, and paths drawn for each. |
| 583 | func TestGlobsAgree(t *testing.T) { |
| 584 | r := newRig(t) |
| 585 | rng := rand.New(rand.NewPCG(20261021, 1000)) |
| 586 | globs := map[string]bool{"docs/": true, "docs//": true, "": true, "**": true, "a**b": true, "**/**/x": true} |
| 587 | for _, f := range fixtures(t, r) { |
| 588 | m, err := r.read(newLayers(t, f.instance, f.project, nil)) |
| 589 | if err != nil { |
| 590 | t.Fatal(err) |
| 591 | } |
| 592 | for _, c := range m.Classes { |
| 593 | for _, g := range c.Paths { |
| 594 | globs[g] = true |
| 595 | } |
| 596 | } |
| 597 | } |
| 598 | pieces := []string{"a", "b", ".", "*", "?", "/", "**", "\\", "(", ")", "[", "]", "{", "}", "+", "^", "$", "|", "é", " ", "x"} |
| 599 | for range 150 { |
| 600 | var g strings.Builder |
| 601 | for range 1 + rng.IntN(6) { |
| 602 | g.WriteString(pieces[rng.IntN(len(pieces))]) |
| 603 | } |
| 604 | globs[g.String()] = true |
| 605 | } |
| 606 | sorted := make([]string, 0, len(globs)) |
| 607 | for g := range globs { |
| 608 | sorted = append(sorted, g) |
| 609 | } |
| 610 | sort.Strings(sorted) |
| 611 | |
| 612 | chars := []string{"a", "b", "x", ".", "/", "é", "\xff", "\n", " ", "*", "?", "\\", "md", "("} |
| 613 | type pair struct{ glob, path string } |
| 614 | var pairs []pair |
| 615 | var input bytes.Buffer |
| 616 | var want strings.Builder |
| 617 | for _, g := range sorted { |
| 618 | fmt.Fprintf(&input, "G\x00%s\x00", g) |
| 619 | paths := map[string]bool{} |
| 620 | for range 8 { |
| 621 | paths[instance(g, rng)] = true |
| 622 | } |
| 623 | for range 24 { |
| 624 | var p strings.Builder |
| 625 | for range rng.IntN(9) { |
| 626 | p.WriteString(chars[rng.IntN(len(chars))]) |
| 627 | } |
| 628 | paths[p.String()] = true |
| 629 | } |
| 630 | for _, p := range sortedKeys(paths) { |
| 631 | fmt.Fprintf(&input, "P\x00%s\x00", p) |
| 632 | pairs = append(pairs, pair{g, p}) |
| 633 | if Match(g, p) { |
| 634 | want.WriteByte('0') |
| 635 | } else { |
| 636 | want.WriteByte('1') |
| 637 | } |
| 638 | } |
| 639 | } |
| 640 | program := r.functions(t, "segment_ere", "glob_ere") + ` |
| 641 | while IFS= read -r -d '' kind && IFS= read -r -d '' value; do |
| 642 | case "$kind" in |
| 643 | G) ere="$(glob_ere "$value")" ;; |
| 644 | P) if [[ $value =~ $ere ]]; then printf 0; else printf '%d' "$?"; fi ;; |
| 645 | esac |
| 646 | done |
| 647 | ` |
| 648 | got := r.bash(t, program, input.Bytes()) |
| 649 | if len(got) != len(pairs) { |
| 650 | t.Fatalf("glob_ere answered %d pairs of %d", len(got), len(pairs)) |
| 651 | } |
| 652 | failed := 0 |
| 653 | for i, p := range pairs { |
| 654 | if got[i] == want.String()[i] { |
| 655 | continue |
| 656 | } |
| 657 | if failed++; failed <= 10 { |
| 658 | 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]) |
| 659 | } |
| 660 | } |
| 661 | t.Logf("%d globs, %d pairs, %d disagree", len(sorted), len(pairs), failed) |
| 662 | } |
| 663 | |
| 664 | // TestDiffReadersAgree holds Changed to bin/valley's diff_paths over the |
| 665 | // output git diff -z --name-status could give, and over every cut of some |
| 666 | // of it. Each must read the same paths in the same order, or both must |
| 667 | // refuse. diff_paths writes a path on a line of its own, so where a path |
| 668 | // holds a newline, its lines are the path split at each, and that is the |
| 669 | // divergence this records. Changed also refuses two records git never |
| 670 | // writes, which diff_paths reads: an unknown status, and an empty path. |
| 671 | func TestDiffReadersAgree(t *testing.T) { |
| 672 | r := newRig(t) |
| 673 | rng := rand.New(rand.NewPCG(20261021, 2000)) |
| 674 | statuses := []string{"A", "M", "D", "T", "R100", "R075", "C050"} |
| 675 | chars := []string{"a", "b/", "x.md", "é", "\xff", " ", "\t", "*", "\\", "-"} |
| 676 | pathOf := func(newline bool) string { |
| 677 | var p strings.Builder |
| 678 | for range 1 + rng.IntN(5) { |
| 679 | p.WriteString(chars[rng.IntN(len(chars))]) |
| 680 | } |
| 681 | if newline { |
| 682 | p.WriteString("\nmore") |
| 683 | } |
| 684 | return p.String() |
| 685 | } |
| 686 | var streams [][]byte |
| 687 | for n := range 200 { |
| 688 | var s bytes.Buffer |
| 689 | for range 1 + rng.IntN(4) { |
| 690 | status := statuses[rng.IntN(len(statuses))] |
| 691 | fmt.Fprintf(&s, "%s\x00%s\x00", status, pathOf(n%10 == 0)) |
| 692 | if status[0] == 'R' || status[0] == 'C' { |
| 693 | fmt.Fprintf(&s, "%s\x00", pathOf(false)) |
| 694 | } |
| 695 | } |
| 696 | streams = append(streams, s.Bytes()) |
| 697 | } |
| 698 | for _, s := range streams[:6] { |
| 699 | for cut := range len(s) { |
| 700 | streams = append(streams, s[:cut]) |
| 701 | } |
| 702 | } |
| 703 | unwritten := [][]byte{[]byte("Z\x00a\x00"), []byte("M\x00\x00")} |
| 704 | streams = append(streams, unwritten...) |
| 705 | |
| 706 | dir := t.TempDir() |
| 707 | for i, s := range streams { |
| 708 | if err := os.WriteFile(filepath.Join(dir, fmt.Sprintf("%05d.in", i)), s, 0o644); err != nil { |
| 709 | t.Fatal(err) |
| 710 | } |
| 711 | } |
| 712 | program := r.functions(t, "diff_paths") + ` |
| 713 | for f in "$1"/*.in; do |
| 714 | if diff_paths < "$f" > "${f%.in}.out"; then echo ok; else echo refused; fi |
| 715 | done |
| 716 | ` |
| 717 | verdicts := strings.Fields(r.bash(t, program, nil, dir)) |
| 718 | if len(verdicts) != len(streams) { |
| 719 | t.Fatalf("diff_paths read %d streams of %d", len(verdicts), len(streams)) |
| 720 | } |
| 721 | agreed, divergent := 0, 0 |
| 722 | for i, s := range streams { |
| 723 | paths, err := Changed(s) |
| 724 | out, rerr := os.ReadFile(filepath.Join(dir, fmt.Sprintf("%05d.out", i))) |
| 725 | if rerr != nil { |
| 726 | t.Fatal(rerr) |
| 727 | } |
| 728 | isUnwritten := i >= len(streams)-len(unwritten) |
| 729 | switch { |
| 730 | case isUnwritten: |
| 731 | if err == nil || verdicts[i] != "ok" { |
| 732 | t.Errorf("stream %q: Changed %v, diff_paths %s; this test records a refusal and a reading", s, err, verdicts[i]) |
| 733 | } |
| 734 | divergent++ |
| 735 | case (err == nil) != (verdicts[i] == "ok"): |
| 736 | t.Errorf("stream %q: Changed says %v, diff_paths %s", s, err, verdicts[i]) |
| 737 | case err != nil: |
| 738 | agreed++ |
| 739 | default: |
| 740 | lines := string(out) |
| 741 | want := "" |
| 742 | if len(paths) > 0 { |
| 743 | want = strings.Join(paths, "\n") + "\n" |
| 744 | } |
| 745 | if lines != want { |
| 746 | t.Errorf("stream %q: Changed read %q, diff_paths wrote %q", s, paths, lines) |
| 747 | } |
| 748 | if strings.Count(want, "\n") > len(paths) { |
| 749 | divergent++ |
| 750 | } else { |
| 751 | agreed++ |
| 752 | } |
| 753 | } |
| 754 | } |
| 755 | t.Logf("%d streams agree; %d hold a newline path or a record git never writes", agreed, divergent) |
| 756 | } |
| 757 | |
| 758 | // functions are bin/valley's definitions of the named functions, to be run |
| 759 | // on their own. |
| 760 | func (r *rig) functions(t *testing.T, names ...string) string { |
| 761 | t.Helper() |
| 762 | script, err := os.ReadFile(r.script) |
| 763 | if err != nil { |
| 764 | t.Fatal(err) |
| 765 | } |
| 766 | var out strings.Builder |
| 767 | for _, name := range names { |
| 768 | start := bytes.Index(script, []byte("\n"+name+"() {\n")) |
| 769 | if start < 0 { |
| 770 | t.Fatalf("bin/valley defines no %s", name) |
| 771 | } |
| 772 | body := script[start+1:] |
| 773 | end := bytes.Index(body, []byte("\n}\n")) |
| 774 | out.Write(body[:end+3]) |
| 775 | } |
| 776 | return out.String() |
| 777 | } |
| 778 | |
| 779 | // bash runs a program with stdin, in the rig's environment, and returns |
| 780 | // what it printed. |
| 781 | func (r *rig) bash(t *testing.T, program string, stdin []byte, args ...string) string { |
| 782 | t.Helper() |
| 783 | cmd := exec.Command("bash", append([]string{"-c", program, "bash"}, args...)...) |
| 784 | cmd.Env = r.env |
| 785 | cmd.Stdin = bytes.NewReader(stdin) |
| 786 | var stdout, stderr bytes.Buffer |
| 787 | cmd.Stdout, cmd.Stderr = &stdout, &stderr |
| 788 | if err := cmd.Run(); err != nil { |
| 789 | t.Fatalf("bash: %v\n%s", err, stderr.String()) |
| 790 | } |
| 791 | return stdout.String() |
| 792 | } |
| 793 | |
| 794 | func sortedKeys(set map[string]bool) []string { |
| 795 | out := make([]string, 0, len(set)) |
| 796 | for k := range set { |
| 797 | out = append(out, k) |
| 798 | } |
| 799 | sort.Strings(out) |
| 800 | return out |
| 801 | } |
| 802 | |
| 803 | // instance is a path made from a glob, which mostly matches it: each `**` |
| 804 | // segment made none, one or two segments, each `*` some bytes, and each `?` |
| 805 | // one character. That character is two bytes when it is é, so `?` meets a |
| 806 | // character that is not one byte. A `*` or a `?` is sometimes made a `/`, |
| 807 | // which neither may match. |
| 808 | func instance(glob string, rng *rand.Rand) string { |
| 809 | segs := strings.Split(glob, "/") |
| 810 | if segs[len(segs)-1] == "" { |
| 811 | segs = segs[:len(segs)-1] |
| 812 | } |
| 813 | stars := []string{"", "x", "x.y", "ü", "\xff", " ", "*", "q.md", "", "x", "x/y"} |
| 814 | ones := []string{"q", "é", "\xfe", "?", "q", "/"} |
| 815 | var out []string |
| 816 | for _, seg := range segs { |
| 817 | if seg == "**" { |
| 818 | out = append(out, []string{"d", "e.md", "ü"}[:rng.IntN(3)]...) |
| 819 | continue |
| 820 | } |
| 821 | var s strings.Builder |
| 822 | for i := 0; i < len(seg); i++ { |
| 823 | switch seg[i] { |
| 824 | case '*': |
| 825 | s.WriteString(stars[rng.IntN(len(stars))]) |
| 826 | case '?': |
| 827 | s.WriteString(ones[rng.IntN(len(ones))]) |
| 828 | default: |
| 829 | s.WriteByte(seg[i]) |
| 830 | } |
| 831 | } |
| 832 | out = append(out, s.String()) |
| 833 | } |
| 834 | return strings.Join(out, "/") |
| 835 | } |
| 836 | |
| 837 | // awkward are names chosen for what a reader of paths might get wrong. |
| 838 | var awkward = []string{ |
| 839 | "README.md", "a b.md", "-dash.md", "naïve.md", "caf\xe9.md", "tab\there.md", |
| 840 | "quote\"d.md", "back\\slash.md", "star*.md", "q?.md", "[br].md", "{x}.md", |
| 841 | "deep/a/b/c/d/e.txt", ".hidden", "dir.md/inner", "\xff\xfe/x", "research/notes.txt", |
| 842 | "src/x.rs.bak", "docs", "bin/valley", "flake.nix", "nix/checks/derive-unit.sh", |
| 843 | } |
| 844 | |
| 845 | // validPath reports whether git would hold p as a path. |
| 846 | func validPath(p string) bool { |
| 847 | if p == "" || strings.ContainsAny(p, "\x00\n") { |
| 848 | return false |
| 849 | } |
| 850 | for _, seg := range strings.Split(p, "/") { |
| 851 | if seg == "" || seg == "." || seg == ".." || strings.EqualFold(seg, ".git") { |
| 852 | return false |
| 853 | } |
| 854 | } |
| 855 | return true |
| 856 | } |
| 857 | |
| 858 | // pathPool is what a fixture's cases are drawn from: instances of every |
| 859 | // glob the policy names, near misses of each, and the awkward names. |
| 860 | func pathPool(m *composed.Model, rng *rand.Rand) []string { |
| 861 | set := map[string]bool{} |
| 862 | add := func(p string) { |
| 863 | if validPath(p) { |
| 864 | set[p] = true |
| 865 | } |
| 866 | } |
| 867 | classes := make([]string, 0, len(m.Classes)) |
| 868 | for name := range m.Classes { |
| 869 | classes = append(classes, name) |
| 870 | } |
| 871 | sort.Strings(classes) |
| 872 | for _, name := range classes { |
| 873 | for _, g := range m.Classes[name].Paths { |
| 874 | for range 3 { |
| 875 | p := instance(g, rng) |
| 876 | add(p) |
| 877 | add("zz/" + p) |
| 878 | add(p + "x") |
| 879 | if i := strings.LastIndexByte(p, '/'); i > 0 { |
| 880 | add(p[:i] + "/zz" + p[i:]) |
| 881 | } |
| 882 | } |
| 883 | } |
| 884 | } |
| 885 | for _, p := range awkward { |
| 886 | add(p) |
| 887 | } |
| 888 | return sortedKeys(set) |
| 889 | } |
| 890 | |
| 891 | // fits reports whether p can join t: no path of t is a directory of p's, |
| 892 | // and p is no directory of a path of t. |
| 893 | func fits(t tree, p string) bool { |
| 894 | if _, ok := t[p]; ok { |
| 895 | return false |
| 896 | } |
| 897 | for q := range t { |
| 898 | if strings.HasPrefix(p, q+"/") || strings.HasPrefix(q, p+"/") { |
| 899 | return false |
| 900 | } |
| 901 | } |
| 902 | return true |
| 903 | } |
| 904 | |
| 905 | // baseTree is about half the pool. |
| 906 | func baseTree(rng *rand.Rand, pool []string) tree { |
| 907 | t := tree{} |
| 908 | for _, p := range pool { |
| 909 | if rng.IntN(2) == 0 && fits(t, p) { |
| 910 | t[p] = file("base " + p + "\n") |
| 911 | } |
| 912 | } |
| 913 | return t |
| 914 | } |
| 915 | |
| 916 | // change is base with one to six changes made to it. |
| 917 | func change(rng *rand.Rand, base tree, pool []string) tree { |
| 918 | t := tree{} |
| 919 | for p, e := range base { |
| 920 | t[p] = e |
| 921 | } |
| 922 | existing := func() string { |
| 923 | paths := make([]string, 0, len(t)) |
| 924 | for p := range t { |
| 925 | paths = append(paths, p) |
| 926 | } |
| 927 | sort.Strings(paths) |
| 928 | if len(paths) == 0 { |
| 929 | return "" |
| 930 | } |
| 931 | return paths[rng.IntN(len(paths))] |
| 932 | } |
| 933 | fresh := func() string { |
| 934 | for range 20 { |
| 935 | if p := pool[rng.IntN(len(pool))]; fits(t, p) { |
| 936 | return p |
| 937 | } |
| 938 | } |
| 939 | return "" |
| 940 | } |
| 941 | for n := range 1 + rng.IntN(6) { |
| 942 | switch rng.IntN(5) { |
| 943 | case 0: // modify |
| 944 | if p := existing(); p != "" { |
| 945 | t[p] = file(fmt.Sprintf("edit %d of %s\n", n, p)) |
| 946 | } |
| 947 | case 1: // delete |
| 948 | if p := existing(); p != "" { |
| 949 | delete(t, p) |
| 950 | } |
| 951 | case 2: // add |
| 952 | if p := fresh(); p != "" { |
| 953 | t[p] = file("added " + p + "\n") |
| 954 | } |
| 955 | case 3: // rename |
| 956 | if from := existing(); from != "" { |
| 957 | e := t[from] |
| 958 | delete(t, from) |
| 959 | if to := fresh(); to != "" { |
| 960 | t[to] = e |
| 961 | } else { |
| 962 | t[from] = e |
| 963 | } |
| 964 | } |
| 965 | case 4: // turn into a symbolic link |
| 966 | if p := existing(); p != "" { |
| 967 | t[p] = entry{mode: "120000", content: "target-of-" + p} |
| 968 | } |
| 969 | } |
| 970 | } |
| 971 | return t |
| 972 | } |