gunk-dev/the-valley

family.go

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