gunk-dev/the-valley

family.go

sourcea4ba77eaef6dmain's published tip history
19.4 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 whose active version has landed
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.
222func (s *Snapshot) changeLayer(n Recorded) *Layer {
223 v := n.Record.ActiveVersion()
224 landing, _ := s.Landing(n.ID, v)
225 return &Layer{
226 Name: s.Handle(n.ID), ID: n.ID, Branch: v.Branch,
227 Ref: change.Ref(Target, n.ID), Commit: n.Commit, Record: n.Record, Version: v.N,
228 Head: HeadOf(v), Landing: landing,
229 }
230}
231
232// connected is the layers joined to the first of all through the bases
233// given: the first's bottom, and every layer on that bottom.
234func connected(all []*Layer, base []int) []*Layer {
235 root := func(i int) int {
236 for base[i] >= 0 {
237 i = base[i]
238 }
239 return i
240 }
241 r := root(0)
242 var keep []*Layer
243 for i := range all {
244 if root(i) == r {
245 keep = append(keep, all[i])
246 }
247 }
248 return keep
249}
250
251// order puts a family bottom first, then breadth first, each layer's
252// children in the order of their names.
253func order(layers []*Layer) []*Layer {
254 var bottom *Layer
255 for _, l := range layers {
256 if l.Below == nil {
257 bottom = l
258 }
259 }
260 out := []*Layer{bottom}
261 for i := 0; i < len(out); i++ {
262 above := out[i].Above
263 sort.SliceStable(above, func(a, b int) bool { return above[a].Name < above[b].Name })
264 out = append(out, above...)
265 }
266 return out
267}
268
269// Check refuses a family the engine cannot rebase whole, before anything
270// is rebased, and finds where each layer's own commits start: for the
271// bottom, the parent of its oldest commit; for every other layer, the
272// head of the layer below. It returns a *Refusal, or Refusals when every
273// layer's branch was read and several were refused. It checks once, and
274// gives the same answer when asked again.
275func (f *Family) Check() error {
276 if !f.checked {
277 f.checked, f.err = true, f.check()
278 }
279 return f.err
280}
281
282func (f *Family) check() error {
283 var tips Refusals // the branches not at their changes' recorded heads
284 in := map[string]bool{}
285 for _, l := range f.Layers {
286 if l.ID != "" {
287 in[l.ID] = true
288 }
289 }
290 for _, l := range f.Layers {
291 switch {
292 case l.ID != "" && l.Branch == "":
293 return &Refusal{Kind: NoBranch, Layer: l}
294 case l.Tip == "":
295 return &Refusal{Kind: BranchMissing, Layer: l}
296 case l.ID != "" && l.Record.State != change.Ready:
297 return &Refusal{Kind: NotReady, Layer: l}
298 case l == f.Start && f.want != "" && l.Head != f.want:
299 return &Refusal{Kind: HeadMoved, Layer: l, Commit: f.want}
300 case l.ID != "" && l.Tip != l.Head:
301 tips = append(tips, &Refusal{Kind: TipMoved, Layer: l})
302 }
303 if l.ID != "" {
304 continue
305 }
306 // A plain branch that is a change's branch holds a head no version
307 // of that change records, as after a rebase that moved the branch
308 // and could not add the version.
309 for _, n := range f.s.Changes {
310 v := n.Record.ActiveVersion()
311 if in[n.ID] || v.Branch != l.Branch || !f.s.Unlanded(n) {
312 continue
313 }
314 tips = append(tips, f.s.about(&Refusal{Kind: BranchOfChange, Layer: l, Version: v}, n))
315 }
316 }
317 // Two layers on one branch leave a change's branch off its recorded
318 // head as well, so they are refused first, for what they are.
319 on := map[string]*Layer{}
320 for _, l := range f.Layers {
321 if o := on[l.Branch]; o != nil {
322 return &Refusal{Kind: SharedBranch, Layer: l, Other: o}
323 }
324 on[l.Branch] = l
325 }
326 if len(tips) > 0 {
327 return tips
328 }
329 return f.commits()
330}
331
332// commits reads the commits the rebase moves, top by top: those each
333// top's head reaches, less those main reaches and those a landed
334// version's head reaches under the bottom. It refuses a merge among them,
335// and a version head of a change that is not ready or is not on that
336// top's chain. It sets each layer's base.
337func (f *Family) commits() error {
338 s, bottom := f.s, f.Bottom()
339 not := []string{"^" + f.Tip}
340 for _, h := range s.LandedUnder(bottom.Head) {
341 not, f.Cut = append(not, "^"+h), append(f.Cut, h)
342 }
343 for _, top := range f.Tops() {
344 chain := map[string]bool{}
345 for l := top; l != nil; l = l.Below {
346 if l.ID != "" {
347 chain[l.ID] = true
348 }
349 }
350 out, err := s.g.output(s.ctx, true, append([]string{"rev-list", "--parents", top.Head}, not...)...)
351 if err != nil {
352 return &Refusal{Kind: StackUnread, Layer: top}
353 }
354 moved := map[string]bool{}
355 for _, line := range strings.Split(out, "\n") {
356 fields := strings.Fields(line)
357 if len(fields) > 2 {
358 return &Refusal{Kind: Merge, Layer: top, Commit: fields[0]}
359 }
360 if len(fields) > 0 {
361 moved[fields[0]] = true
362 }
363 }
364 for _, n := range s.Changes {
365 for _, v := range n.Record.Versions {
366 c := HeadOf(v)
367 if !moved[c] || (chain[n.ID] && n.Record.State == change.Ready) {
368 continue
369 }
370 return s.about(&Refusal{Kind: ForeignHead, Layer: top, Version: v, Commit: c}, n)
371 }
372 }
373 }
374 out, err := s.g.output(s.ctx, true, append([]string{"rev-list", "--parents", "--reverse", bottom.Head}, not...)...)
375 if err != nil {
376 return &Refusal{Kind: LayerUnread, Layer: bottom}
377 }
378 bottom.Base = bottom.Head
379 if oldest, _, _ := strings.Cut(out, "\n"); oldest != "" {
380 fields := strings.Fields(oldest)
381 if len(fields) < 2 {
382 return &Refusal{Kind: NoHistory, Layer: bottom}
383 }
384 bottom.Base = fields[1]
385 }
386 for _, l := range f.Layers[1:] {
387 l.Base = l.Below.Head
388 }
389 return nil
390}
391
392// Kind is what a refusal is about.
393type Kind int
394
395const (
396 // Capture: the start is gone from origin.
397 Gone Kind = iota + 1 // the start's record
398 StartMissing // the start's branch
399
400 // Check.
401 NoBranch // a change layer records no branch
402 BranchMissing // a layer's branch is missing on origin
403 NotReady // a change layer is not ready
404 HeadMoved // the start is no longer at Selection.Head, which Commit holds
405 TipMoved // a change layer's branch is not at its recorded head
406 BranchOfChange // a plain branch is the branch of Change, which is no layer
407 SharedBranch // Layer and Other are on one branch
408 StackUnread // the commits under a top could not be read
409 LayerUnread // the bottom's commits could not be read
410 Merge // the commits under a top hold the merge Commit
411 ForeignHead // the commit Commit under a top is Version of Change, which is not ready or not on that top's chain
412 NoHistory // the bottom shares no history with main
413
414 // Prepare: nothing is pushed.
415 NoWorktree // no directory could be made for the rebase
416 NoCheckout // the bottom could not be checked out
417 Conflict // a layer conflicts with what it is rebased onto
418 NoNewHead // a layer's rebased head could not be read
419 EmptyLayer // a layer adds nothing once rebased
420
421 // Publish, read again just before the push: nothing is pushed.
422 OriginUnread // origin could not be read again
423 RecordGone // a change layer's record is gone
424 RecordUnread // a change layer's moved record could not be read
425 RecordNotReady // a change layer's record, now Change, is not ready
426 RecordNewHead // a change layer's record, now Change, is at another head
427 RecordChanged // a change layer's record, now Change, changed otherwise
428 BranchUnread // a plain branch could not be read against origin's records
429 BecameChange // a plain branch is now the branch of Change
430)
431
432// Refusal is why a family cannot be rebased whole. The step that returns
433// one has changed nothing on origin.
434type Refusal struct {
435 Kind Kind
436 Name string // Gone and StartMissing: the start's handle or branch
437 Layer *Layer // the layer it is about
438 Other *Layer // SharedBranch: the layer below on the same branch
439
440 // The change it is about, other than the layer itself, and the
441 // version concerned.
442 Change *Recorded
443 Version change.Version
444
445 Handle string // the handle of Change
446
447 Commit string // HeadMoved, Merge, ForeignHead: the commit concerned
448 Paths []string // Conflict: every path that conflicted, in git's order
449 Below string // Conflict and EmptyLayer: what the layer was rebased onto, by name
450}
451
452func (r *Refusal) Error() string {
453 l := r.Layer
454 switch r.Kind {
455 case Gone:
456 return "origin no longer holds a record of change " + r.Name
457 case StartMissing:
458 return "no such branch on origin: " + r.Name
459 case NoBranch:
460 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)
461 case BranchMissing:
462 return fmt.Sprintf("%s is on the branch %s, and origin has no such branch; nothing rebased", l.Name, l.Branch)
463 case NotReady:
464 return fmt.Sprintf("change %s v%d is %s, not ready; nothing rebased", l.Name, l.Version, l.Record.State)
465 case HeadMoved:
466 return fmt.Sprintf("%s is at %s, and the head given was %s; nothing rebased", l.Name, l.Head, r.Commit)
467 case TipMoved:
468 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)
469 case BranchOfChange:
470 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)
471 case SharedBranch:
472 return fmt.Sprintf("%s and %s are both on the branch %s; nothing rebased", r.Other.Name, l.Name, l.Branch)
473 case StackUnread:
474 return fmt.Sprintf("could not read the commits under %s; nothing rebased", l.Name)
475 case LayerUnread:
476 return fmt.Sprintf("could not read the commits of %s; nothing rebased", l.Name)
477 case Merge:
478 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))
479 case ForeignHead:
480 h, why := r.Handle, "which is no layer of this stack"
481 if r.Change.Record.State != change.Ready {
482 why = fmt.Sprintf("which is %s, not ready", r.Change.Record.State)
483 }
484 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",
485 short(r.Commit), l.Name, r.Version.N, h, why, h)
486 case NoHistory:
487 return fmt.Sprintf("%s and %s share no history; nothing rebased", l.Name, Target)
488 case NoWorktree:
489 return "could not make a directory for the rebase; nothing changed"
490 case NoCheckout:
491 return fmt.Sprintf("could not check out origin/%s for the rebase; nothing changed", l.Branch)
492 case Conflict:
493 return fmt.Sprintf("%s conflicts with %s; nothing changed", l.Name, r.Below)
494 case NoNewHead:
495 return fmt.Sprintf("could not read the rebased head of %s; nothing pushed", l.Branch)
496 case EmptyLayer:
497 return fmt.Sprintf("%s adds nothing to %s once rebased, as when its commits have landed already; nothing pushed", l.Name, r.Below)
498 case OriginUnread:
499 return "could not read origin again before the push; nothing pushed"
500 case RecordGone:
501 return fmt.Sprintf("origin no longer holds a record of change %s; nothing pushed", l.Name)
502 case RecordUnread:
503 return fmt.Sprintf("could not read the record of change %s again; nothing pushed", l.Name)
504 case RecordNotReady:
505 v := r.Change.Record.ActiveVersion()
506 return fmt.Sprintf("change %s v%d is %s, not ready; nothing pushed", l.Name, v.N, r.Change.Record.State)
507 case RecordNewHead:
508 v := r.Change.Record.ActiveVersion()
509 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)
510 case RecordChanged:
511 return fmt.Sprintf("the record of change %s changed while it was rebased; nothing pushed", l.Name)
512 case BranchUnread:
513 return fmt.Sprintf("could not read origin/%s again against origin's records; nothing pushed", l.Branch)
514 case BecameChange:
515 return fmt.Sprintf("origin/%s is now change %s; nothing pushed", l.Branch, r.Handle)
516 }
517 return fmt.Sprintf("refusal %d", r.Kind)
518}
519
520// about is a refusal about the change n, other than its layer.
521func (s *Snapshot) about(r *Refusal, n Recorded) *Refusal {
522 r.Change, r.Handle = &Recorded{ID: n.ID, Commit: n.Commit, Record: n.Record}, s.Handle(n.ID)
523 return r
524}
525
526// Refusals are several refusals found together: Check reads every layer's
527// branch before it refuses those not at their changes' heads.
528type Refusals []*Refusal
529
530func (rs Refusals) Error() string {
531 var words []string
532 for _, r := range rs {
533 words = append(words, r.Error())
534 }
535 return strings.Join(words, "\n")
536}