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