gunk-dev/the-valley

rebase_test.go

sourcefefe7833f700main's published tip history
24.4 KiB
1package rebase
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "strconv"
14 "strings"
15 "testing"
16 "time"
17
18 "the-valley/change"
19)
20
21// roleEnv, set to "drop-acks", makes the test binary origin's receive-pack
22// that never acknowledges a push: see dropAcks.
23const roleEnv = "REBASE_TEST_ROLE"
24
25func TestMain(m *testing.M) {
26 if os.Getenv(roleEnv) == "drop-acks" {
27 os.Exit(dropAcks(os.Args[1:]))
28 }
29 os.Exit(m.Run())
30}
31
32// dropAcks is git receive-pack less its acknowledgements. It runs the real
33// receive-pack, which takes the push, and passes its report on without the
34// status of any ref, as when origin's answer is lost. The side-band
35// capabilities are taken out of its advertisement, so the report comes as
36// plain pkt-lines.
37func dropAcks(args []string) int {
38 cmd := exec.Command("git", append([]string{"receive-pack"}, args...)...)
39 cmd.Stdin, cmd.Stderr = os.Stdin, os.Stderr
40 out, err := cmd.StdoutPipe()
41 if err != nil || cmd.Start() != nil {
42 return 1
43 }
44 r := bufio.NewReader(out)
45 advertised := false
46 for {
47 p, err := readPkt(r)
48 if err != nil {
49 break
50 }
51 switch {
52 case p == nil:
53 advertised = true
54 case !advertised:
55 if refs, caps, ok := bytes.Cut(p, []byte{0}); ok {
56 var kept []string
57 for _, c := range strings.Fields(string(caps)) {
58 if !strings.HasPrefix(c, "side-band") {
59 kept = append(kept, c)
60 }
61 }
62 p = []byte(string(refs) + "\x00" + strings.Join(kept, " ") + "\n")
63 }
64 case bytes.HasPrefix(p, []byte("ok ")) || bytes.HasPrefix(p, []byte("ng ")) || bytes.HasPrefix(p, []byte("option ")):
65 continue
66 }
67 if p == nil {
68 io.WriteString(os.Stdout, "0000")
69 } else {
70 fmt.Fprintf(os.Stdout, "%04x%s", len(p)+4, p)
71 }
72 }
73 if cmd.Wait() != nil {
74 return 1
75 }
76 return 0
77}
78
79// readPkt reads one pkt-line, nil for a flush.
80func readPkt(r *bufio.Reader) ([]byte, error) {
81 var size [4]byte
82 if _, err := io.ReadFull(r, size[:]); err != nil {
83 return nil, err
84 }
85 n, err := strconv.ParseUint(string(size[:]), 16, 16)
86 if err != nil || n < 4 {
87 return nil, err
88 }
89 p := make([]byte, n-4)
90 _, err = io.ReadFull(r, p)
91 return p, err
92}
93
94// world is a bare origin and a clone of it to work in, with git's
95// configuration its own.
96type world struct {
97 t *testing.T
98 origin, work string
99 env []string
100 g Git
101}
102
103func newWorld(t *testing.T) *world {
104 t.Helper()
105 dir := t.TempDir()
106 w := &world{t: t, origin: filepath.Join(dir, "origin.git"), work: filepath.Join(dir, "work")}
107 w.env = append(os.Environ(), "HOME="+dir, "XDG_CONFIG_HOME="+filepath.Join(dir, "config"), "GIT_CONFIG_NOSYSTEM=1",
108 "GIT_AUTHOR_NAME=rebase-test", "GIT_AUTHOR_EMAIL=rebase-test@localhost",
109 "GIT_COMMITTER_NAME=rebase-test", "GIT_COMMITTER_EMAIL=rebase-test@localhost")
110 w.run(dir, "init", "--quiet", "--bare", "--initial-branch=main", w.origin)
111 w.run(dir, "clone", "--quiet", w.origin, w.work)
112 w.g = Git{Dir: w.work, Env: w.env}
113 w.git("checkout", "--quiet", "-b", "main")
114 w.commit("base", "base.txt", "base\n")
115 w.git("push", "--quiet", "origin", "main")
116 return w
117}
118
119func (w *world) run(dir string, args ...string) string {
120 w.t.Helper()
121 cmd := exec.Command("git", args...)
122 cmd.Dir, cmd.Env = dir, w.env
123 out, err := cmd.CombinedOutput()
124 if err != nil {
125 w.t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
126 }
127 return strings.TrimSpace(string(out))
128}
129
130func (w *world) git(args ...string) string { w.t.Helper(); return w.run(w.work, args...) }
131
132// commit writes one file on the current branch and commits it.
133func (w *world) commit(subject, file, content string) string {
134 w.t.Helper()
135 if err := os.WriteFile(filepath.Join(w.work, file), []byte(content), 0o644); err != nil {
136 w.t.Fatal(err)
137 }
138 w.git("add", file)
139 w.git("commit", "--quiet", "-m", subject)
140 return w.git("rev-parse", "HEAD")
141}
142
143// layer makes a branch on from with one commit of its own, pushes it, and
144// returns its head.
145func (w *world) layer(branch, from string) string {
146 w.t.Helper()
147 w.git("checkout", "--quiet", "-b", branch, from)
148 head := w.commit("layer "+branch, branch+".txt", branch+"\n")
149 w.git("push", "--quiet", "origin", branch)
150 return head
151}
152
153// moveMain moves origin's main on by a commit of its own.
154func (w *world) moveMain(file, content string) string {
155 w.t.Helper()
156 w.git("checkout", "--quiet", "main")
157 head := w.commit("main moves on: "+file, file, content)
158 w.git("push", "--quiet", "origin", "main")
159 return head
160}
161
162// ready writes a ready record for a change at v1, on branch at its head on
163// origin, through the engine's own write path. Its title is its head's
164// commit subject.
165func (w *world) ready(id, branch string) {
166 w.t.Helper()
167 w.readyTitled(id, branch, "layer "+branch)
168}
169
170// readyTitled is ready with the title given.
171func (w *world) readyTitled(id, branch, title string) {
172 w.t.Helper()
173 head := w.at("refs/heads/" + branch)
174 r := &change.Record{
175 Schema: change.Schema, ChangeID: id, Target: Target, Owner: "author", State: change.Ready, Seq: 1, Active: 1,
176 Versions: []change.Version{{N: 1, Head: change.HeadPrefix + head, Title: title, Branch: branch, Uploader: "author"}},
177 }
178 w.write(id, r, "", head)
179}
180
181// setState writes the change's record again in another state.
182func (w *world) setState(id, state string) {
183 w.t.Helper()
184 old := w.at(change.Ref(Target, id))
185 r := w.record(id)
186 r.State, r.Seq = state, r.Seq+1
187 w.write(id, r, old, old)
188}
189
190func (w *world) write(id string, r *change.Record, old string, parents ...string) {
191 w.t.Helper()
192 ctx := context.Background()
193 commit, err := WriteRecord(ctx, w.g, r, "test record", parents...)
194 if err != nil {
195 w.t.Fatal(err)
196 }
197 if got := PushRecord(ctx, w.g, id, old, commit); got.Push != Pushed {
198 w.t.Fatalf("the record of %s was not pushed: %+v", id, got)
199 }
200}
201
202// at is a ref on origin, or "" for none.
203func (w *world) at(ref string) string {
204 w.t.Helper()
205 cmd := exec.Command("git", "rev-parse", "--verify", "--quiet", ref)
206 cmd.Dir, cmd.Env = w.origin, w.env
207 out, _ := cmd.Output()
208 return strings.TrimSpace(string(out))
209}
210
211func (w *world) record(id string) *change.Record {
212 w.t.Helper()
213 data := w.run(w.origin, "cat-file", "blob", change.Ref(Target, id)+":record.json")
214 r, err := change.Parse([]byte(data + "\n"))
215 if err != nil {
216 w.t.Fatal(err)
217 }
218 return r
219}
220
221// refs is every branch and record on origin, to tell that nothing moved.
222func (w *world) refs() string {
223 w.t.Helper()
224 return w.run(w.origin, "for-each-ref", "--format=%(objectname) %(refname)", "refs/heads/", change.RefPrefix)
225}
226
227// capture reads a snapshot and the family a selection names.
228func (w *world) capture(sel Selection) *Family {
229 w.t.Helper()
230 s, err := ReadSnapshot(context.Background(), w.g, Verifier{Attest: "attest"})
231 if err != nil {
232 w.t.Fatal(err)
233 }
234 f, err := Capture(s, sel)
235 if err != nil {
236 w.t.Fatal(err)
237 }
238 return f
239}
240
241// publish prepares, pushes and appends a family as the principal rebaser.
242func (w *world) publish(f *Family) *Publication {
243 w.t.Helper()
244 ctx := context.Background()
245 p, err := Prepare(ctx, w.g, f)
246 if err != nil {
247 w.t.Fatalf("prepare: %v", err)
248 }
249 defer p.Release(ctx, w.g)
250 pub, err := Publish(ctx, w.g, p)
251 if err != nil {
252 w.t.Fatalf("publish: %v", err)
253 }
254 pub.AppendAll(ctx, w.g, "rebaser")
255 return pub
256}
257
258// unacknowledged is a receive-pack for origin that takes a push and never
259// acknowledges it, for remote.origin.receivepack.
260func (w *world) unacknowledged() string {
261 w.t.Helper()
262 self, err := os.Executable()
263 if err != nil {
264 w.t.Fatal(err)
265 }
266 path := filepath.Join(w.t.TempDir(), "unacknowledged-receive-pack")
267 script := fmt.Sprintf("#!/bin/sh\n%s=drop-acks exec '%s' \"$@\"\n", roleEnv, self)
268 if err := os.WriteFile(path, []byte(script), 0o755); err != nil {
269 w.t.Fatal(err)
270 }
271 return path
272}
273
274// sameDelta holds that a layer's diff from its base is what it was.
275func (w *world) sameDelta(oldBase, oldHead, newBase, newHead string) {
276 w.t.Helper()
277 if a, b := w.run(w.origin, "diff", oldBase, oldHead), w.run(w.origin, "diff", newBase, newHead); a != b {
278 w.t.Errorf("the diff of %s changed in the rebase:\n%s\nnow:\n%s", oldHead, a, b)
279 }
280}
281
282func (w *world) ancestor(a, b string) bool {
283 cmd := exec.Command("git", "merge-base", "--is-ancestor", a, b)
284 cmd.Dir, cmd.Env = w.origin, w.env
285 return cmd.Run() == nil
286}
287
288func names(layers []*Layer) string {
289 var n []string
290 for _, l := range layers {
291 n = append(n, l.Name)
292 }
293 return strings.Join(n, " ")
294}
295
296var (
297 idA = strings.Repeat("k", 32)
298 idB = strings.Repeat("m", 32)
299 idC = strings.Repeat("n", 32)
300)
301
302// A chain A → B → C moves whole onto main: each layer onto the rebased
303// layer below, each keeping its own diff, one push for every branch, and
304// each change's rebased head added as v2 with the rebaser as its uploader.
305func TestChainMovesWhole(t *testing.T) {
306 w := newWorld(t)
307 base := w.at("refs/heads/main")
308 a := w.layer("a", "main")
309 b := w.layer("b", "a")
310 c := w.layer("c", "b")
311 w.ready(idA, "a")
312 w.ready(idB, "b")
313 w.ready(idC, "c")
314 main := w.moveMain("main.txt", "main\n")
315
316 f := w.capture(Selection{ID: idC})
317 if got := names(f.Layers); got != "kkkk mmmm nnnn" {
318 t.Fatalf("the chain under c is %q", got)
319 }
320 pub := w.publish(f)
321 if pub.Push != Pushed {
322 t.Fatalf("the branches were not pushed: %v %v", pub.Push, pub.Refused)
323 }
324 na, nb, nc := w.at("refs/heads/a"), w.at("refs/heads/b"), w.at("refs/heads/c")
325 if !w.ancestor(main, na) || !w.ancestor(na, nb) || !w.ancestor(nb, nc) {
326 t.Fatal("the rebased chain is not main, a, b, c")
327 }
328 w.sameDelta(base, a, main, na)
329 w.sameDelta(a, b, na, nb)
330 w.sameDelta(b, c, nb, nc)
331 for id, head := range map[string]string{idA: na, idB: nb, idC: nc} {
332 r := w.record(id)
333 v := r.ActiveVersion()
334 if r.State != change.Ready || v.N != 2 || HeadOf(v) != head || v.Uploader != "rebaser" {
335 t.Errorf("change %s: %+v", id[:4], r)
336 }
337 }
338 for _, res := range pub.Results {
339 if res.Branch != Pushed || res.Appended == nil || res.Appended.Version != 2 || res.Unfinished() {
340 t.Errorf("%s: %+v", res.Layer.Name, res)
341 }
342 }
343}
344
345// A shared lower layer, A → B and A → C, is prepared once: A gains one
346// version, both children are rebased onto its new head, and one push moves
347// all three branches. The family is the same from either child.
348func TestSharedLowerLayerIsRebasedOnce(t *testing.T) {
349 w := newWorld(t)
350 a := w.layer("a", "main")
351 b := w.layer("b", "a")
352 c := w.layer("c", "a")
353 w.ready(idA, "a")
354 w.ready(idB, "b")
355 w.ready(idC, "c")
356 main := w.moveMain("main.txt", "main\n")
357
358 if got := names(w.capture(Selection{ID: idC, Whole: true}).Layers); got != "kkkk mmmm nnnn" {
359 t.Fatalf("the family of c is %q", got)
360 }
361 f := w.capture(Selection{ID: idB, Whole: true})
362 if got := names(f.Layers); got != "kkkk mmmm nnnn" {
363 t.Fatalf("the family of b is %q", got)
364 }
365 if len(f.Tops()) != 2 || f.Bottom().ID != idA {
366 t.Fatalf("the family's tops are %q", names(f.Tops()))
367 }
368 pub := w.publish(f)
369 if pub.Push != Pushed {
370 t.Fatalf("the branches were not pushed: %v %v", pub.Push, pub.Refused)
371 }
372 na, nb, nc := w.at("refs/heads/a"), w.at("refs/heads/b"), w.at("refs/heads/c")
373 if w.run(w.origin, "rev-parse", nb+"^") != na || w.run(w.origin, "rev-parse", nc+"^") != na {
374 t.Fatal("b and c are not both on the new head of a")
375 }
376 if !w.ancestor(main, na) {
377 t.Fatal("a is not on main")
378 }
379 w.sameDelta(a, b, na, nb)
380 w.sameDelta(a, c, na, nc)
381 if r := w.record(idA); len(r.Versions) != 2 || HeadOf(r.ActiveVersion()) != na {
382 t.Errorf("a gained other than one version: %+v", r)
383 }
384}
385
386// A conflict in one child holds the whole family: no branch moves, and no
387// record gains a version, the siblings' included. The refusal names the
388// layer and the path.
389func TestConflictMovesNothing(t *testing.T) {
390 w := newWorld(t)
391 w.layer("a", "main")
392 w.layer("b", "a")
393 w.layer("c", "a")
394 w.ready(idA, "a")
395 w.ready(idB, "b")
396 w.ready(idC, "c")
397 w.moveMain("c.txt", "main has its own\n")
398 before := w.refs()
399
400 f := w.capture(Selection{ID: idA, Whole: true})
401 _, err := Prepare(context.Background(), w.g, f)
402 var r *Refusal
403 if !errors.As(err, &r) || r.Kind != Conflict || r.Layer.ID != idC || r.Below != "kkkk as rebased" {
404 t.Fatalf("prepare: %v", err)
405 }
406 if strings.Join(r.Paths, " ") != "c.txt" {
407 t.Errorf("the conflict names %q", r.Paths)
408 }
409 if after := w.refs(); after != before {
410 t.Errorf("a conflict moved something:\n%s\nnow:\n%s", before, after)
411 }
412 if out := w.git("worktree", "list", "--porcelain"); strings.Count(out, "worktree ") != 1 {
413 t.Errorf("the rebase left a worktree:\n%s", out)
414 }
415}
416
417// A layer whose commits are on main already rebases to nothing, and is
418// refused rather than retired.
419func TestEmptyLayerIsRefused(t *testing.T) {
420 w := newWorld(t)
421 w.layer("a", "main")
422 w.ready(idA, "a")
423 w.moveMain("a.txt", "a\n")
424 before := w.refs()
425
426 _, err := Prepare(context.Background(), w.g, w.capture(Selection{ID: idA}))
427 var r *Refusal
428 if !errors.As(err, &r) || r.Kind != EmptyLayer || r.Layer.ID != idA || r.Below != Target {
429 t.Fatalf("prepare: %v", err)
430 }
431 if after := w.refs(); after != before {
432 t.Errorf("an empty layer moved something")
433 }
434}
435
436// A branch moved on origin between the capture and the push loses its
437// lease: the atomic push moves no branch, says which was refused, and no
438// version is appended.
439func TestMovedBranchLosesItsLease(t *testing.T) {
440 w := newWorld(t)
441 w.layer("a", "main")
442 w.layer("b", "a")
443 w.ready(idA, "a")
444 w.ready(idB, "b")
445 w.moveMain("main.txt", "main\n")
446 ctx := context.Background()
447
448 p, err := Prepare(ctx, w.g, w.capture(Selection{ID: idB}))
449 if err != nil {
450 t.Fatal(err)
451 }
452 defer p.Release(ctx, w.g)
453 elsewhere := w.layer("elsewhere", "b")
454 w.git("push", "--quiet", "--force", "origin", elsewhere+":refs/heads/b")
455 before := w.refs()
456
457 pub, err := Publish(ctx, w.g, p)
458 if err != nil {
459 t.Fatal(err)
460 }
461 pub.AppendAll(ctx, w.g, "rebaser")
462 stale := false
463 for _, ref := range pub.Refused {
464 stale = stale || ref.Ref == "refs/heads/b" && strings.Contains(ref.Why, "stale info")
465 }
466 if pub.Push != Refused || !stale {
467 t.Fatalf("the push was %v, refusing %+v", pub.Push, pub.Refused)
468 }
469 if after := w.refs(); after != before {
470 t.Errorf("a refused push moved something:\n%s\nnow:\n%s", before, after)
471 }
472 for _, res := range pub.Results {
473 if res.Appended != nil || res.Unfinished() {
474 t.Errorf("%s: %+v", res.Layer.Name, res.Appended)
475 }
476 }
477}
478
479// After the branches move, each append stands alone. A change unreadied
480// meanwhile gains no version and writes no record; one whose record push
481// the hook refuses keeps the record commit it tried; one whose record push
482// origin takes and never acknowledges is unknown, not refused; and the
483// rest are appended.
484func TestAppendsAfterThePushStandAlone(t *testing.T) {
485 w := newWorld(t)
486 w.layer("a", "main")
487 w.layer("b", "a")
488 w.layer("c", "b")
489 w.layer("d", "c")
490 idD := strings.Repeat("p", 32)
491 w.ready(idA, "a")
492 w.ready(idB, "b")
493 w.ready(idC, "c")
494 w.ready(idD, "d")
495 w.moveMain("main.txt", "main\n")
496 ctx := context.Background()
497
498 p, err := Prepare(ctx, w.g, w.capture(Selection{ID: idD}))
499 if err != nil {
500 t.Fatal(err)
501 }
502 defer p.Release(ctx, w.g)
503 pub, err := Publish(ctx, w.g, p)
504 if err != nil || pub.Push != Pushed {
505 t.Fatalf("publish: %v %v", err, pub.Push)
506 }
507 w.setState(idB, change.Draft)
508 hook := filepath.Join(w.origin, "hooks", "pre-receive")
509 refuse := "#!/bin/sh\nwhile read old new ref; do [ \"$ref\" = " + change.Ref(Target, idC) + " ] && exit 1; done\nexit 0\n"
510 if err := os.WriteFile(hook, []byte(refuse), 0o755); err != nil {
511 t.Fatal(err)
512 }
513 lossy := w.unacknowledged()
514
515 for _, res := range pub.Results {
516 if res.Layer.ID == idD {
517 w.git("config", "remote.origin.receivepack", lossy)
518 }
519 pub.Append(ctx, w.g, "rebaser", res)
520 }
521 w.git("config", "--unset", "remote.origin.receivepack")
522 byID := map[string]*Appended{}
523 for _, res := range pub.Results {
524 byID[res.Layer.ID] = res.Appended
525 }
526 if ap := byID[idA]; ap.Err != nil || ap.Version != 2 || ap.Write.Push != Pushed {
527 t.Errorf("a: %+v", ap)
528 }
529 if ap := byID[idB]; ap.Err == nil || ap.Version != 0 || ap.Write.Commit != "" || ap.Write.Push != Unpushed {
530 t.Errorf("b, unreadied: %+v", ap)
531 }
532 if ap := byID[idC]; ap.Err == nil || ap.Write.Push != Refused || ap.Write.Commit == "" || ap.Write.Why == "" ||
533 w.at(change.Ref(Target, idC)) != ap.Write.Old {
534 t.Errorf("c, refused by the hook: %+v", ap)
535 }
536 if ap := byID[idD]; ap.Err == nil || ap.Write.Push != Unknown || ap.Write.Why != "" || w.at(change.Ref(Target, idD)) != ap.Write.Commit {
537 t.Errorf("d, its acknowledgement lost: %+v", ap)
538 }
539 if r := w.record(idB); r.State != change.Draft || len(r.Versions) != 1 {
540 t.Errorf("b gained a version while a draft: %+v", r)
541 }
542 var unfinished []string
543 for _, res := range pub.Results {
544 if res.Unfinished() {
545 unfinished = append(unfinished, res.Layer.Name)
546 }
547 }
548 if got := strings.Join(unfinished, " "); got != "mmmm nnnn pppp" {
549 t.Errorf("the unfinished layers are %q", got)
550 }
551}
552
553// A branch push that origin takes and never acknowledges is unknown, not
554// refused. git reports each branch as a remote failure, origin holds
555// every prepared head, and each change is left unfinished, with no version
556// appended.
557func TestUnacknowledgedBranchPushIsUnknown(t *testing.T) {
558 w := newWorld(t)
559 w.layer("a", "main")
560 w.layer("b", "a")
561 w.ready(idA, "a")
562 w.ready(idB, "b")
563 w.moveMain("main.txt", "main\n")
564 ctx := context.Background()
565
566 p, err := Prepare(ctx, w.g, w.capture(Selection{ID: idB}))
567 if err != nil {
568 t.Fatal(err)
569 }
570 defer p.Release(ctx, w.g)
571 w.git("config", "remote.origin.receivepack", w.unacknowledged())
572 pub, err := Publish(ctx, w.g, p)
573 w.git("config", "--unset", "remote.origin.receivepack")
574 if err != nil {
575 t.Fatal(err)
576 }
577 pub.AppendAll(ctx, w.g, "rebaser")
578 if pub.Push != Unknown || len(pub.Refused) != 0 {
579 t.Fatalf("the push was %v, refusing %+v", pub.Push, pub.Refused)
580 }
581 for _, res := range pub.Results {
582 if got := w.at("refs/heads/" + res.Layer.Branch); got != res.Head {
583 t.Errorf("origin's %s is at %s, not the prepared %s", res.Layer.Branch, got, res.Head)
584 }
585 if res.Branch != Unknown || res.Appended != nil || !res.Unfinished() {
586 t.Errorf("%s: %+v", res.Layer.Name, res)
587 }
588 }
589}
590
591// blocker is a script that stands for a hook or a filter that does not
592// return. The first time it gets past its guard, it says it has started.
593// It then keeps whatever output it was given open for a minute, and beats
594// while it does: it adds a line to a file every tenth of a second.
595type blocker struct {
596 script, started, beats string
597}
598
599func newBlocker(t *testing.T, script, guard string) *blocker {
600 t.Helper()
601 dir := t.TempDir()
602 b := &blocker{script: script, started: filepath.Join(dir, "started"), beats: filepath.Join(dir, "beats")}
603 body := fmt.Sprintf("#!/bin/sh\n%s\n[ -e '%s' ] && exit 0\n: > '%s'\n"+
604 "i=0\nwhile [ $i -lt 600 ]; do echo >> '%s'; sleep 0.1; i=$((i+1)); done\n",
605 guard, b.started, b.started, b.beats)
606 if err := os.WriteFile(script, []byte(body), 0o755); err != nil {
607 t.Fatal(err)
608 }
609 return b
610}
611
612// wait waits for the blocker to start.
613func (b *blocker) wait(t *testing.T) {
614 t.Helper()
615 for deadline := time.Now().Add(30 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) {
616 if _, err := os.Stat(b.started); err == nil {
617 return
618 }
619 }
620 t.Fatal("the blocker never started")
621}
622
623// beating reports whether the blocker is still alive: whether it beats
624// within a second.
625func (b *blocker) beating() bool {
626 size := func() int64 {
627 fi, err := os.Stat(b.beats)
628 if err != nil {
629 return 0
630 }
631 return fi.Size()
632 }
633 time.Sleep(200 * time.Millisecond)
634 before := size()
635 time.Sleep(time.Second)
636 return size() != before
637}
638
639// A Prepare cancelled while git waits on a hook or a filter returns at
640// once, and leaves nothing behind. git and what it started are killed,
641// even when they hold the output the engine reads. No worktree stays
642// registered, though worktree add was killed part way, and no ref stays,
643// though update-ref had created the refs before it was killed.
644func TestCancelledPartWayLeavesNothing(t *testing.T) {
645 for _, c := range []struct {
646 name string
647 block func(w *world) *blocker
648 }{
649 {"a post-checkout hook, as worktree add ends", func(w *world) *blocker {
650 return newBlocker(w.t, filepath.Join(w.work, ".git", "hooks", "post-checkout"), "")
651 }},
652 {"a smudge filter, as worktree add checks out", func(w *world) *blocker {
653 b := newBlocker(w.t, filepath.Join(w.t.TempDir(), "smudge"), "")
654 w.git("config", "filter.block.smudge", b.script)
655 return b
656 }},
657 {"a reference-transaction hook, once the kept refs are created", func(w *world) *blocker {
658 guard := "[ \"$1\" = committed ] || exit 0\ncase $(cat) in *' " + keepPrefix + "'*) ;; *) exit 0 ;; esac"
659 return newBlocker(w.t, filepath.Join(w.work, ".git", "hooks", "reference-transaction"), guard)
660 }},
661 } {
662 t.Run(c.name, func(t *testing.T) {
663 w := newWorld(t)
664 w.git("checkout", "--quiet", "-b", "a", "main")
665 w.commit("layer a", ".gitattributes", "*.blocked filter=block\n")
666 w.commit("layer a, blocked", "a.blocked", "a\n")
667 w.git("push", "--quiet", "origin", "a")
668 w.ready(idA, "a")
669 w.moveMain("main.txt", "main\n")
670 f := w.capture(Selection{ID: idA})
671 before := w.refs()
672 b := c.block(w)
673 tmp := filepath.Join(t.TempDir(), "tmp")
674 if err := os.Mkdir(tmp, 0o755); err != nil {
675 t.Fatal(err)
676 }
677 t.Setenv("TMPDIR", tmp)
678
679 // The engine's stderr is a pipe that the blocker holds.
680 var stderr bytes.Buffer
681 g := w.g
682 g.Stderr = &stderr
683 ctx, cancel := context.WithCancel(context.Background())
684 defer cancel()
685 done := make(chan error, 1)
686 go func() {
687 _, err := Prepare(ctx, g, f)
688 done <- err
689 }()
690 b.wait(t)
691 cancel()
692 select {
693 case err := <-done:
694 if !errors.Is(err, context.Canceled) {
695 t.Fatalf("prepare: %v", err)
696 }
697 case <-time.After(30 * time.Second):
698 t.Fatal("prepare did not return once cancelled")
699 }
700
701 if b.beating() {
702 t.Error("what git started outlived the cancellation")
703 }
704 if kept := w.git("for-each-ref", keepPrefix); kept != "" {
705 t.Errorf("the rebase left a ref behind: %q", kept)
706 }
707 if out := w.git("worktree", "list", "--porcelain"); strings.Count(out, "worktree ") != 1 {
708 t.Errorf("the rebase left a worktree registered:\n%s", out)
709 }
710 if left, _ := os.ReadDir(filepath.Join(w.work, ".git", "worktrees")); len(left) != 0 {
711 t.Errorf("the rebase left %d worktree registrations", len(left))
712 }
713 if left, _ := os.ReadDir(tmp); len(left) != 0 {
714 t.Errorf("the rebase left its worktree's directory: %s", left[0].Name())
715 }
716 if after := w.refs(); after != before {
717 t.Errorf("a cancelled rebase moved something")
718 }
719 })
720 }
721}
722
723// A cancelled context publishes nothing: Prepare under one leaves no
724// worktree and no ref behind, and Publish under one pushes nothing, the
725// prepared heads kept until they are released.
726func TestCancelledBeforePublishPublishesNothing(t *testing.T) {
727 w := newWorld(t)
728 w.layer("a", "main")
729 w.ready(idA, "a")
730 w.moveMain("main.txt", "main\n")
731 before := w.refs()
732
733 cancelled, cancel := context.WithCancel(context.Background())
734 cancel()
735 if _, err := Prepare(cancelled, w.g, w.capture(Selection{ID: idA})); !errors.Is(err, context.Canceled) {
736 t.Fatalf("prepare under a cancelled context: %v", err)
737 }
738 ctx, cancel := context.WithCancel(context.Background())
739 p, err := Prepare(ctx, w.g, w.capture(Selection{ID: idA}))
740 if err != nil {
741 t.Fatal(err)
742 }
743 if kept := w.git("for-each-ref", "--format=%(objectname)", keepPrefix); kept != p.Heads[p.Family.Bottom()] {
744 t.Errorf("the prepared head is not kept: %q", kept)
745 }
746 cancel()
747 pub, err := Publish(ctx, w.g, p)
748 if !errors.Is(err, context.Canceled) || pub.Push != Unpushed {
749 t.Fatalf("publish under a cancelled context: %v, %v", err, pub.Push)
750 }
751 if after := w.refs(); after != before {
752 t.Errorf("a cancelled rebase moved something")
753 }
754 if err := p.Release(ctx, w.g); err != nil {
755 t.Fatal(err)
756 }
757 if kept := w.git("for-each-ref", keepPrefix); kept != "" || strings.Count(w.git("worktree", "list", "--porcelain"), "worktree ") != 1 {
758 t.Errorf("the rebase left a ref or a worktree behind: %q", kept)
759 }
760}
761
762// Capture reports each layer's state and refuses nothing a caller could
763// hold instead: a draft and a plain branch are layers, which Check then
764// refuses as the manual rebase does.
765func TestCaptureReportsStatesForTheCallerToHold(t *testing.T) {
766 w := newWorld(t)
767 w.layer("a", "main")
768 w.layer("b", "a")
769 w.layer("c", "b")
770 w.ready(idB, "b")
771 w.ready(idC, "c")
772 w.setState(idB, change.Draft)
773 w.moveMain("main.txt", "main\n")
774
775 f := w.capture(Selection{ID: idC})
776 var states []string
777 for _, l := range f.Layers {
778 states = append(states, string(l.State()))
779 }
780 if got := strings.Join(states, " "); got != "branch draft ready" {
781 t.Fatalf("the states are %q", got)
782 }
783 var r *Refusal
784 if err := f.Check(); !errors.As(err, &r) || r.Kind != NotReady || r.Layer.ID != idB {
785 t.Fatalf("check: %v", err)
786 }
787}