gunk-dev/the-valley

compare_test.go

sourcec4c1671e1d82main's published tip history
19.7 KiB
1package main
2
3import (
4 "bytes"
5 "io"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "strconv"
10 "strings"
11 "testing"
12)
13
14// compareRepo is an origin and a clone of it, for compare's tests.
15type compareRepo struct {
16 t *testing.T
17 origin, work string
18}
19
20func newCompareRepo(t *testing.T) *compareRepo {
21 t.Helper()
22 dir := t.TempDir()
23 t.Setenv("HOME", dir)
24 t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))
25 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
26 t.Setenv("VALLEY_KNOWN_SIGNERS", "")
27 r := &compareRepo{t: t, origin: filepath.Join(dir, "origin.git"), work: filepath.Join(dir, "work")}
28 r.in(dir, "init", "--quiet", "--bare", "--initial-branch=main", r.origin)
29 r.in(dir, "clone", "--quiet", r.origin, r.work)
30 r.git("config", "user.name", "compare-test")
31 r.git("config", "user.email", "compare-test@localhost")
32 r.git("config", "valley.principal", "alice")
33 r.git("checkout", "--quiet", "-b", "main")
34 r.file("README", "base\n")
35 r.git("commit", "--quiet", "-m", "base")
36 r.git("push", "--quiet", "origin", "main")
37 t.Chdir(r.work)
38 return r
39}
40
41func (r *compareRepo) in(dir string, args ...string) string {
42 r.t.Helper()
43 cmd := exec.Command("git", args...)
44 cmd.Dir = dir
45 var stderr bytes.Buffer
46 cmd.Stderr = &stderr
47 out, err := cmd.Output()
48 if err != nil {
49 r.t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, stderr.String())
50 }
51 return strings.TrimSpace(string(out))
52}
53
54func (r *compareRepo) git(args ...string) string {
55 r.t.Helper()
56 return r.in(r.work, args...)
57}
58
59// file writes a file in the work tree and stages it.
60func (r *compareRepo) file(name, content string) {
61 r.t.Helper()
62 if err := os.WriteFile(filepath.Join(r.work, name), []byte(content), 0o644); err != nil {
63 r.t.Fatal(err)
64 }
65 r.git("add", name)
66}
67
68// valley runs a verb of valley and returns what it printed.
69func (r *compareRepo) valley(args ...string) string {
70 r.t.Helper()
71 var stdout, stderr bytes.Buffer
72 if code := run(args, &stdout, &stderr, os.Exit); code != 0 {
73 r.t.Fatalf("valley %s: %s", strings.Join(args, " "), stderr.String())
74 }
75 return stdout.String()
76}
77
78// runCompare sets a version against its approved one, as review does.
79func (r *compareRepo) runCompare(args ...string) (string, error) {
80 var out bytes.Buffer
81 err := runCompare(git{env: gitEnvironment(os.Environ()), stderr: io.Discard}, args, &out)
82 return out.String(), err
83}
84
85// moveMain adds a commit to main on origin, as a landing would, and
86// fetches it. It returns main's new tip.
87func (r *compareRepo) moveMain(name string) string {
88 r.git("checkout", "--quiet", "main")
89 r.file(name, name+"\n")
90 r.git("commit", "--quiet", "-m", "land "+name)
91 r.git("push", "--quiet", "origin", "main")
92 return r.git("rev-parse", "HEAD")
93}
94
95// rebaseOnto rebases a branch onto main and pushes it, and returns its
96// new head.
97func (r *compareRepo) rebaseOnto(branch string) string {
98 r.git("checkout", "--quiet", branch)
99 r.git("rebase", "--quiet", "main")
100 r.git("push", "--quiet", "--force", "origin", branch)
101 r.git("checkout", "--quiet", "main")
102 return r.git("rev-parse", branch)
103}
104
105// setRef points a ref on origin at an object, or deletes it for "".
106func (r *compareRepo) setRef(ref, oid string) {
107 if oid == "" {
108 r.in(r.origin, "update-ref", "-d", ref)
109 return
110 }
111 r.in(r.origin, "update-ref", ref, oid)
112}
113
114// outcomeRecord writes an outcome record on origin, as the integrator
115// writes one, and returns its blob.
116func (r *compareRepo) outcomeRecord(head, decision string) string {
117 cmd := exec.Command("git", "hash-object", "-w", "--stdin")
118 cmd.Dir = r.origin
119 cmd.Stdin = strings.NewReader(head + " " + r.git("rev-parse", "main") + " 0123456789abcdef " + decision + "\n")
120 out, err := cmd.Output()
121 if err != nil {
122 r.t.Fatal(err)
123 }
124 return strings.TrimSpace(string(out))
125}
126
127func (r *compareRepo) compare(id string, version int, head string) (kind, text string) {
128 r.t.Helper()
129 return r.compareWith(id, version, head)
130}
131
132func (r *compareRepo) compareVerbose(id string, version int, head string) (kind, text string) {
133 r.t.Helper()
134 return r.compareWith(id, version, head, "-v")
135}
136
137func (r *compareRepo) compareWith(id string, version int, head string, flags ...string) (kind, text string) {
138 r.t.Helper()
139 args := append(append([]string{}, flags...), "--tip", r.git("rev-parse", "origin/main"), id, strconv.Itoa(version), head)
140 out, err := r.runCompare(args...)
141 if err != nil {
142 r.t.Fatalf("compare %s: %s", strings.Join(args, " "), err)
143 }
144 kind, text, _ = strings.Cut(out, "\n")
145 return kind, text
146}
147
148// A request or an outcome under a branch's request name is evidence that
149// a head was approved only while nothing else maps to that name: no
150// version of another change, and no branch on origin that is not the
151// change's own. Under c-<change ID> it always is. An ambiguous name stops
152// the search: an older version is not compared instead.
153func TestTheApprovedVersionIsNamedUnambiguously(t *testing.T) {
154 r := newCompareRepo(t)
155 id := strings.Repeat("x", 32)
156 r.git("checkout", "--quiet", "-b", "a/b")
157 r.file("feature.txt", "feature\n")
158 r.git("commit", "--quiet", "-m", "add the feature")
159 r.git("push", "--quiet", "origin", "a/b")
160 r.valley("ready", "--change", id, "a/b")
161 v1 := r.git("rev-parse", "a/b")
162 byBranch := requestPrefix + "a-b"
163 r.setRef(byBranch, v1)
164 r.moveMain("other")
165 v2 := r.rebaseOnto("a/b")
166 r.valley("ready", "--change", id, "a/b")
167 r.git("fetch", "--quiet", "origin")
168
169 clean := func(why string) {
170 t.Helper()
171 if kind, text := r.compare(id, 2, v2); kind != compareClean || !strings.Contains(text, "rebased since you approved v1 at "+short(v1)+", with the same file changes.") {
172 t.Fatalf("%s: %s\n%s", why, kind, text)
173 }
174 }
175 unknown := func(why, ref string) {
176 t.Helper()
177 kind, text := r.compare(id, 2, v2)
178 if kind != compareNone || !strings.Contains(text, "is named by "+ref+", and another change or branch maps to that name too") {
179 t.Fatalf("%s: %s\n%s", why, kind, text)
180 }
181 }
182 clean("a request under the branch's name")
183
184 // A plain branch on origin whose name maps to a-b as well.
185 r.git("push", "--quiet", "origin", "main:refs/heads/a-b")
186 unknown("a request under a name a plain branch maps to", byBranch)
187 r.setRef("refs/heads/a-b", "")
188 clean("a request once the plain branch is gone")
189
190 // Another change, whose version names a branch that maps to a-b.
191 r.git("checkout", "--quiet", "-b", "a-b", "main")
192 r.file("y.txt", "y\n")
193 r.git("commit", "--quiet", "-m", "another change")
194 r.git("push", "--quiet", "origin", "a-b")
195 r.valley("ready", "--change", strings.Repeat("y", 32), "a-b")
196 r.git("checkout", "--quiet", "main")
197 r.setRef("refs/heads/a-b", "")
198 unknown("a request under a name another change's version maps to", byBranch)
199
200 // The outcome of the same request, after the integrator consumed it:
201 // ambiguous under a-b, and evidence under c-<change ID>.
202 r.setRef(byBranch, "")
203 r.setRef(outcomePrefix+"a-b", r.outcomeRecord(v1, "stale"))
204 unknown("an outcome under a name another change's version maps to", outcomePrefix+"a-b")
205 r.setRef(outcomePrefix+"a-b", "")
206 r.setRef(outcomePrefix+"c-"+id, r.outcomeRecord(v1, "refused-not-ready"))
207 if kind, text := r.compare(id, 2, v2); kind != compareNone || text != "" {
208 t.Fatalf("an outcome that judged no approval counted: %s\n%s", kind, text)
209 }
210 r.setRef(outcomePrefix+"c-"+id, r.outcomeRecord(v1, "land"))
211 clean("an outcome under c-<change ID>")
212
213 // A version shown is never its own reference, and a greater version
214 // named only ambiguously stops the search before v1.
215 r.git("checkout", "--quiet", "a/b")
216 r.file("feature.txt", "feature, edited\n")
217 r.git("commit", "--quiet", "-m", "edit the feature")
218 r.git("push", "--quiet", "origin", "a/b")
219 r.valley("ready", "--change", id, "a/b")
220 r.git("checkout", "--quiet", "main")
221 v3 := r.git("rev-parse", "a/b")
222 r.setRef(requestPrefix+"c-"+id, v3)
223 if kind, text := r.compare(id, 3, v3); kind != compareChanged || !strings.Contains(text, "edited since you approved v1 at "+short(v1)+".") {
224 t.Fatalf("v3 is not set against v1, the greatest version below it with an approval: %s\n%s", kind, text)
225 }
226 r.setRef(requestPrefix+"c-"+id, "")
227 r.setRef(byBranch, v2)
228 if kind, text := r.compare(id, 3, v3); kind != compareNone || !strings.Contains(text, "v2 at "+short(v2)+" is named by "+byBranch) {
229 t.Fatalf("v2 named ambiguously did not stop the search before v1: %s\n%s", kind, text)
230 }
231}
232
233// A branch named c/<ID> or c-<ID> maps to c-<ID>, which is reserved for
234// the change with that ID. A request or an outcome under it is that
235// change's, so it is no evidence of approval for a change whose versions
236// name the branch, even when it names one of their heads.
237func TestAnotherChangesReservedNameIsNoEvidence(t *testing.T) {
238 id, other := strings.Repeat("x", 32), strings.Repeat("y", 32)
239 for _, prefix := range []string{"c/", "c-"} {
240 t.Run(prefix, func(t *testing.T) {
241 r := newCompareRepo(t)
242 branch := prefix + other
243 r.git("checkout", "--quiet", "-b", branch)
244 r.file("feature.txt", "feature\n")
245 r.git("commit", "--quiet", "-m", "add the feature")
246 r.git("push", "--quiet", "origin", branch)
247 r.valley("ready", "--change", id, branch)
248 v1 := r.git("rev-parse", branch)
249 r.moveMain("other")
250 v2 := r.rebaseOnto(branch)
251 r.valley("ready", "--change", id, branch)
252 r.git("fetch", "--quiet", "origin")
253
254 reserved := "c-" + other
255 r.setRef(requestPrefix+reserved, v1)
256 r.setRef(outcomePrefix+reserved, r.outcomeRecord(v1, "land"))
257 if kind, text := r.compare(id, 2, v2); kind != compareNone || text != "" {
258 t.Fatalf("a request and an outcome under %s counted for %s: %s\n%s", reserved, id[:4], kind, text)
259 }
260 r.setRef(requestPrefix+"c-"+id, v1)
261 if kind, text := r.compare(id, 2, v2); kind != compareClean || !strings.Contains(text, "rebased since you approved v1 at "+short(v1)+", with the same file changes.") {
262 t.Fatalf("a request under the change's own c-<change ID>: %s\n%s", kind, text)
263 }
264 })
265 }
266}
267
268// land adds a commit to main on origin that writes a file, as a landing
269// would, and fetches it. It returns main's new tip.
270func (r *compareRepo) land(name, content, subject string) string {
271 r.git("checkout", "--quiet", "main")
272 r.file(name, content)
273 r.git("commit", "--quiet", "-m", subject)
274 r.git("push", "--quiet", "origin", "main")
275 return r.git("rev-parse", "HEAD")
276}
277
278// amend replaces the branch's last commit with the work tree's staged
279// files, keeping its message, and returns the new head after readying it.
280func (r *compareRepo) amend(id, branch string, args ...string) string {
281 r.git(append([]string{"commit", "--quiet", "--amend"}, args...)...)
282 r.git("push", "--quiet", "--force", "origin", branch)
283 r.valley("ready", "--change", id, branch)
284 r.git("checkout", "--quiet", "main")
285 return r.git("rev-parse", branch)
286}
287
288// lines is one line for each of n, numbered, with the line at edit
289// replaced.
290func lines(n, edit int, replacement string) string {
291 var b strings.Builder
292 for i := 1; i <= n; i++ {
293 if i == edit {
294 b.WriteString(replacement + "\n")
295 } else {
296 b.WriteString("line " + strconv.Itoa(i) + "\n")
297 }
298 }
299 return b.String()
300}
301
302func mustSay(t *testing.T, what, text string, want ...string) {
303 t.Helper()
304 for _, line := range want {
305 if !strings.Contains(text, line) {
306 t.Fatalf("%s does not say %q:\n%s", what, line, text)
307 }
308 }
309}
310
311// A clean restack names the landings between the two bases, oldest
312// first. An edited version lists the files whose change differs, the
313// range-diff, and the shown version's diff of those files in git's
314// ordinary form, whatever the person's diff configuration. A message or
315// an author that changed is an edit, shown whatever the files say.
316func TestCompareSaysWhatChanged(t *testing.T) {
317 r := newCompareRepo(t)
318 id := strings.Repeat("z", 32)
319 r.git("checkout", "--quiet", "-b", "topic")
320 r.file("tool.sh", "#!/bin/sh\n")
321 r.file("image.bin", "\x00\x01")
322 r.git("commit", "--quiet", "-m", "add the tool")
323 r.git("push", "--quiet", "origin", "topic")
324 r.valley("ready", "--change", id, "topic")
325 v1 := r.git("rev-parse", "topic")
326 b0 := r.git("rev-parse", "main")
327 r.setRef(requestPrefix+"c-"+id, v1)
328 one, two := r.moveMain("one"), r.moveMain("two")
329 v2 := r.rebaseOnto("topic")
330 r.valley("ready", "--change", id, "topic")
331 r.git("fetch", "--quiet", "origin")
332
333 kind, text := r.compare(id, 2, v2)
334 want := "zzzz v2 at " + short(v2) + ": rebased since you approved v1 at " + short(v1) + ", with the same file changes.\n" +
335 "Main moved " + short(b0) + " → " + short(two) + ", landing 2 commits:\n" +
336 " " + short(one) + " land one\n" +
337 " " + short(two) + " land two\n"
338 if kind != compareClean || text != want {
339 t.Fatalf("clean:\n%s\n%s\nwant:\n%s", kind, text, want)
340 }
341
342 // v3: the binary file's content and the tool's mode change. git
343 // range-diff calls the two commits equal, since a binary file's patch
344 // says only that it differs, but the commit's patch is not the same.
345 r.setRef(requestPrefix+"c-"+id, v2)
346 r.git("checkout", "--quiet", "topic")
347 r.file("image.bin", "\x00\x02")
348 if err := os.Chmod(filepath.Join(r.work, "tool.sh"), 0o755); err != nil {
349 t.Fatal(err)
350 }
351 r.git("add", "tool.sh")
352 v3 := r.amend(id, "topic", "--no-edit")
353 r.git("config", "diff.noprefix", "true")
354 kind, text = r.compare(id, 3, v3)
355 r.git("config", "--unset", "diff.noprefix")
356 mustSay(t, "an edited commit", text,
357 "zzzz v3 at "+short(v3)+": edited since you approved v2 at "+short(v2)+".\n"+
358 "Its base is still "+short(two)+".\n"+
359 "1 of 1 commit changed, and 2 files differ from v2:\n image.bin\n tool.sh\n\n",
360 "── git range-diff "+short(two)+".."+short(v2)+" "+short(two)+".."+short(v3)+" ──\n",
361 "1: "+short(v2)+" = 1: "+short(v3)+" add the tool",
362 "\n── v3's diff of these 2 files against main "+short(two)+" ──\ndiff --git a/image.bin b/image.bin\n",
363 "Binary files /dev/null and b/image.bin differ\ndiff --git a/tool.sh b/tool.sh\nnew file mode 100755\n",
364 "@@ -0,0 +1 @@\n+#!/bin/sh\n",
365 )
366 if kind != compareChanged || strings.Contains(text, "Commit messages") || strings.Contains(text, "v2: absent") {
367 t.Fatalf("an edited commit: %s\n%s", kind, text)
368 }
369 _, verbose := r.compareVerbose(id, 3, v3)
370 mustSay(t, "-v", verbose, " image.bin\n v2: absent -> 100644 ", " tool.sh\n v2: absent -> 100644 ", " v3: absent -> 100755 ")
371
372 // v4: the same files, with another message and another author.
373 r.setRef(requestPrefix+"c-"+id, v3)
374 r.git("checkout", "--quiet", "topic")
375 v4 := r.amend(id, "topic", "-m", "add the tool, renamed", "--author", "Someone Else <else@localhost>")
376 kind, text = r.compare(id, 4, v4)
377 mustSay(t, "a changed message and author", text,
378 ": edited since you approved v3 at "+short(v3)+", with the same file changes.\n",
379 "Commit messages edited since you approved v3. Read them before approving:\n"+
380 " v3, commit 1 of 1, "+short(v3)+":\n add the tool\n"+
381 " v4, commit 1 of 1, "+short(v4)+":\n add the tool, renamed\n",
382 "Commit authors edited since you approved v3:\n v3, commit 1 of 1, "+short(v3)+": compare-test <compare-test@localhost> ",
383 " v4, commit 1 of 1, "+short(v4)+": Someone Else <else@localhost> ",
384 "Its base is still "+short(two)+".\n",
385 )
386 if kind != compareClean {
387 t.Fatalf("a changed message alone is still a clean file delta: %s", kind)
388 }
389
390 // The version given must have the head given.
391 if _, err := r.runCompare("--tip", two, id, "3", v4); err == nil || !strings.Contains(err.Error(), "v3 of change zzzz records the head") {
392 t.Fatalf("compare took a head its version does not record: %v", err)
393 }
394}
395
396// A rebase whose commit is untouched, onto landings that edited the same
397// file, says the commit is unchanged and names those landings, with no
398// range-diff. An edit after it names, for each file whose change
399// differs, the landings that edited it or none, then the range-diff.
400func TestCompareAttributesFilesMainAlsoEdited(t *testing.T) {
401 r := newCompareRepo(t)
402 id := strings.Repeat("w", 32)
403 r.land("shared.txt", lines(20, 0, ""), "add shared")
404 b0 := r.git("rev-parse", "main")
405 r.git("checkout", "--quiet", "-b", "topic")
406 r.file("shared.txt", lines(20, 2, "topic's line 2"))
407 r.git("commit", "--quiet", "-m", "edit line 2")
408 r.git("push", "--quiet", "origin", "topic")
409 r.valley("ready", "--change", id, "topic")
410 v1 := r.git("rev-parse", "topic")
411 r.setRef(requestPrefix+"c-"+id, v1)
412 shared := r.land("shared.txt", lines(20, 18, "main's line 18"), "edit line 18 of shared, with a subject long enough that the listing has to cut it short")
413 b1 := r.moveMain("unrelated")
414 v2 := r.rebaseOnto("topic")
415 r.valley("ready", "--change", id, "topic")
416 r.git("fetch", "--quiet", "origin")
417
418 kind, text := r.compare(id, 2, v2)
419 mustSay(t, "a rebase onto a file main also edited", text,
420 "wwww v2 at "+short(v2)+": rebased since you approved v1 at "+short(v1)+".\n"+
421 "Its commit is unchanged: same patch, same message.\n"+
422 "Main moved "+short(b0)+" → "+short(b1)+" and also edited 1 of its files:\n"+
423 " shared.txt "+short(shared)+" edit line 18 of shared, with a subject long enough that the listing has to cu…\n"+
424 "\n── v2's diff of this file against main "+short(b1)+" ──\ndiff --git a/shared.txt b/shared.txt\n",
425 "-line 2\n+topic's line 2\n",
426 )
427 if kind != compareChanged || strings.Contains(text, "range-diff") {
428 t.Fatalf("a rebase onto a file main also edited: %s\n%s", kind, text)
429 }
430
431 // v3: the commit is edited and adds a file, after main edits the
432 // shared file again.
433 r.setRef(requestPrefix+"c-"+id, v2)
434 again := r.land("shared.txt", lines(20, 18, "main's line 18, again"), "edit line 18 again")
435 b2 := r.git("rev-parse", "main")
436 r.rebaseOnto("topic")
437 r.git("checkout", "--quiet", "topic")
438 r.file("shared.txt", strings.Replace(r.git("show", "HEAD:shared.txt")+"\n", "topic's line 2", "topic's line 2, edited", 1))
439 r.file("new.txt", "new\n")
440 v3 := r.amend(id, "topic", "--no-edit")
441 r.git("fetch", "--quiet", "origin")
442 kind, text = r.compare(id, 3, v3)
443 mustSay(t, "an edit after a rebase", text,
444 "wwww v3 at "+short(v3)+": edited since you approved v2 at "+short(v2)+".\n"+
445 "Main moved "+short(b1)+" → "+short(b2)+".\n"+
446 "1 of 1 commit changed, and 2 files differ from v2:\n"+
447 " new.txt not edited on main\n"+
448 " shared.txt "+short(again)+" edit line 18 again\n"+
449 "\n── git range-diff "+short(b1)+".."+short(v2)+" "+short(b2)+".."+short(v3)+" ──\n",
450 "1: "+short(v3)+" edit line 2\n",
451 "\n── v3's diff of these 2 files against main "+short(b2)+" ──\ndiff --git a/new.txt b/new.txt\n",
452 )
453 if kind != compareChanged {
454 t.Fatalf("an edit after a rebase: %s", kind)
455 }
456}
457
458// style changes no line's text, styles a comparison's title, headings and
459// summary, and leaves a diff's lines as they are; with NO_COLOR set, or
460// for no terminal, it copies the page.
461func TestStyleKeepsEveryLine(t *testing.T) {
462 page := "layer heading\n" +
463 "zzzz v3 at 1234abc: edited since you approved v2 at 5678def.\n" +
464 "does oc-1234567: a knot\n" +
465 "Main moved 1111aaa → 2222bbb.\n" +
466 " shared.txt 3333ccc edit line 18\n" +
467 "\n── v3's diff of this file against main 2222bbb ──\n" +
468 "diff --git a/f b/f\n" +
469 "+edited 4444ddd\n"
470 style := func(args ...string) string {
471 var out bytes.Buffer
472 if err := runStyle(args, strings.NewReader(page), &out); err != nil {
473 t.Fatal(err)
474 }
475 return out.String()
476 }
477 t.Setenv("NO_COLOR", "")
478 styled := style("--paged")
479 if got := styleEscape.ReplaceAllString(styled, ""); got != page {
480 t.Fatalf("style changed the text:\n%s", got)
481 }
482 for _, want := range []string{
483 "layer heading\n",
484 "\x1b[1mzzzz v3 at 1234abc: \x1b[33medited\x1b[39m since you approved v2 at 5678def.\x1b[22m\n",
485 "Main moved \x1b[2m1111aaa\x1b[22m → \x1b[2m2222bbb\x1b[22m.\n",
486 "\x1b[36m── v3's diff of this file against main 2222bbb ──\x1b[39m\n",
487 "diff --git a/f b/f\n+edited 4444ddd\n",
488 } {
489 if !strings.Contains(styled, want) {
490 t.Fatalf("style does not give %q:\n%q", want, styled)
491 }
492 }
493 if got := style(); got != page {
494 t.Fatalf("style styled a page for no terminal:\n%q", got)
495 }
496 t.Setenv("NO_COLOR", "1")
497 if got := style("--paged"); got != page {
498 t.Fatalf("style styled a page with NO_COLOR set:\n%q", got)
499 }
500}