gunk-dev/the-valley

rebase.go

source499d9e61dfeemain's published tip history
20.8 KiB
1// valley-go rebase: a change's whole stack, rebased onto main.
2//
3// `valley rebase <change>` and review's [b]ase run it. The stack is what
4// valley-go stack lists (stack.go): the change, and the chain of layers
5// under it, each on the one below. A change with nothing under it is a
6// stack of one, and is rebased the same way.
7//
8// The rebase engine (../rebase) does the work. It captures the chain from
9// one snapshot of origin, refuses a stack it cannot move whole and changes
10// nothing, rebases every layer in one throwaway worktree, bottom first,
11// and publishes in two phases: one atomic push of every layer's branch,
12// leased on the tips it read, and then, bottom first, each change's
13// rebased head added to its record as a new version, as
14// ready --if-active adds one. This verb words what the engine reports. It
15// refuses a stack that holds a change when git config valley.principal
16// names no one, since phase 2 writes each record as that principal.
17//
18// A stack prints a manifest at the end: each layer's old and new head,
19// whether its branch moved, whether a version was added, and the exact
20// valley ready command that finishes each layer left unfinished. A change
21// alone prints what rebase has always printed.
22//
23// An interrupt or a SIGTERM while the stack is rebased cancels the
24// rebase: the engine kills git and anything git started, such as a hook,
25// and removes its worktree and its refs. Nothing is pushed, and the verb
26// exits 130. Review's [b]ase is cancelled by an interrupt alone, and
27// review acts on a SIGTERM once the rebase has ended (review.go).
28
29package main
30
31import (
32 "context"
33 "errors"
34 "fmt"
35 "io"
36 "os"
37 "os/signal"
38 "strings"
39 "sync/atomic"
40 "syscall"
41
42 "the-valley/change"
43 "the-valley/rebase"
44)
45
46const rebaseUsage = "usage: valley-go rebase [--head <sha>] <change>"
47
48// What became of a layer's branch in the push.
49const (
50 pushNot = "not pushed"
51 pushDone = "pushed"
52 pushUnknown = "may have moved"
53)
54
55// errReported is a failure whose words are printed already.
56var errReported = errors.New("reported")
57
58// errInterrupted is a rebase a signal cancelled. It prints nothing, and
59// exits 130.
60var errInterrupted = errors.New("interrupted")
61
62// layer is one line of the manifest: a layer of the stack, and what became
63// of it.
64type layer struct {
65 name string // a change's handle, or a branch's name
66 id string // a change's ID; "" for a plain branch
67 branch string // the branch the rebase pushes
68 head string // the head rebased
69 rebased string // its rebased head
70 pushed string // what became of its branch: pushNot, pushDone or pushUnknown
71 added int // the version phase 2 added, or 0
72}
73
74// rebaseRun is one rebase of a stack.
75type rebaseRun struct {
76 g git
77 s *snapshot
78 f *rebase.Family
79 given string // the name the change was given by
80 stdout, stderr io.Writer
81 signals []os.Signal // what cancels the rebase
82}
83
84// top is the change the stack is under, the last of its layers.
85func (r *rebaseRun) top() *rebase.Layer { return r.f.Start }
86func (r *rebaseRun) single() bool { return len(r.f.Layers) == 1 }
87
88// index is a layer's place in the stack, from 0 at the bottom.
89func (r *rebaseRun) index(l *rebase.Layer) int {
90 for k, m := range r.f.Layers {
91 if m == l {
92 return k
93 }
94 }
95 return -1
96}
97
98// place is where a layer sits, for a refusal that names it: nothing for a
99// change alone, and otherwise ", layer <k> of <n> under <top>,".
100func (r *rebaseRun) place(l *rebase.Layer) string {
101 if r.single() {
102 return ""
103 }
104 return fmt.Sprintf(", layer %d of %d under %s,", r.index(l)+1, len(r.f.Layers), r.top().Name)
105}
106
107func parseRebaseArgs(args []string) (name, want string, err error) {
108 var rest []string
109 for i := 0; i < len(args); i++ {
110 switch a := args[i]; {
111 case a == "--head" && i+1 < len(args):
112 want = args[i+1]
113 i++
114 case strings.HasPrefix(a, "--head="):
115 want = strings.TrimPrefix(a, "--head=")
116 case strings.HasPrefix(a, "-"):
117 return "", "", failure(rebaseUsage)
118 default:
119 rest = append(rest, a)
120 }
121 }
122 if len(rest) != 1 || (want != "" && !isObjectID(want)) {
123 return "", "", failure(rebaseUsage)
124 }
125 return rest[0], want, nil
126}
127
128// runRebase rebases the stack under the change named. --head is the head
129// the caller showed as the change's: the rebase refuses when the change
130// is at another head by now.
131func runRebase(g git, args []string, stdout, stderr io.Writer) int {
132 return rebaseCancelledBy(g, newVerifier(), args, stdout, stderr, os.Interrupt, syscall.SIGTERM)
133}
134
135// rebaseCancelledBy is runRebase, its reads verifying transfer statements
136// with v, cancelled by the signals given.
137func rebaseCancelledBy(g git, v verifier, args []string, stdout, stderr io.Writer, signals ...os.Signal) int {
138 err := rebaseStack(g, v, args, stdout, stderr, signals)
139 switch {
140 case err == nil:
141 return 0
142 case errors.Is(err, errInterrupted):
143 return 130
144 case !errors.Is(err, errReported):
145 fmt.Fprintf(stderr, "valley: %s\n", err)
146 }
147 return 1
148}
149
150func rebaseStack(g git, v verifier, args []string, stdout, stderr io.Writer, signals []os.Signal) error {
151 name, want, err := parseRebaseArgs(args)
152 if err != nil {
153 return err
154 }
155 if !g.succeeds(true, "rev-parse", "--git-dir") {
156 return failure("not a git repository")
157 }
158 res, err := resolveRecorded(g, name)
159 if err != nil {
160 return err
161 }
162 if res.id != "" && res.branch == "" {
163 return failure(fmt.Sprintf("change %s v%d records no branch, and rebase acts on a change's branch. Approve its head alone: valley approve --head %s %s",
164 res.handle, res.version, res.head, res.handle))
165 }
166 s, err := readSnapshot(g, v)
167 if err != nil {
168 return err
169 }
170 if s.tip == "" {
171 return failure("origin has no " + recordTarget + " to rebase onto")
172 }
173 f, err := rebase.Capture(s.land, rebase.Selection{ID: res.id, Branch: res.branch, Head: want})
174 if err != nil {
175 return err
176 }
177 r := &rebaseRun{g: g, s: s, f: f, given: name, stdout: stdout, stderr: stderr, signals: signals}
178 if err := f.Check(); err != nil {
179 return r.refused(err)
180 }
181 // review offers [b]ase only to a stack that is stale. One that
182 // fast-forwards already is left alone, rather than rewritten for
183 // nothing.
184 if top := r.top(); f.FastForwards() {
185 fmt.Fprintf(stdout, "%s already fast-forwards from origin/%s; nothing rebased\n head %s\n", top.Branch, recordTarget, top.Head)
186 return nil
187 }
188 principal, err := r.needPrincipal()
189 if err != nil {
190 return err
191 }
192 eg := g.engine()
193 eg.Stdout = stdout
194 p, err := r.prepare(eg)
195 if err != nil {
196 return err
197 }
198 defer p.Release(context.Background(), eg)
199 pub, err := rebase.Publish(context.Background(), eg, p)
200 if err != nil {
201 return r.refused(err)
202 }
203 return r.publish(eg, pub, principal)
204}
205
206// needPrincipal is the principal git config valley.principal names, and
207// refuses a stack that holds a change when it names no one: phase 2 writes
208// each change's record as that principal, and finding out there would
209// leave every branch moved and no version added.
210func (r *rebaseRun) needPrincipal() (string, error) {
211 changes := false
212 for _, l := range r.f.Layers {
213 changes = changes || l.ID != ""
214 }
215 p, err := r.g.output(true, "config", "valley.principal")
216 if !changes || err == nil && change.ValidPrincipal(p) {
217 return p, nil
218 }
219 what := fmt.Sprintf("rebasing change %s adds the rebased head to its record", r.top().Name)
220 if !r.single() {
221 what = fmt.Sprintf("rebasing the stack under %s adds each change's rebased head to its record", r.top().Name)
222 }
223 return "", failure(what + " as the principal your key pushes as, and git config valley.principal names none, so nothing is rebased; set it with git config valley.principal <name>")
224}
225
226// prepare has the engine rebase every layer, the user's checkout
227// untouched. An interrupt or a SIGTERM meanwhile cancels the rebase, and
228// once the engine has removed its worktree the run ends with
229// errInterrupted.
230func (r *rebaseRun) prepare(eg rebase.Git) (*rebase.Prepared, error) {
231 ctx, cancel := context.WithCancel(context.Background())
232 defer cancel()
233 interrupted := make(chan os.Signal, 1)
234 signal.Notify(interrupted, r.signals...)
235 defer signal.Stop(interrupted)
236 var signalled atomic.Bool
237 done := make(chan struct{})
238 defer close(done)
239 go func() {
240 select {
241 case <-interrupted:
242 signalled.Store(true)
243 cancel()
244 case <-done:
245 }
246 }()
247 p, err := rebase.Prepare(ctx, eg, r.f)
248 if signalled.Load() || errors.Is(err, context.Canceled) || errors.Is(err, rebase.ErrInterrupted) {
249 if p != nil {
250 p.Release(context.Background(), eg)
251 }
252 return nil, errInterrupted
253 }
254 if err != nil {
255 return nil, r.refused(err)
256 }
257 return p, nil
258}
259
260// refused words a refusal the engine gives as valley rebase has always
261// worded it: with the layer's place in the stack, and the command that
262// acts on it. Several are one line each.
263func (r *rebaseRun) refused(err error) error {
264 var many rebase.Refusals
265 if errors.As(err, &many) {
266 var words []string
267 for _, one := range many {
268 words = append(words, r.words(one))
269 }
270 return failure(strings.Join(words, "\nvalley: "))
271 }
272 var one *rebase.Refusal
273 if errors.As(err, &one) {
274 return failure(r.words(one))
275 }
276 return err
277}
278
279func (r *rebaseRun) words(x *rebase.Refusal) string {
280 l := x.Layer
281 switch x.Kind {
282 case rebase.NoBranch:
283 return fmt.Sprintf("change %s v%d%s records no branch, so the rebase has no branch to push it to; nothing rebased",
284 l.Name, l.Version, r.place(l))
285 case rebase.BranchMissing:
286 if r.single() {
287 return "no such branch on origin: " + l.Branch
288 }
289 return fmt.Sprintf("change %s v%d%s is on the branch %s, and origin has no such branch; nothing rebased",
290 l.Name, l.Version, r.place(l), l.Branch)
291 case rebase.NotReady:
292 return fmt.Sprintf("change %s v%d%s is %s, not ready; nothing rebased. Ready it first: %s",
293 l.Name, l.Version, r.place(l), l.Record.State, readyHint(l.ID, l.Branch))
294 case rebase.HeadMoved:
295 if l.ID == "" {
296 return fmt.Sprintf("origin/%s is at %s, and is no longer at %s, the head shown; nothing rebased", l.Branch, l.Head, x.Commit)
297 }
298 return fmt.Sprintf("change %s is at v%d, %s, and this run began at %s; nothing rebased. Review it again at its new head",
299 l.Name, l.Version, l.Head, versionAt(l, x.Commit))
300 case rebase.TipMoved:
301 return fmt.Sprintf("change %s v%d%s records the head %s, and origin/%s is at %s; nothing rebased. Ready the branch's head as a new version of %s to act on it: %s",
302 l.Name, l.Version, r.place(l), l.Head, l.Branch, l.Tip, l.Name, readyCommand(l.Tip, l.ID, l.Branch))
303 case rebase.BranchOfChange:
304 return fmt.Sprintf("change %s v%d records the head %s, and origin/%s%s is at %s; nothing rebased. Ready the branch's head as a new version of %s to act on it: %s",
305 x.Handle, x.Version.N, headOf(x.Version), l.Branch, r.place(l), l.Tip, x.Handle, readyCommand(l.Tip, x.Change.ID, l.Branch))
306 case rebase.SharedBranch:
307 return fmt.Sprintf("%s and %s, layers %d and %d of %d under %s, are both on the branch %s; nothing rebased",
308 x.Other.Name, l.Name, r.index(x.Other)+1, r.index(l)+1, len(r.f.Layers), r.top().Name, l.Branch)
309 case rebase.Conflict:
310 if r.single() {
311 return fmt.Sprintf("%s conflicts with main — resolve by hand; nothing changed", l.Branch)
312 }
313 return fmt.Sprintf("%s, layer %d of %d under %s, conflicts with %s — resolve by hand; nothing changed",
314 l.Name, r.index(l)+1, len(r.f.Layers), r.top().Name, x.Below)
315 case rebase.RecordNotReady:
316 v := x.Change.Record.ActiveVersion()
317 return fmt.Sprintf("change %s v%d%s is %s, not ready; nothing pushed. Ready it first: %s",
318 l.Name, v.N, r.place(l), x.Change.Record.State, readyHint(l.ID, v.Branch))
319 case rebase.RecordNewHead:
320 v := x.Change.Record.ActiveVersion()
321 return fmt.Sprintf("change %s%s is at v%d, %s, and this run began at v%d, %s; nothing pushed. Review it again at its new head",
322 l.Name, r.place(l), v.N, headOf(v), l.Version, l.Head)
323 case rebase.RecordChanged:
324 return fmt.Sprintf("the record of change %s%s changed while it was rebased; nothing pushed. Rebase it again: valley rebase %s",
325 l.Name, r.place(l), r.top().Name)
326 case rebase.BranchUnread:
327 return fmt.Sprintf("could not read %s again against origin's records; nothing pushed", strings.TrimSuffix(r.plainName(l), ","))
328 case rebase.BecameChange:
329 n, h, name := x.Change, x.Handle, r.plainName(l)
330 v := n.Record.ActiveVersion()
331 switch {
332 case n.Record.State != change.Ready:
333 return fmt.Sprintf("%s is now change %s v%d, which is %s, not ready; nothing pushed. Ready it first: %s",
334 name, h, v.N, n.Record.State, readyHint(n.ID, v.Branch))
335 case headOf(v) != l.Head:
336 return fmt.Sprintf("%s is now change %s v%d, which records the head %s, and this run began at %s; nothing pushed. Review it again by its handle",
337 name, h, v.N, headOf(v), l.Head)
338 }
339 return fmt.Sprintf("%s is now change %s v%d; nothing pushed. Rebase it again by its handle: valley rebase %s", name, h, v.N, h)
340 }
341 return x.Error()
342}
343
344// plainName is how a refusal names a plain branch of the stack: as it was
345// given, for a branch alone, and otherwise as origin's, with its place.
346func (r *rebaseRun) plainName(l *rebase.Layer) string {
347 if r.single() {
348 return r.given
349 }
350 return "origin/" + l.Branch + r.place(l)
351}
352
353// versionAt names a head of a change by its version too, when its record
354// has one there.
355func versionAt(l *rebase.Layer, head string) string {
356 for _, v := range l.Record.Versions {
357 if headOf(v) == head {
358 return fmt.Sprintf("v%d, %s", v.N, head)
359 }
360 }
361 return head
362}
363
364// publish says what became of the branch push, adds each change's version
365// when the branches moved, and says what became of each layer.
366func (r *rebaseRun) publish(eg rebase.Git, pub *rebase.Publication, principal string) error {
367 top := r.top()
368 switch pub.Push {
369 case rebase.Refused:
370 if r.single() {
371 return failure(fmt.Sprintf("lease on origin/%s failed (it moved since the fetch); nothing pushed", top.Branch))
372 }
373 r.writeManifest(pub)
374 var why []string
375 for _, ref := range pub.Refused {
376 why = append(why, "origin/"+strings.TrimPrefix(ref.Ref, "refs/heads/")+": "+ref.Why)
377 }
378 return failure(fmt.Sprintf("origin refused the push of the stack's branches, so none moved (%s); nothing pushed. Rebase the stack again: valley rebase %s",
379 strings.Join(why, "; "), top.Name))
380 case rebase.Unknown:
381 r.writeManifest(pub)
382 var refs []string
383 for _, l := range r.f.Layers {
384 refs = append(refs, shellQuote("refs/heads/"+l.Branch))
385 }
386 return failure("the push of the branches failed, and whether origin took it is not known. Check with git ls-remote origin " +
387 strings.Join(refs, " ") + ": a branch at its new head is pushed, and the command above finishes its change")
388 case rebase.Unpushed:
389 return failure("could not run the push of the branches; nothing pushed")
390 }
391 if r.single() {
392 fmt.Fprintf(r.stdout, "rebased %s onto origin/%s, pushed with --force-with-lease\n", top.Branch, recordTarget)
393 fmt.Fprintf(r.stdout, " head %s\n", pub.Result(top).Head)
394 }
395 r.addVersions(eg, pub, principal)
396 if !r.single() {
397 r.writeManifest(pub)
398 }
399 r.otherStacks()
400 n := len(unfinished(r.rows(pub)))
401 switch {
402 case n > 0 && r.single():
403 return errReported
404 case n == 1:
405 return failure(fmt.Sprintf("1 change of the stack under %s is unfinished; finish it with the command above", top.Name))
406 case n > 0:
407 return failure(fmt.Sprintf("%d changes of the stack under %s are unfinished; finish each with the command above", n, top.Name))
408 }
409 return nil
410}
411
412// addVersions is phase 2: bottom first, each change's rebased head is
413// added to its record as a new version, while the change is still ready
414// at the head the rebase began with. A change alone says what ready says,
415// as it always has.
416func (r *rebaseRun) addVersions(eg rebase.Git, pub *rebase.Publication, principal string) {
417 for _, res := range pub.Results {
418 l := res.Layer
419 if l.ID == "" {
420 continue
421 }
422 pub.Append(context.Background(), eg, principal, res)
423 if ap := res.Appended; ap.Err != nil {
424 fmt.Fprintf(r.stderr, "valley: %s\n", ap.Err)
425 if r.single() {
426 fmt.Fprintf(r.stderr, "valley: origin/%s is rebased to %s, and no version of %s records it. Ready it once the change is ready: %s\n",
427 l.Branch, res.Head, l.Name, readyCommand(res.Head, l.ID, l.Branch))
428 }
429 } else if r.single() {
430 fmt.Fprintf(r.stdout, "%s %s v%d ready\n", project(r.g), ap.Handle, ap.Version)
431 }
432 }
433}
434
435// rows is the manifest's line for each layer, bottom first.
436func (r *rebaseRun) rows(pub *rebase.Publication) []*layer {
437 var rows []*layer
438 for _, res := range pub.Results {
439 l := res.Layer
440 row := &layer{name: l.Name, id: l.ID, branch: l.Branch, head: l.Head, rebased: res.Head, pushed: pushNot}
441 switch res.Branch {
442 case rebase.Pushed:
443 row.pushed = pushDone
444 case rebase.Unknown:
445 row.pushed = pushUnknown
446 }
447 if res.Appended != nil {
448 row.added = res.Appended.Version
449 }
450 rows = append(rows, row)
451 }
452 return rows
453}
454
455// unfinished is each change layer whose branch may hold its rebased head
456// with no version recording it.
457func unfinished(layers []*layer) []*layer {
458 var left []*layer
459 for _, l := range layers {
460 if l.id != "" && l.pushed != pushNot && l.added == 0 {
461 left = append(left, l)
462 }
463 }
464 return left
465}
466
467func (r *rebaseRun) writeManifest(pub *rebase.Publication) {
468 io.WriteString(r.stdout, manifest(r.top().Name, r.rows(pub)))
469}
470
471// manifest is what the rebase did to each layer, bottom first, one line
472// each: its old and new head, what became of its branch, and for a change
473// whether a version was added. Then, for each change left unfinished, the
474// valley ready command that finishes it.
475func manifest(top string, layers []*layer) string {
476 var b strings.Builder
477 fmt.Fprintf(&b, "the stack under %s, bottom first:\n", top)
478 width := 0
479 for _, l := range layers {
480 width = max(width, columns(l.name))
481 }
482 for _, l := range layers {
483 rebased := "(not rebased)"
484 if l.rebased != "" {
485 rebased = short(l.rebased)
486 }
487 status := "origin/" + l.branch + " " + l.pushed
488 switch {
489 case l.id != "" && l.added > 0:
490 status += fmt.Sprintf(", v%d added", l.added)
491 case l.id != "":
492 status += ", no version added"
493 }
494 fmt.Fprintf(&b, " %s%s %s -> %s %s\n", l.name, strings.Repeat(" ", width-columns(l.name)), short(l.head), rebased, status)
495 }
496 for _, l := range unfinished(layers) {
497 fmt.Fprintf(&b, "to finish %s: %s\n", l.name, readyCommand(l.rebased, l.id, l.branch))
498 }
499 return b.String()
500}
501
502// otherStacks names each ready change and plain branch outside the stack
503// whose head contains a layer's old head, such as a second stack on a
504// lower layer. The rebase left it on that old head, and does not move it.
505func (r *rebaseRun) otherStacks() {
506 ids, branches := map[string]bool{}, map[string]bool{}
507 for _, l := range r.f.Layers {
508 ids[l.ID], branches[l.Branch] = true, true
509 }
510 on := func(head string) *rebase.Layer {
511 for k := len(r.f.Layers) - 1; k >= 0; k-- {
512 if l := r.f.Layers[k]; head == l.Head || r.s.reach(head)[l.Head] {
513 return l
514 }
515 }
516 return nil
517 }
518 for _, n := range r.s.all {
519 if ids[n.id] || n.record.State != change.Ready || !unlanded(r.s, n) {
520 continue
521 }
522 if l := on(headOf(n.record.ActiveVersion())); l != nil {
523 h := r.s.o.handle(n.id)
524 fmt.Fprintf(r.stdout, "%s is now on an old head of %s; rebase it with valley rebase %s\n", h, l.Name, h)
525 }
526 }
527 for _, b := range r.s.unrecorded() {
528 if l := on(b.Head); l != nil && !branches[b.Branch] {
529 fmt.Fprintf(r.stdout, "%s is now on an old head of %s; rebase it with valley rebase %s\n", branchName(b.Branch), l.Name, shellQuote(b.Branch))
530 }
531 }
532}
533
534// readyHint is the valley ready line that readies a change again, naming
535// the branch unless its version records none, as bin/valley's ready_hint
536// writes it.
537func readyHint(id, branch string) string {
538 if branch == "" {
539 return "valley ready --change " + id
540 }
541 return "valley ready --change " + id + " " + shellQuote(branch)
542}
543
544// readyCommand is the valley ready line that adds head to a change's
545// record as a new version on branch.
546func readyCommand(head, id, branch string) string {
547 return "valley ready --head " + head + " --change " + id + " " + shellQuote(branch)
548}
549
550// bringsOf is the handle of each change that has not landed, other than
551// except, with a version head among the commits head would bring to
552// main: those it reaches and main does not, in the order of the changes'
553// IDs. approve refuses a head that does not fast-forward from main and
554// would bring one, since it is a layer of a stack that has to be rebased
555// first.
556func bringsOf(g git, v verifier, except, head string) ([]string, error) {
557 if !g.succeeds(true, "cat-file", "-e", head+"^{commit}") {
558 return nil, failure("no commit " + head + " here")
559 }
560 s, err := readSnapshot(g, v)
561 if err != nil {
562 return nil, err
563 }
564 if s.tip == "" {
565 return nil, failure("origin has no " + recordTarget + " to read against")
566 }
567 reach := s.reach(head)
568 var handles []string
569 for _, n := range s.all {
570 if n.id == except || !unlanded(s, n) {
571 continue
572 }
573 for _, v := range n.record.Versions {
574 if reach[headOf(v)] {
575 handles = append(handles, s.o.handle(n.id))
576 break
577 }
578 }
579 }
580 return handles, nil
581}