gunk-dev/the-valley

rebase.go

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