gunk-dev/the-valley

rebase.go

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