gunk-dev/the-valley

family.go

source68d12192bbd3main's published tip history
19.5 KiB
1// A family of layers, captured from one snapshot of origin.
2//
3// A layer is a change whose active version has not landed, in any state,
4// or a branch on origin that no record is on, that main does not reach,
5// and that no landed version's head reaches (Snapshot.Unrecorded).
6// Each layer sits on its base: the nearest layer its head strictly
7// contains, as valley pending nests its entries (Snapshot.Nest). A layer
8// with no base sits on main. Linear history gives every layer at most one
9// base, so the layers on a bottom layer form a tree: one chain, as in
10// A → B → C, or a shared lower layer with several children, as in A → B
11// and A → C. That tree is a family.
12//
13// Capture reads a family and every layer's state, and refuses nothing a
14// caller could choose to hold instead: a draft, a withdrawn change, a
15// plain branch, a change that may have landed. Check then refuses what the
16// engine cannot rebase whole:
17//
18// - a change layer is not ready, names no branch, or its branch is
19// missing on origin or not at its recorded head;
20// - a plain branch in the family is the branch of a change that is no
21// layer, as a change is once a rebase has moved its branch and could
22// not add the rebased head to its record;
23// - two layers are on one branch;
24// - the commits to be rebased under a top layer hold a merge, or a
25// version head of a change that is not ready or is no layer of that
26// top's chain. A rebase gives every commit a new ID, so such a commit
27// would ride into the family under an ID no version records. That is
28// the rule the integrator lands by (integrator/records.go), applied
29// before the rebase.
30//
31// Commits under the bottom that a lower change landed drop out of the
32// rebase: the integrator landed them as one new commit, so their content
33// is on main already though main does not reach them. They are the commits
34// a landed version's head reaches.
35
36package rebase
37
38import (
39 "fmt"
40 "sort"
41 "strconv"
42 "strings"
43
44 "the-valley/change"
45)
46
47// State is what a layer is, for a caller deciding whether to move it.
48type State string
49
50const (
51 Ready State = "ready" // a ready change
52 Draft State = "draft" // a change its owner paused
53 Withdrawn State = "withdrawn" // a change its owner withdrew
54 Plain State = "branch" // a branch no record is on
55 Submitted State = "submitted" // a change that has landed as any version
56 Uncertain State = "uncertain" // a change whose active version may have landed, with no evidence either way
57)
58
59// Layer is one layer of a family as captured.
60type Layer struct {
61 Name string // a change's handle, or a branch's name
62 ID string // a change's ID; "" for a plain branch
63 Branch string // the branch a rebase pushes: the active version's, or the plain branch
64 Tip string // that branch's tip on origin as captured; "" when it is missing
65
66 // A change's record as captured: its ref and commit, the record, and
67 // the number of its active version.
68 Ref, Commit string
69 Record *change.Record
70 Version int
71
72 Head string // the head rebased: the active version's, or the branch's tip
73 Base string // the commit its own commits start above; set by Check
74 Landing string // a change's active version's landing evidence; "" for a plain branch
75 When int64 // its head's commit time
76
77 Below *Layer // the layer it sits on; nil for the bottom
78 Above []*Layer // the layers that sit on it
79}
80
81// State is what the layer is: a plain branch, a change that has landed or
82// may have, or else its record's state.
83func (l *Layer) State() State {
84 switch {
85 case l.ID == "":
86 return Plain
87 case l.Landing == Landed || l.Landing == LandedRecorded:
88 return Submitted
89 case l.Landing == LandingUncertain:
90 return Uncertain
91 }
92 return State(l.Record.State)
93}
94
95// Family is a tree of layers on one bottom layer, as captured from one
96// snapshot.
97type Family struct {
98 Tip string // main on origin as captured: what the family is rebased onto
99 Layers []*Layer // bottom first, every layer after the layer below it
100 Start *Layer // the layer the capture started from
101
102 // Cut is the head of each landed version under the bottom: the
103 // commits they reach drop out of the rebase. Set by Check.
104 Cut []string
105
106 s *Snapshot
107 want string
108 checked bool
109 err error
110}
111
112// Bottom is the layer every other layer of the family sits on.
113func (f *Family) Bottom() *Layer { return f.Layers[0] }
114
115// Tops is every layer nothing sits on, in the family's order.
116func (f *Family) Tops() []*Layer {
117 var tops []*Layer
118 for _, l := range f.Layers {
119 if len(l.Above) == 0 {
120 tops = append(tops, l)
121 }
122 }
123 return tops
124}
125
126// FastForwards reports whether the family already fast-forwards from
127// main: whether its bottom's head contains main's tip, so a rebase would
128// change nothing.
129func (f *Family) FastForwards() bool {
130 return f.s.g.succeeds(f.s.ctx, true, "merge-base", "--is-ancestor", f.Tip, f.Bottom().Head)
131}
132
133// Selection is where a capture starts, and how much of the family it
134// takes.
135type Selection struct {
136 ID string // the change the capture starts from, or
137 Branch string // the plain branch it starts from
138
139 // Whole takes every layer connected to the start: the layers under it,
140 // the layers on them, and so on. Otherwise the capture takes the start
141 // and the chain of layers under it, which is what valley rebase moves.
142 Whole bool
143
144 // Head, when set, is the head the caller showed as the start's: Check
145 // refuses the family when the start is at another head by now.
146 Head string
147}
148
149// Capture reads the family a selection names from the snapshot. The only
150// refusals are a start that origin no longer holds.
151func Capture(s *Snapshot, sel Selection) (*Family, error) {
152 var start *Layer
153 if sel.ID != "" {
154 for _, n := range s.Changes {
155 if n.ID == sel.ID {
156 start = s.changeLayer(n)
157 }
158 }
159 if start == nil {
160 return nil, &Refusal{Kind: Gone, Name: s.Handle(sel.ID)}
161 }
162 } else {
163 head := s.Refs["refs/heads/"+sel.Branch]
164 if head == "" {
165 return nil, &Refusal{Kind: StartMissing, Name: sel.Branch}
166 }
167 start = &Layer{Name: sel.Branch, Branch: sel.Branch, Head: head}
168 }
169 // A chain is the start and what its head contains, so only they are
170 // measured. A whole family is found among every layer there is.
171 contains := func(head string) bool { return sel.Whole || s.StrictAncestor(head, start.Head) }
172 all := []*Layer{start}
173 for _, n := range s.Changes {
174 if n.ID != start.ID && s.Unlanded(n) && contains(HeadOf(n.Record.ActiveVersion())) {
175 all = append(all, s.changeLayer(n))
176 }
177 }
178 for _, b := range s.Unrecorded() {
179 if b.Branch != start.Name && contains(b.Head) {
180 all = append(all, &Layer{Name: b.Branch, Branch: b.Branch, Head: b.Head})
181 }
182 }
183 nodes := make([]Node, len(all))
184 for i, l := range all {
185 out, _ := s.g.output(s.ctx, true, "log", "-1", "--format=%ct", l.Head)
186 l.When, _ = strconv.ParseInt(out, 10, 64)
187 if l.Branch != "" {
188 l.Tip = s.Refs["refs/heads/"+l.Branch]
189 }
190 nodes[i] = Node{Name: l.Name, Head: l.Head, When: l.When}
191 }
192 nest := s.Nest(nodes)
193 var keep []*Layer
194 if sel.Whole {
195 keep = connected(all, nest.Base)
196 } else {
197 for i := 0; i >= 0; i = nest.Base[i] {
198 keep = append([]*Layer{all[i]}, keep...)
199 }
200 }
201 index := map[*Layer]int{}
202 for i, l := range all {
203 index[l] = i
204 }
205 member := map[*Layer]bool{}
206 for _, l := range keep {
207 member[l] = true
208 }
209 for _, l := range keep {
210 if b := nest.Base[index[l]]; b >= 0 && member[all[b]] {
211 l.Below = all[b]
212 l.Below.Above = append(l.Below.Above, l)
213 }
214 }
215 f := &Family{Tip: s.Tip, Start: start, s: s, want: sel.Head}
216 f.Layers = order(keep)
217 return f, nil
218}
219
220// changeLayer is a change as a layer: its handle, its record, its active
221// version's head and branch, and how far that version has landed, or the
222// version the change landed as has (LandedAs).
223func (s *Snapshot) changeLayer(n Recorded) *Layer {
224 v := n.Record.ActiveVersion()
225 landing, _ := s.Landing(n.ID, v)
226 if as, landed := s.LandedAs(n); landed {
227 landing, _ = s.Landing(n.ID, as)
228 }
229 return &Layer{
230 Name: s.Handle(n.ID), ID: n.ID, Branch: v.Branch,
231 Ref: change.Ref(Target, n.ID), Commit: n.Commit, Record: n.Record, Version: v.N,
232 Head: HeadOf(v), Landing: landing,
233 }
234}
235
236// connected is the layers joined to the first of all through the bases
237// given: the first's bottom, and every layer on that bottom.
238func connected(all []*Layer, base []int) []*Layer {
239 root := func(i int) int {
240 for base[i] >= 0 {
241 i = base[i]
242 }
243 return i
244 }
245 r := root(0)
246 var keep []*Layer
247 for i := range all {
248 if root(i) == r {
249 keep = append(keep, all[i])
250 }
251 }
252 return keep
253}
254
255// order puts a family bottom first, then breadth first, each layer's
256// children in the order of their names.
257func order(layers []*Layer) []*Layer {
258 var bottom *Layer
259 for _, l := range layers {
260 if l.Below == nil {
261 bottom = l
262 }
263 }
264 out := []*Layer{bottom}
265 for i := 0; i < len(out); i++ {
266 above := out[i].Above
267 sort.SliceStable(above, func(a, b int) bool { return above[a].Name < above[b].Name })
268 out = append(out, above...)
269 }
270 return out
271}
272
273// Check refuses a family the engine cannot rebase whole, before anything
274// is rebased, and finds where each layer's own commits start: for the
275// bottom, the parent of its oldest commit; for every other layer, the
276// head of the layer below. It returns a *Refusal, or Refusals when every
277// layer's branch was read and several were refused. It checks once, and
278// gives the same answer when asked again.
279func (f *Family) Check() error {
280 if !f.checked {
281 f.checked, f.err = true, f.check()
282 }
283 return f.err
284}
285
286func (f *Family) check() error {
287 var tips Refusals // the branches not at their changes' recorded heads
288 in := map[string]bool{}
289 for _, l := range f.Layers {
290 if l.ID != "" {
291 in[l.ID] = true
292 }
293 }
294 for _, l := range f.Layers {
295 switch {
296 case l.ID != "" && l.Branch == "":
297 return &Refusal{Kind: NoBranch, Layer: l}
298 case l.Tip == "":
299 return &Refusal{Kind: BranchMissing, Layer: l}
300 case l.ID != "" && l.Record.State != change.Ready:
301 return &Refusal{Kind: NotReady, Layer: l}
302 case l == f.Start && f.want != "" && l.Head != f.want:
303 return &Refusal{Kind: HeadMoved, Layer: l, Commit: f.want}
304 case l.ID != "" && l.Tip != l.Head:
305 tips = append(tips, &Refusal{Kind: TipMoved, Layer: l})
306 }
307 if l.ID != "" {
308 continue
309 }
310 // A plain branch that is a change's branch holds a head no version
311 // of that change records, as after a rebase that moved the branch
312 // and could not add the version.
313 for _, n := range f.s.Changes {
314 v := n.Record.ActiveVersion()
315 if in[n.ID] || v.Branch != l.Branch || !f.s.Unlanded(n) {
316 continue
317 }
318 tips = append(tips, f.s.about(&Refusal{Kind: BranchOfChange, Layer: l, Version: v}, n))
319 }
320 }
321 // Two layers on one branch leave a change's branch off its recorded
322 // head as well, so they are refused first, for what they are.
323 on := map[string]*Layer{}
324 for _, l := range f.Layers {
325 if o := on[l.Branch]; o != nil {
326 return &Refusal{Kind: SharedBranch, Layer: l, Other: o}
327 }
328 on[l.Branch] = l
329 }
330 if len(tips) > 0 {
331 return tips
332 }
333 return f.commits()
334}
335
336// commits reads the commits the rebase moves, top by top: those each
337// top's head reaches, less those main reaches and those a landed
338// version's head reaches under the bottom. It refuses a merge among them,
339// and a version head of a change that is not ready or is not on that
340// top's chain. It sets each layer's base.
341func (f *Family) commits() error {
342 s, bottom := f.s, f.Bottom()
343 not := []string{"^" + f.Tip}
344 for _, h := range s.LandedUnder(bottom.Head) {
345 not, f.Cut = append(not, "^"+h), append(f.Cut, h)
346 }
347 for _, top := range f.Tops() {
348 chain := map[string]bool{}
349 for l := top; l != nil; l = l.Below {
350 if l.ID != "" {
351 chain[l.ID] = true
352 }
353 }
354 out, err := s.g.output(s.ctx, true, append([]string{"rev-list", "--parents", top.Head}, not...)...)
355 if err != nil {
356 return &Refusal{Kind: StackUnread, Layer: top}
357 }
358 moved := map[string]bool{}
359 for _, line := range strings.Split(out, "\n") {
360 fields := strings.Fields(line)
361 if len(fields) > 2 {
362 return &Refusal{Kind: Merge, Layer: top, Commit: fields[0]}
363 }
364 if len(fields) > 0 {
365 moved[fields[0]] = true
366 }
367 }
368 for _, n := range s.Changes {
369 for _, v := range n.Record.Versions {
370 c := HeadOf(v)
371 if !moved[c] || (chain[n.ID] && n.Record.State == change.Ready) {
372 continue
373 }
374 return s.about(&Refusal{Kind: ForeignHead, Layer: top, Version: v, Commit: c}, n)
375 }
376 }
377 }
378 out, err := s.g.output(s.ctx, true, append([]string{"rev-list", "--parents", "--reverse", bottom.Head}, not...)...)
379 if err != nil {
380 return &Refusal{Kind: LayerUnread, Layer: bottom}
381 }
382 bottom.Base = bottom.Head
383 if oldest, _, _ := strings.Cut(out, "\n"); oldest != "" {
384 fields := strings.Fields(oldest)
385 if len(fields) < 2 {
386 return &Refusal{Kind: NoHistory, Layer: bottom}
387 }
388 bottom.Base = fields[1]
389 }
390 for _, l := range f.Layers[1:] {
391 l.Base = l.Below.Head
392 }
393 return nil
394}
395
396// Kind is what a refusal is about.
397type Kind int
398
399const (
400 // Capture: the start is gone from origin.
401 Gone Kind = iota + 1 // the start's record
402 StartMissing // the start's branch
403
404 // Check.
405 NoBranch // a change layer records no branch
406 BranchMissing // a layer's branch is missing on origin
407 NotReady // a change layer is not ready
408 HeadMoved // the start is no longer at Selection.Head, which Commit holds
409 TipMoved // a change layer's branch is not at its recorded head
410 BranchOfChange // a plain branch is the branch of Change, which is no layer
411 SharedBranch // Layer and Other are on one branch
412 StackUnread // the commits under a top could not be read
413 LayerUnread // the bottom's commits could not be read
414 Merge // the commits under a top hold the merge Commit
415 ForeignHead // the commit Commit under a top is Version of Change, which is not ready or not on that top's chain
416 NoHistory // the bottom shares no history with main
417
418 // Prepare: nothing is pushed.
419 NoWorktree // no directory could be made for the rebase
420 NoCheckout // the bottom could not be checked out
421 Conflict // a layer conflicts with what it is rebased onto
422 NoNewHead // a layer's rebased head could not be read
423 EmptyLayer // a layer adds nothing once rebased
424
425 // Publish, read again just before the push: nothing is pushed.
426 OriginUnread // origin could not be read again
427 RecordGone // a change layer's record is gone
428 RecordUnread // a change layer's moved record could not be read
429 RecordNotReady // a change layer's record, now Change, is not ready
430 RecordNewHead // a change layer's record, now Change, is at another head
431 RecordChanged // a change layer's record, now Change, changed otherwise
432 BranchUnread // a plain branch could not be read against origin's records
433 BecameChange // a plain branch is now the branch of Change
434)
435
436// Refusal is why a family cannot be rebased whole. The step that returns
437// one has changed nothing on origin.
438type Refusal struct {
439 Kind Kind
440 Name string // Gone and StartMissing: the start's handle or branch
441 Layer *Layer // the layer it is about
442 Other *Layer // SharedBranch: the layer below on the same branch
443
444 // The change it is about, other than the layer itself, and the
445 // version concerned.
446 Change *Recorded
447 Version change.Version
448
449 Handle string // the handle of Change
450
451 Commit string // HeadMoved, Merge, ForeignHead: the commit concerned
452 Paths []string // Conflict: every path that conflicted, in git's order
453 Below string // Conflict and EmptyLayer: what the layer was rebased onto, by name
454}
455
456func (r *Refusal) Error() string {
457 l := r.Layer
458 switch r.Kind {
459 case Gone:
460 return "origin no longer holds a record of change " + r.Name
461 case StartMissing:
462 return "no such branch on origin: " + r.Name
463 case NoBranch:
464 return fmt.Sprintf("change %s v%d records no branch, so the rebase has no branch to push it to; nothing rebased", l.Name, l.Version)
465 case BranchMissing:
466 return fmt.Sprintf("%s is on the branch %s, and origin has no such branch; nothing rebased", l.Name, l.Branch)
467 case NotReady:
468 return fmt.Sprintf("change %s v%d is %s, not ready; nothing rebased", l.Name, l.Version, l.Record.State)
469 case HeadMoved:
470 return fmt.Sprintf("%s is at %s, and the head given was %s; nothing rebased", l.Name, l.Head, r.Commit)
471 case TipMoved:
472 return fmt.Sprintf("change %s v%d records the head %s, and origin/%s is at %s; nothing rebased", l.Name, l.Version, l.Head, l.Branch, l.Tip)
473 case BranchOfChange:
474 return fmt.Sprintf("change %s v%d records the head %s, and origin/%s is at %s; nothing rebased", r.Handle, r.Version.N, HeadOf(r.Version), l.Branch, l.Tip)
475 case SharedBranch:
476 return fmt.Sprintf("%s and %s are both on the branch %s; nothing rebased", r.Other.Name, l.Name, l.Branch)
477 case StackUnread:
478 return fmt.Sprintf("could not read the commits under %s; nothing rebased", l.Name)
479 case LayerUnread:
480 return fmt.Sprintf("could not read the commits of %s; nothing rebased", l.Name)
481 case Merge:
482 return fmt.Sprintf("the commits under %s include the merge %s, and a rebase moves a line of commits; nothing rebased", l.Name, short(r.Commit))
483 case ForeignHead:
484 h, why := r.Handle, "which is no layer of this stack"
485 if r.Change.Record.State != change.Ready {
486 why = fmt.Sprintf("which is %s, not ready", r.Change.Record.State)
487 }
488 return fmt.Sprintf("the commit %s under %s is v%d of change %s, %s; nothing rebased. A rebase gives each commit a new ID, which no version of %s would record",
489 short(r.Commit), l.Name, r.Version.N, h, why, h)
490 case NoHistory:
491 return fmt.Sprintf("%s and %s share no history; nothing rebased", l.Name, Target)
492 case NoWorktree:
493 return "could not make a directory for the rebase; nothing changed"
494 case NoCheckout:
495 return fmt.Sprintf("could not check out origin/%s for the rebase; nothing changed", l.Branch)
496 case Conflict:
497 return fmt.Sprintf("%s conflicts with %s; nothing changed", l.Name, r.Below)
498 case NoNewHead:
499 return fmt.Sprintf("could not read the rebased head of %s; nothing pushed", l.Branch)
500 case EmptyLayer:
501 return fmt.Sprintf("%s adds nothing to %s once rebased, as when its commits have landed already; nothing pushed", l.Name, r.Below)
502 case OriginUnread:
503 return "could not read origin again before the push; nothing pushed"
504 case RecordGone:
505 return fmt.Sprintf("origin no longer holds a record of change %s; nothing pushed", l.Name)
506 case RecordUnread:
507 return fmt.Sprintf("could not read the record of change %s again; nothing pushed", l.Name)
508 case RecordNotReady:
509 v := r.Change.Record.ActiveVersion()
510 return fmt.Sprintf("change %s v%d is %s, not ready; nothing pushed", l.Name, v.N, r.Change.Record.State)
511 case RecordNewHead:
512 v := r.Change.Record.ActiveVersion()
513 return fmt.Sprintf("change %s is at v%d, %s, and the rebase began at v%d, %s; nothing pushed", l.Name, v.N, HeadOf(v), l.Version, l.Head)
514 case RecordChanged:
515 return fmt.Sprintf("the record of change %s changed while it was rebased; nothing pushed", l.Name)
516 case BranchUnread:
517 return fmt.Sprintf("could not read origin/%s again against origin's records; nothing pushed", l.Branch)
518 case BecameChange:
519 return fmt.Sprintf("origin/%s is now change %s; nothing pushed", l.Branch, r.Handle)
520 }
521 return fmt.Sprintf("refusal %d", r.Kind)
522}
523
524// about is a refusal about the change n, other than its layer.
525func (s *Snapshot) about(r *Refusal, n Recorded) *Refusal {
526 r.Change, r.Handle = &Recorded{ID: n.ID, Commit: n.Commit, Record: n.Record}, s.Handle(n.ID)
527 return r
528}
529
530// Refusals are several refusals found together: Check reads every layer's
531// branch before it refuses those not at their changes' heads.
532type Refusals []*Refusal
533
534func (rs Refusals) Error() string {
535 var words []string
536 for _, r := range rs {
537 words = append(words, r.Error())
538 }
539 return strings.Join(words, "\n")
540}