| 1 | package derive |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "path/filepath" |
| 10 | "regexp" |
| 11 | "sort" |
| 12 | "strconv" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | |
| 16 | "the-valley/composed" |
| 17 | ) |
| 18 | |
| 19 | // The tests beside this file hold the Go deriver to bin/valley's, which is |
| 20 | // the deriver every caller runs. This file is what they share: the |
| 21 | // rig that runs both, the scratch repositories they run over, and the |
| 22 | // reading of bin/valley's report. |
| 23 | // |
| 24 | // Both derivers run in the C locale. bin/valley matches a glob with bash's |
| 25 | // regular expressions, which read bytes in that locale, and this package |
| 26 | // matches bytes in every locale. bin/valley under another locale is not |
| 27 | // held here. |
| 28 | |
| 29 | // rig is what both derivers need: bin/valley, the schema, cue, and an |
| 30 | // environment of the test's own, with no configuration of the person |
| 31 | // running it. |
| 32 | type rig struct { |
| 33 | root, script, schema, cue string |
| 34 | env []string |
| 35 | } |
| 36 | |
| 37 | func newRig(t *testing.T) *rig { |
| 38 | t.Helper() |
| 39 | for _, tool := range []string{"bash", "git", "cue"} { |
| 40 | if _, err := exec.LookPath(tool); err != nil { |
| 41 | if os.Getenv("VALLEY_TEST_TOOLS") == "required" { |
| 42 | t.Fatalf("no %s on PATH, and VALLEY_TEST_TOOLS=required", tool) |
| 43 | } |
| 44 | t.Skipf("no %s to run bin/valley's deriver with; the derive-unit check provides one", tool) |
| 45 | } |
| 46 | } |
| 47 | root, err := filepath.Abs("..") |
| 48 | if err != nil { |
| 49 | t.Fatal(err) |
| 50 | } |
| 51 | cue, _ := exec.LookPath("cue") |
| 52 | r := &rig{ |
| 53 | root: root, |
| 54 | script: filepath.Join(root, "bin", "valley"), |
| 55 | schema: filepath.Join(root, "schema", "verification.cue"), |
| 56 | cue: cue, |
| 57 | } |
| 58 | for _, f := range []string{r.script, r.schema} { |
| 59 | if _, err := os.Stat(f); err != nil { |
| 60 | t.Fatalf("the tests read %s, and it is not there: %v", f, err) |
| 61 | } |
| 62 | } |
| 63 | r.env = []string{ |
| 64 | "PATH=" + os.Getenv("PATH"), |
| 65 | "HOME=" + t.TempDir(), |
| 66 | "TMPDIR=" + os.TempDir(), |
| 67 | "LC_ALL=C", |
| 68 | "GIT_CONFIG_NOSYSTEM=1", |
| 69 | "GIT_AUTHOR_NAME=derive-test", "GIT_AUTHOR_EMAIL=derive-test@localhost", |
| 70 | "GIT_COMMITTER_NAME=derive-test", "GIT_COMMITTER_EMAIL=derive-test@localhost", |
| 71 | "GIT_AUTHOR_DATE=2026-10-21T00:00:00Z", "GIT_COMMITTER_DATE=2026-10-21T00:00:00Z", |
| 72 | } |
| 73 | return r |
| 74 | } |
| 75 | |
| 76 | // path is a file of the repository the tests run in. |
| 77 | func (r *rig) path(rel string) string { return filepath.Join(r.root, rel) } |
| 78 | |
| 79 | // glob is every file of the repository a pattern names, sorted. |
| 80 | func (r *rig) glob(t *testing.T, pattern string) []string { |
| 81 | t.Helper() |
| 82 | found, err := filepath.Glob(r.path(pattern)) |
| 83 | if err != nil || len(found) == 0 { |
| 84 | t.Fatalf("no file matches %s", pattern) |
| 85 | } |
| 86 | return found |
| 87 | } |
| 88 | |
| 89 | // layers is a policy on disk: the floor's directory and the project |
| 90 | // layer's, as both derivers are given them. |
| 91 | type layers struct{ instance, project string } |
| 92 | |
| 93 | // newLayers copies the floor's documents and the project's into |
| 94 | // directories of their own, and writes extra, by name, beside the |
| 95 | // project's. A project with no documents is one that adds nothing. |
| 96 | func newLayers(t *testing.T, instance, project []string, extra map[string]string) layers { |
| 97 | t.Helper() |
| 98 | dir := t.TempDir() |
| 99 | l := layers{instance: filepath.Join(dir, "instance"), project: filepath.Join(dir, "project")} |
| 100 | for _, d := range []string{l.instance, l.project} { |
| 101 | if err := os.Mkdir(d, 0o755); err != nil { |
| 102 | t.Fatal(err) |
| 103 | } |
| 104 | } |
| 105 | copyTo := func(dest string, files []string) { |
| 106 | for _, f := range files { |
| 107 | body, err := os.ReadFile(f) |
| 108 | if err != nil { |
| 109 | t.Fatal(err) |
| 110 | } |
| 111 | if err := os.WriteFile(filepath.Join(dest, filepath.Base(f)), body, 0o644); err != nil { |
| 112 | t.Fatal(err) |
| 113 | } |
| 114 | } |
| 115 | } |
| 116 | copyTo(l.instance, instance) |
| 117 | copyTo(l.project, project) |
| 118 | if len(project) == 0 && len(extra) == 0 { |
| 119 | extra = map[string]string{"adds-nothing.cue": "package verification\n"} |
| 120 | } |
| 121 | for name, body := range extra { |
| 122 | if err := os.WriteFile(filepath.Join(l.project, name), []byte(body), 0o644); err != nil { |
| 123 | t.Fatal(err) |
| 124 | } |
| 125 | } |
| 126 | return l |
| 127 | } |
| 128 | |
| 129 | // read is composed.Read of the layers under the rig's schema. |
| 130 | func (r *rig) read(l layers) (*composed.Model, error) { |
| 131 | return composed.Read(context.Background(), r.cue, r.schema, l.instance, l.project) |
| 132 | } |
| 133 | |
| 134 | // valley runs bin/valley's `checks` over two commits of the repository at |
| 135 | // dir and reads its report. A run that fails returns what it said, and must |
| 136 | // print nothing on stdout. env is added to the rig's environment. |
| 137 | func (r *rig) valley(t *testing.T, dir, schema string, l layers, base, head string, env ...string) (*report, error) { |
| 138 | t.Helper() |
| 139 | cmd := exec.Command("bash", r.script, "checks", "--schema", schema, |
| 140 | "--instance", l.instance, "--project", l.project, base, head) |
| 141 | cmd.Dir = dir |
| 142 | cmd.Env = append(append([]string{}, r.env...), env...) |
| 143 | var stdout, stderr bytes.Buffer |
| 144 | cmd.Stdout, cmd.Stderr = &stdout, &stderr |
| 145 | if err := cmd.Run(); err != nil { |
| 146 | if stdout.Len() > 0 { |
| 147 | t.Errorf("bin/valley failed and printed to stdout:\n%s", stdout.String()) |
| 148 | } |
| 149 | return nil, fmt.Errorf("%w: %s", err, strings.TrimSpace(stderr.String())) |
| 150 | } |
| 151 | rep, err := parseReport(stdout.String()) |
| 152 | if err != nil { |
| 153 | t.Fatalf("bin/valley's report does not read: %v\n%s", err, stdout.String()) |
| 154 | } |
| 155 | return rep, nil |
| 156 | } |
| 157 | |
| 158 | // derive is the Go deriver over the same two commits: Diff, then Derive. |
| 159 | func (r *rig) derive(m *composed.Model, dir, base, head string, env ...string) (*Result, error) { |
| 160 | paths, err := Diff(context.Background(), dir, append(append([]string{}, r.env...), env...), base, head) |
| 161 | if err != nil { |
| 162 | return nil, err |
| 163 | } |
| 164 | return Derive(m, paths) |
| 165 | } |
| 166 | |
| 167 | // report is what bin/valley's `checks` printed, as far as it says what a |
| 168 | // change requires. |
| 169 | type report struct { |
| 170 | paths int // the count on the header line |
| 171 | classes []string // classes matched, unclassified included |
| 172 | carry string // the carry mode |
| 173 | required map[string]reportRow // check -> its row |
| 174 | unclassified []string // the paths listed as matching no class |
| 175 | } |
| 176 | |
| 177 | type reportRow struct { |
| 178 | pin string |
| 179 | classes []string // the classes requiring it, unclassified included |
| 180 | cost string // from the quick: and slow: lines |
| 181 | } |
| 182 | |
| 183 | var reportHeader = regexp.MustCompile(`^[0-9a-f]+\.\.[0-9a-f]+: ([0-9]+) changed path\(s\)$`) |
| 184 | |
| 185 | func parseReport(out string) (*report, error) { |
| 186 | rep := &report{required: map[string]reportRow{}} |
| 187 | lines := strings.Split(strings.TrimSuffix(out, "\n"), "\n") |
| 188 | m := reportHeader.FindStringSubmatch(lines[0]) |
| 189 | if m == nil { |
| 190 | return nil, fmt.Errorf("no header line") |
| 191 | } |
| 192 | rep.paths, _ = strconv.Atoi(m[1]) |
| 193 | splitList := func(s string) []string { |
| 194 | if s == "none" { |
| 195 | return nil |
| 196 | } |
| 197 | return strings.Split(s, ", ") |
| 198 | } |
| 199 | for i := 1; i < len(lines); i++ { |
| 200 | line := lines[i] |
| 201 | switch { |
| 202 | case strings.HasPrefix(line, "classes matched: "): |
| 203 | rep.classes = splitList(strings.TrimPrefix(line, "classes matched: ")) |
| 204 | case strings.HasPrefix(line, "carry mode: "): |
| 205 | rep.carry = strings.TrimPrefix(line, "carry mode: ") |
| 206 | case line == "required checks:": |
| 207 | for i++; i < len(lines) && lines[i] != ""; i++ { |
| 208 | f := strings.Fields(lines[i]) |
| 209 | if len(f) < 3 { |
| 210 | return nil, fmt.Errorf("a required-check row %q", lines[i]) |
| 211 | } |
| 212 | rep.required[f[0]] = reportRow{pin: f[1], classes: splitList(strings.Join(f[2:], " "))} |
| 213 | } |
| 214 | case strings.HasPrefix(line, "unclassified: "): |
| 215 | for i++; i < len(lines) && lines[i] != ""; i++ { |
| 216 | if lines[i] == " the policy requires nothing of them — it is behind the tree" { |
| 217 | continue |
| 218 | } |
| 219 | rep.unclassified = append(rep.unclassified, strings.TrimPrefix(lines[i], " ")) |
| 220 | } |
| 221 | case strings.HasPrefix(line, "quick: "), strings.HasPrefix(line, "slow: "): |
| 222 | cost, list, _ := strings.Cut(line, ": ") |
| 223 | for _, name := range splitList(list) { |
| 224 | row, ok := rep.required[name] |
| 225 | if !ok { |
| 226 | return nil, fmt.Errorf("%s lists %s, which no row requires", cost, name) |
| 227 | } |
| 228 | row.cost = cost |
| 229 | rep.required[name] = row |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | if rep.carry == "" { |
| 234 | return nil, fmt.Errorf("no carry mode") |
| 235 | } |
| 236 | return rep, nil |
| 237 | } |
| 238 | |
| 239 | // agree reports every way the Go deriver's answer differs from bin/valley's |
| 240 | // report. bin/valley names the unclassified set as a class called |
| 241 | // unclassified, so that is how the Go answer is read here. |
| 242 | func agree(rep *report, res *Result) []string { |
| 243 | var diffs []string |
| 244 | differ := func(what string, bash, gos any) { |
| 245 | diffs = append(diffs, fmt.Sprintf("%s: bin/valley %q, Go %q", what, bash, gos)) |
| 246 | } |
| 247 | if rep.paths != len(res.Paths) { |
| 248 | differ("changed paths", strconv.Itoa(rep.paths), strconv.Itoa(len(res.Paths))) |
| 249 | } |
| 250 | classes := append([]string{}, res.Classes...) |
| 251 | if len(res.Unclassified) > 0 { |
| 252 | classes = append(classes, "unclassified") |
| 253 | } |
| 254 | if !sameSet(rep.classes, classes) { |
| 255 | differ("classes matched", rep.classes, classes) |
| 256 | } |
| 257 | if rep.carry != res.Carry { |
| 258 | differ("carry mode", rep.carry, res.Carry) |
| 259 | } |
| 260 | if !sameSet(rep.unclassified, res.Unclassified) { |
| 261 | differ("unclassified paths", rep.unclassified, res.Unclassified) |
| 262 | } |
| 263 | got := map[string]Required{} |
| 264 | for _, q := range res.Required { |
| 265 | got[q.Name] = q |
| 266 | } |
| 267 | for name, row := range rep.required { |
| 268 | q, ok := got[name] |
| 269 | if !ok { |
| 270 | differ("required "+name, "required", "not required") |
| 271 | continue |
| 272 | } |
| 273 | by := append([]string{}, q.Classes...) |
| 274 | if q.Unclassified { |
| 275 | by = append(by, "unclassified") |
| 276 | } |
| 277 | if !sameSet(row.classes, by) { |
| 278 | differ(name+"'s classes", row.classes, by) |
| 279 | } |
| 280 | if row.pin != string(q.Pin) { |
| 281 | differ(name+"'s pin", row.pin, string(q.Pin)) |
| 282 | } |
| 283 | if row.cost != q.Cost { |
| 284 | differ(name+"'s cost", row.cost, q.Cost) |
| 285 | } |
| 286 | } |
| 287 | for name := range got { |
| 288 | if _, ok := rep.required[name]; !ok { |
| 289 | differ("required "+name, "not required", "required") |
| 290 | } |
| 291 | } |
| 292 | sort.Strings(diffs) |
| 293 | return diffs |
| 294 | } |
| 295 | |
| 296 | func sameSet(a, b []string) bool { |
| 297 | a, b = sortedSet(a), sortedSet(b) |
| 298 | if len(a) != len(b) { |
| 299 | return false |
| 300 | } |
| 301 | for i := range a { |
| 302 | if a[i] != b[i] { |
| 303 | return false |
| 304 | } |
| 305 | } |
| 306 | return true |
| 307 | } |
| 308 | |
| 309 | // names are the required checks' names, sorted. |
| 310 | func names(res *Result) []string { |
| 311 | var out []string |
| 312 | for _, q := range res.Required { |
| 313 | out = append(out, q.Name) |
| 314 | } |
| 315 | return out |
| 316 | } |
| 317 | |
| 318 | // entry is one file of a scratch tree: its mode and its content, which |
| 319 | // for a symbolic link is its target. |
| 320 | type entry struct{ mode, content string } |
| 321 | |
| 322 | // tree is a scratch commit's files, by path. |
| 323 | type tree map[string]entry |
| 324 | |
| 325 | // repo is a scratch repository whose commits are written straight into |
| 326 | // its object store, so a path may hold any byte a git path may, whatever |
| 327 | // the file system makes of it. |
| 328 | type repo struct { |
| 329 | t *testing.T |
| 330 | dir string |
| 331 | env []string |
| 332 | blobs map[string]string |
| 333 | n int |
| 334 | } |
| 335 | |
| 336 | func newRepo(t *testing.T, r *rig) *repo { |
| 337 | t.Helper() |
| 338 | rp := &repo{t: t, dir: t.TempDir(), env: r.env, blobs: map[string]string{}} |
| 339 | rp.git(nil, "init", "--quiet", "--initial-branch=main") |
| 340 | return rp |
| 341 | } |
| 342 | |
| 343 | func (rp *repo) git(stdin []byte, args ...string) string { |
| 344 | rp.t.Helper() |
| 345 | return rp.gitEnv(nil, stdin, args...) |
| 346 | } |
| 347 | |
| 348 | func (rp *repo) gitEnv(env []string, stdin []byte, args ...string) string { |
| 349 | rp.t.Helper() |
| 350 | cmd := exec.Command("git", args...) |
| 351 | cmd.Dir = rp.dir |
| 352 | cmd.Env = append(append([]string{}, rp.env...), env...) |
| 353 | cmd.Stdin = bytes.NewReader(stdin) |
| 354 | var stdout, stderr bytes.Buffer |
| 355 | cmd.Stdout, cmd.Stderr = &stdout, &stderr |
| 356 | if err := cmd.Run(); err != nil { |
| 357 | rp.t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, stderr.String()) |
| 358 | } |
| 359 | return strings.TrimSpace(stdout.String()) |
| 360 | } |
| 361 | |
| 362 | // commit writes files as one commit on parent, which may be "", and |
| 363 | // returns it. |
| 364 | func (rp *repo) commit(parent string, files tree) string { |
| 365 | rp.t.Helper() |
| 366 | var info bytes.Buffer |
| 367 | paths := make([]string, 0, len(files)) |
| 368 | for p := range files { |
| 369 | paths = append(paths, p) |
| 370 | } |
| 371 | sort.Strings(paths) |
| 372 | for _, p := range paths { |
| 373 | e := files[p] |
| 374 | blob, ok := rp.blobs[e.content] |
| 375 | if !ok { |
| 376 | blob = rp.git([]byte(e.content), "hash-object", "-w", "--stdin") |
| 377 | rp.blobs[e.content] = blob |
| 378 | } |
| 379 | fmt.Fprintf(&info, "%s %s\t%s\x00", e.mode, blob, p) |
| 380 | } |
| 381 | rp.n++ |
| 382 | index := []string{"GIT_INDEX_FILE=" + filepath.Join(rp.dir, ".git", fmt.Sprintf("scratch-index-%d", rp.n))} |
| 383 | rp.gitEnv(index, info.Bytes(), "update-index", "--add", "-z", "--index-info") |
| 384 | tr := rp.gitEnv(index, nil, "write-tree") |
| 385 | args := []string{"commit-tree", tr, "-m", fmt.Sprintf("commit %d", rp.n)} |
| 386 | if parent != "" { |
| 387 | args = append(args, "-p", parent) |
| 388 | } |
| 389 | return rp.git(nil, args...) |
| 390 | } |
| 391 | |
| 392 | // file is a regular file holding content. |
| 393 | func file(content string) entry { return entry{mode: "100644", content: content} } |