gunk-dev/the-valley

snapshot.go

sourceca98fdc29fbfmain's published tip history
26.6 KiB
1// Every change a repository holds a record of, and how far each version
2// has landed.
3//
4// A snapshot is one read of origin: every branch, every record, every
5// integration request, outcome record and landing record, every
6// attestation ref, and every restack report. From it, for each version of
7// each change, it decides the landing evidence the version has. The first
8// rule that applies is the answer:
9//
10// 1. landed: the version's head is on main's first-parent history, and
11// no commit on that history between the head and main's tip is a
12// merge. The integrator never writes a merge, and it never puts a
13// change's own commits on that history. This rule matches a head
14// written to main directly, or landed directly by an earlier
15// integrator. A merge above the head
16// could have dropped the head's content, whichever parent the head is
17// reached through, so it leaves the head not landed by this rule.
18// 2. landed-recorded: a commit L on main's first-parent history, with one
19// parent, carries a transfer statement, signed by the integrator,
20// whose change is a request name of the version and whose base is
21// the valley-tree-v1 digest of the version's tree. The integrator
22// writes one when it lands a change (integrator/transfer.go). The
23// integrator recorded landing this version's head as L under that
24// request name: a statement about trees does not name the exact head,
25// and the integrator's records do. Only the integrator writes them.
26// The landing record for the head (change/landing.go) says so when
27// origin holds one. A landing made before the integrator wrote
28// landing records has none, and then the outcome record for the
29// request name must say land at this version's head. And the
30// integrator's own merge of the head onto L's parent gives L's tree.
31// 3. uncertain: a request for the version was consumed, or the outcome
32// record says the integrator failed on it, or a landing record names
33// its head, and neither of the above holds. The integrator records a
34// landing in the transaction that moves main (integrator/refs.go), so
35// only a landing made before it did, or one cut short inside git's
36// commit of that transaction, exists without its evidence.
37// 4. not-landed: otherwise.
38//
39// An outcome record or a landing record alone is never proof of a
40// landing. An outcome record is kept per request name, so a later pass
41// can overwrite it: a landing that only its outcome record bound to its
42// head, and whose record a later pass overwrote, reads uncertain, never
43// landed-recorded. A landing record is kept per head, so a later landing
44// under the same request name leaves it in place.
45
46package rebase
47
48import (
49 "context"
50 "fmt"
51 "sort"
52 "strings"
53
54 "the-valley/change"
55)
56
57// The landing evidence a version can have.
58const (
59 Landed = "landed"
60 LandedRecorded = "landed-recorded"
61 LandingUncertain = "uncertain"
62 NotLanded = "not-landed"
63)
64
65// Verifier is what a transfer statement is checked with: the known-signers
66// file of verifier keys, the name the integrator signs under, and the
67// directory what was verified is remembered in. Without the first two, no
68// transfer statement is believed, and a version that only one could show
69// landed reads as uncertain or not-landed.
70//
71// SignerProjects is the signer projects file the host's controllers
72// read (note/signerprojects.go): each signer it names, and the projects
73// that signer's check evidence counts in. A signer it names, a worker or
74// another controller, is never this host's integrator, so while it names
75// Signer no transfer statement is believed, in any project.
76//
77// Resolve, when set, finds the keys, the name and the signer projects
78// file when they are first needed: a snapshot calls it once, before it
79// reads its first statement, and checks with what it returns in place of
80// Keys, Signer and SignerProjects. A snapshot that reads no statement
81// never calls it.
82//
83// Cache is the directory verified statements and tree digests are
84// remembered in between commands (cache.go), such as CacheDir, or "" to
85// remember nothing.
86type Verifier struct {
87 Keys, Signer string
88 SignerProjects map[string]map[string]bool
89 Resolve func() (keys, signer string, signerProjects map[string]map[string]bool)
90 Cache string
91}
92
93// Snapshot is one read of a repository's origin. Its landing decisions,
94// and the ancestry it reads, are read from git when first asked for, under
95// the context the snapshot was made with, and kept.
96type Snapshot struct {
97 Origin
98 Tip string // main on origin; "" when origin has none
99 Changes []Recorded // every record that reads, in the order of their IDs
100 Unread []UnreadRecord // each record that does not read, which no reader shows
101
102 ctx context.Context
103 g Git
104 verify Verifier
105 keys *keyring // the verifier, once resolved
106 cache cache
107
108 outcomes map[string]Outcome // outcome ref → the record it holds
109 landed map[string]landingAt // head → its landing record, once read
110 landingData map[string]string // landing record commit → its landing file, as one batch read them; nil until read
111 reports map[string]Report // change ID → its restack report, once read
112 landings map[string][2]string // "<change ID> <n>" → landing and commit
113 firstParent map[string]int // main's first-parent history, down to its first merge, and each commit's number of parents; nil until read
114 reachesOf map[string]bool
115 reachOf map[string]reached
116 ancestorOf map[[2]string]bool // "is a an ancestor of b", as git answered it
117 history *history // every commit main reaches; nil until read, or when it does not read
118 historyRead bool
119 digestOf map[string]string
120 transfers []transferStatement
121 read bool // whether transfers has been read
122
123 // unverified is set when a transfer statement named a version and
124 // could not be checked, so its landing may be stronger than shown.
125 unverified bool
126}
127
128// snapshotTries is how many times ReadSnapshot lists origin and fetches
129// what the listing names before it gives up.
130const snapshotTries = 3
131
132// ReadSnapshot lists origin once and fetches every object the snapshot
133// reads: main, every branch tip, every record commit, every outcome and
134// landing record, and every restack report. A record commit has its
135// version heads as parents, so they come with it.
136//
137// A ref can move between the listing and the fetch. Origin may then no
138// longer hold the object the listing named, as when main was rewritten and
139// its old tip pruned, and the fetch fails. The read is then made again
140// from a new listing, up to snapshotTries times in all, and a fetch that
141// still fails is the snapshot's error.
142func ReadSnapshot(ctx context.Context, g Git, v Verifier) (*Snapshot, error) {
143 for try := 1; ; try++ {
144 end := g.phase("fetch")
145 o, err := ListOrigin(ctx, g, InventoryPatterns...)
146 end()
147 if err != nil {
148 return nil, err
149 }
150 s, err := fetchSnapshot(ctx, g, o, v)
151 if err == nil || try == snapshotTries || ctx.Err() != nil {
152 return s, err
153 }
154 }
155}
156
157// fetchSnapshot fetches every object a snapshot of the listing reads, and
158// reads every record it names.
159func fetchSnapshot(ctx context.Context, g Git, o Origin, v Verifier) (*Snapshot, error) {
160 var want []string
161 for ref, oid := range o.Refs {
162 if strings.HasPrefix(ref, "refs/heads/") || strings.HasPrefix(ref, OutcomePrefix) ||
163 strings.HasPrefix(ref, LandingPrefix) || strings.HasPrefix(ref, RestackPrefix) {
164 want = append(want, oid)
165 }
166 }
167 end := g.phase("fetch")
168 err := Fetch(ctx, g, want...)
169 end()
170 if err != nil {
171 return nil, err
172 }
173 defer g.phase("records")()
174 all, unread, err := ReadAll(ctx, g, o)
175 if err != nil {
176 return nil, err
177 }
178 s := NewSnapshot(ctx, g, o, all, v)
179 s.Unread = unread
180 return s, nil
181}
182
183// NewSnapshot is a snapshot of what o lists, with every record in all
184// already read and every object it names already fetched.
185func NewSnapshot(ctx context.Context, g Git, o Origin, all []Recorded, v Verifier) *Snapshot {
186 s := &Snapshot{
187 Origin: o, Tip: o.Refs["refs/heads/"+Target], Changes: all,
188 ctx: ctx, g: g, verify: v, cache: cache{dir: v.Cache},
189 outcomes: map[string]Outcome{}, landed: map[string]landingAt{}, reports: map[string]Report{}, landings: map[string][2]string{},
190 reachesOf: map[string]bool{}, reachOf: map[string]reached{}, ancestorOf: map[[2]string]bool{}, digestOf: map[string]string{},
191 }
192 var records []string
193 for ref, oid := range o.Refs {
194 if strings.HasPrefix(ref, OutcomePrefix) {
195 records = append(records, oid)
196 }
197 }
198 read := g.blobs(ctx, records)
199 for ref, oid := range o.Refs {
200 if strings.HasPrefix(ref, OutcomePrefix) {
201 data, ok := read[oid]
202 if !ok {
203 var err error
204 if data, err = g.output(ctx, true, "cat-file", "blob", oid); err != nil {
205 data = ""
206 }
207 }
208 s.outcomes[ref] = ParseOutcome(data)
209 }
210 }
211 return s
212}
213
214// Unverified reports whether a transfer statement named a version and
215// could not be checked, so that version's landing may be stronger than
216// the snapshot says.
217func (s *Snapshot) Unverified() bool { return s.unverified }
218
219// OnMain reports whether a commit is on main's first-parent history (main
220// itself, its first parent, that commit's first parent, and so on) with no
221// merge between it and main's tip: whether
222// `git rev-list --first-parent --merges <oid>..main` would list nothing.
223// This is where a landing puts a change. The history is read down to its
224// first merge, which is itself the last commit counted, since no merge is
225// above it.
226func (s *Snapshot) OnMain(oid string) bool {
227 if s.Tip == "" || oid == "" {
228 return false
229 }
230 if s.firstParent == nil {
231 s.firstParent = map[string]int{}
232 if out, err := s.g.output(s.ctx, true, "rev-list", "--first-parent", "--parents", s.Tip); err == nil {
233 for _, line := range strings.Split(out, "\n") {
234 fields := strings.Fields(line)
235 if len(fields) == 0 {
236 continue
237 }
238 s.firstParent[fields[0]] = len(fields) - 1
239 if len(fields) > 2 {
240 break
241 }
242 }
243 }
244 }
245 _, on := s.firstParent[oid]
246 return on
247}
248
249// Reaches reports whether main reaches a commit by any path: whether the
250// commit is an ancestor of main, or main itself. That is ancestry, which
251// is not landing (OnMain).
252//
253// Main's history answers, once read. A commit outside it that Reach lists
254// is one main does not reach. Anything else, such as a name that is not a
255// commit's ID, git answers, once.
256func (s *Snapshot) Reaches(oid string) bool {
257 if s.Tip == "" || oid == "" {
258 return false
259 }
260 if h := s.mainHistory(); h != nil {
261 if h.has(oid) {
262 return true
263 }
264 if s.Reach(oid)[oid] {
265 return false
266 }
267 }
268 r, seen := s.reachesOf[oid]
269 if !seen {
270 r = s.g.succeeds(s.ctx, true, "merge-base", "--is-ancestor", oid, s.Tip)
271 s.reachesOf[oid] = r
272 }
273 return r
274}
275
276// Request is the ref of the integration request origin holds for a
277// version: one filed under either of its names, at its head.
278func (s *Snapshot) Request(id string, v change.Version) (ref string, ok bool) {
279 for _, name := range RequestNames(id, v) {
280 if ref := RequestPrefix + name; s.Refs[ref] == HeadOf(v) {
281 return ref, true
282 }
283 }
284 return "", false
285}
286
287// OutcomeOf is the outcome record origin holds under a request name, as
288// ParseOutcome reads it, and whether origin holds one.
289func (s *Snapshot) OutcomeOf(name string) (Outcome, bool) {
290 m, ok := s.outcomes[OutcomePrefix+name]
291 return m, ok
292}
293
294// Outcome is the integrator's last decision about a version: the outcome
295// record under either of its names whose head is the version's head.
296func (s *Snapshot) Outcome(id string, v change.Version) (name string, m Outcome, found bool) {
297 for _, name := range RequestNames(id, v) {
298 if m, ok := s.outcomes[OutcomePrefix+name]; ok && m.Head == HeadOf(v) {
299 return name, m, true
300 }
301 }
302 return "", Outcome{}, false
303}
304
305// Landing is the landing evidence a version has, and the commit on main it
306// landed as, when it has. Each version is decided once per snapshot.
307func (s *Snapshot) Landing(id string, v change.Version) (kind, commit string) {
308 key := fmt.Sprintf("%s %d", id, v.N)
309 if l, ok := s.landings[key]; ok {
310 return l[0], l[1]
311 }
312 kind, commit = s.decideLanding(id, v)
313 s.landings[key] = [2]string{kind, commit}
314 return kind, commit
315}
316
317func (s *Snapshot) decideLanding(id string, v change.Version) (kind, commit string) {
318 head := HeadOf(v)
319 if s.OnMain(head) {
320 return Landed, head
321 }
322 if commit, ok := s.recordedLanding(id, v); ok {
323 return LandedRecorded, commit
324 }
325 if name, m, ok := s.Outcome(id, v); ok {
326 consumed := m.Decision == "land" && s.Refs[RequestPrefix+name] != head
327 if consumed || m.Decision == "failed" {
328 return LandingUncertain, ""
329 }
330 }
331 if s.Refs[LandingPrefix+head] != "" {
332 return LandingUncertain, ""
333 }
334 return NotLanded, ""
335}
336
337// IsLanded reports whether a version has landed by the first two rules.
338func (s *Snapshot) IsLanded(id string, v change.Version) bool {
339 kind, _ := s.Landing(id, v)
340 return kind == Landed || kind == LandedRecorded
341}
342
343// LandedAs is the version a change landed as, and whether it has: the
344// newest of its versions that landed by the first two rules. A change
345// counts as landed once any of its versions has, so a version restacked
346// while an earlier one was approved, and still active when that one
347// landed, is no work left to land. An active version whose head reaches
348// that landing was made on a main that holds it, and is the change's next
349// round: the change reads unlanded until that version lands.
350func (s *Snapshot) LandedAs(n Recorded) (change.Version, bool) {
351 active := n.Record.ActiveVersion()
352 for i := len(n.Record.Versions) - 1; i >= 0; i-- {
353 v := n.Record.Versions[i]
354 kind, commit := s.Landing(n.ID, v)
355 if kind != Landed && kind != LandedRecorded {
356 continue
357 }
358 if v.N != active.N && s.StrictAncestor(commit, HeadOf(active)) {
359 return change.Version{}, false
360 }
361 return v, true
362 }
363 return change.Version{}, false
364}
365
366// Unlanded reports whether a change, in any state, has not landed as any
367// of its versions (LandedAs): the changes a stack's layers are among.
368func (s *Snapshot) Unlanded(n Recorded) bool {
369 _, landed := s.LandedAs(n)
370 return !landed
371}
372
373// recordedLanding looks for a transfer statement that records the version
374// landing as a commit on main, and verifies the first that matches.
375// Statements are read only for a version the integrator's records bind to
376// some landing, since boundTo asks that of every statement that counts.
377func (s *Snapshot) recordedLanding(id string, v change.Version) (string, bool) {
378 names := map[string]bool{}
379 for _, n := range RequestNames(id, v) {
380 names[n] = true
381 }
382 head := HeadOf(v)
383 if !s.bound(names, head) {
384 return "", false
385 }
386 for _, t := range s.transferStatements() {
387 if !names[t.change] || !IsObjectID(t.landed) || !s.OnMain(t.landed) || !s.singleParent(t.landed) {
388 continue
389 }
390 if s.boundTo(t, head) && s.verified(t, head) {
391 return t.landed, true
392 }
393 }
394 return "", false
395}
396
397// bound reports whether the integrator's records bind head to a landing
398// under one of names, whatever commit it landed as: what boundTo asks of
399// a statement, before any statement is read.
400func (s *Snapshot) bound(names map[string]bool, head string) bool {
401 if at, found := s.landingRecord(head); found {
402 return at.read && at.Head == head && names[at.Request]
403 }
404 for name := range names {
405 if m, ok := s.outcomes[OutcomePrefix+name]; ok && m.Decision == "land" && m.Head == head {
406 return true
407 }
408 }
409 return false
410}
411
412// boundTo reports whether the integrator recorded landing head as the
413// statement's commit, under the statement's request name. When origin
414// holds a landing record for the head, that record alone answers. A
415// landing made before landing records were written has none, and its
416// outcome record answers instead.
417func (s *Snapshot) boundTo(t transferStatement, head string) bool {
418 if at, found := s.landingRecord(head); found {
419 return at.read && at.Landed == t.landed && at.Request == t.change && at.Head == head
420 }
421 m, ok := s.outcomes[OutcomePrefix+t.change]
422 return ok && m.Decision == "land" && m.Head == head
423}
424
425// landingAt is a landing record as a snapshot read it, and whether it
426// read.
427type landingAt struct {
428 change.Landing
429 read bool
430}
431
432// landingRecord reads the landing record origin holds for head, once.
433// found is false when origin holds none. A record that does not read is
434// found, and says nothing. The first call reads every landing record
435// origin holds with one batch, and a record the batch does not show is
436// fetched and read alone.
437func (s *Snapshot) landingRecord(head string) (landingAt, bool) {
438 oid := s.Refs[LandingPrefix+head]
439 if oid == "" {
440 return landingAt{}, false
441 }
442 if at, ok := s.landed[head]; ok {
443 return at, true
444 }
445 if s.landingData == nil {
446 var names []string
447 for ref, oid := range s.Refs {
448 if strings.HasPrefix(ref, LandingPrefix) {
449 names = append(names, oid+":"+change.LandingFile)
450 }
451 }
452 s.landingData = s.g.blobs(s.ctx, names)
453 }
454 var at landingAt
455 data, ok := s.landingData[oid+":"+change.LandingFile]
456 if !ok {
457 var err error
458 if err = Fetch(s.ctx, s.g, oid); err != nil {
459 s.unverified = true
460 } else {
461 data, err = s.g.output(s.ctx, true, "cat-file", "blob", oid+":"+change.LandingFile)
462 }
463 ok = err == nil
464 }
465 if ok {
466 if l, err := change.ParseLanding([]byte(data + "\n")); err == nil {
467 at = landingAt{Landing: l, read: true}
468 }
469 }
470 s.landed[head] = at
471 return at, true
472}
473
474// singleParent reports whether a commit has exactly one parent, as every
475// commit the integrator lands as does. For a commit on main (OnMain), the
476// read of main's first-parent history has its parents.
477func (s *Snapshot) singleParent(oid string) bool {
478 if n, on := s.firstParent[oid]; on {
479 return n == 1
480 }
481 out, err := s.g.output(s.ctx, true, "rev-list", "--parents", "-n", "1", oid)
482 return err == nil && len(strings.Fields(out)) == 2
483}
484
485// mergesTo reports whether the integrator's merge of head onto landed's
486// parent gives landed's tree. It is the merge integrator/git.go's
487// mergeDelta makes: merge-tree onto the tip, with the merge base of the
488// tip and the head as the base. A head that merges to another tree, or
489// not at all, is not what landed. Every git here reads with replacement
490// refs off, as digest does, so the answer a landing entry remembers
491// depends on the objects alone, never on the reading repository's
492// refs/replace.
493func (s *Snapshot) mergesTo(head, landed string) bool {
494 git := func(args ...string) (string, error) {
495 return s.g.output(s.ctx, true, append([]string{"--no-replace-objects"}, args...)...)
496 }
497 tip, err := git("rev-parse", "--verify", "--quiet", landed+"^1^{commit}")
498 if err != nil {
499 return false
500 }
501 want, err := git("rev-parse", "--verify", "--quiet", landed+"^{tree}")
502 if err != nil {
503 return false
504 }
505 base, err := git("merge-base", tip, head)
506 if err != nil {
507 return false
508 }
509 out, err := git("merge-tree", "--write-tree", "--merge-base="+base, tip, head)
510 if err != nil {
511 return false
512 }
513 tree, _, _ := strings.Cut(out, "\n")
514 return strings.TrimSpace(tree) == want
515}
516
517// reached is what a commit reaches, as one rev-list read it.
518type reached struct {
519 commits map[string]bool // every commit it reaches that main does not
520 // below is each commit main reaches that is a parent of one in
521 // commits: where its own history meets main's.
522 below []string
523}
524
525// Reach is every commit reachable from oid that main does not reach.
526func (s *Snapshot) Reach(oid string) map[string]bool {
527 return s.reached(oid).commits
528}
529
530// reached reads what oid reaches, once.
531func (s *Snapshot) reached(oid string) reached {
532 if r, ok := s.reachOf[oid]; ok {
533 return r
534 }
535 args := []string{"rev-list", "--parents", oid}
536 if s.Tip != "" {
537 args = append(args, "^"+s.Tip)
538 }
539 r := reached{commits: map[string]bool{}}
540 if out, err := s.g.output(s.ctx, true, args...); err == nil {
541 var parents []string
542 for _, line := range strings.Split(out, "\n") {
543 if fields := strings.Fields(line); len(fields) > 0 {
544 r.commits[fields[0]] = true
545 parents = append(parents, fields[1:]...)
546 }
547 }
548 seen := map[string]bool{}
549 for _, p := range parents {
550 if !r.commits[p] && !seen[p] {
551 seen[p] = true
552 r.below = append(r.below, p)
553 }
554 }
555 }
556 s.reachOf[oid] = r
557 return r
558}
559
560// StrictAncestor reports whether a is an ancestor of b, and not b itself.
561// A commit main does not reach is an ancestor of b exactly when it is in
562// Reach(b). A commit main reaches is one exactly when b is a commit main
563// reaches and has it in its history, or when a commit where b's own
564// history meets main's has it. Main's history answers that. git is asked
565// only when the snapshot cannot tell, and each pair once.
566func (s *Snapshot) StrictAncestor(a, b string) bool {
567 switch {
568 case a == b:
569 return false
570 case s.Reach(b)[a]:
571 return true
572 case !s.Reaches(a):
573 return false
574 }
575 if r, known := s.mainAncestor(a, b); known {
576 return r
577 }
578 key := [2]string{a, b}
579 r, seen := s.ancestorOf[key]
580 if !seen {
581 r = s.g.succeeds(s.ctx, true, "merge-base", "--is-ancestor", a, b)
582 s.ancestorOf[key] = r
583 }
584 return r
585}
586
587// mainAncestor answers, from main's history, whether a, a commit main
588// reaches, is an ancestor of b. known is false when it cannot tell: when
589// main's history did not read, or b is not a commit Reach(b) or main's
590// history lists.
591func (s *Snapshot) mainAncestor(a, b string) (r, known bool) {
592 h := s.mainHistory()
593 if h == nil || !h.has(a) {
594 return false, false
595 }
596 if h.has(b) {
597 return h.reaches(b, a), true
598 }
599 at := s.reached(b)
600 if !at.commits[b] {
601 return false, false
602 }
603 for _, c := range at.below {
604 if !h.has(c) {
605 return false, false
606 }
607 }
608 for _, c := range at.below {
609 if h.reaches(c, a) {
610 return true, true
611 }
612 }
613 return false, true
614}
615
616// mainHistory is every commit main reaches, read once. It is nil when
617// origin has no main, or its history does not read.
618func (s *Snapshot) mainHistory() *history {
619 if !s.historyRead && s.Tip != "" {
620 s.historyRead = true
621 s.history, _ = readHistory(s.ctx, s.g, s.Tip)
622 }
623 return s.history
624}
625
626// BranchHead is a branch on origin and the commit at its tip.
627type BranchHead struct {
628 Branch, Head string
629}
630
631// Unrecorded is every branch on origin, other than main, whose tip main
632// does not reach, that is not the head of any change's active version, and
633// that no landed version's head reaches, in the order of their names.
634//
635// A version lands as one new commit on main, so main does not reach the
636// version's own commits, nor a branch below them. Their content is on
637// main, so such a branch is no work waiting to land: it is left out, as
638// the rebase engine cuts a landed version's commits from a family
639// (LandedUnder).
640func (s *Snapshot) Unrecorded() []BranchHead {
641 active := map[string]bool{}
642 for _, n := range s.Changes {
643 active[HeadOf(n.Record.ActiveVersion())] = true
644 }
645 var branches []BranchHead
646 for ref, oid := range s.Refs {
647 name, ok := strings.CutPrefix(ref, "refs/heads/")
648 if !ok || name == Target || active[oid] || s.Reaches(oid) || s.underLanded(oid) {
649 continue
650 }
651 branches = append(branches, BranchHead{Branch: name, Head: oid})
652 }
653 sort.Slice(branches, func(i, j int) bool { return branches[i].Branch < branches[j].Branch })
654 return branches
655}
656
657// underLanded reports whether a landed version's head is oid or reaches
658// it. Each version's landing is decided once per snapshot, before
659// anything is walked, and only a landed version's head has its reach
660// read, once per snapshot.
661func (s *Snapshot) underLanded(oid string) bool {
662 for _, n := range s.Changes {
663 for _, v := range n.Record.Versions {
664 if h := HeadOf(v); s.IsLanded(n.ID, v) && (h == oid || s.Reach(h)[oid]) {
665 return true
666 }
667 }
668 }
669 return false
670}
671
672// LandedUnder is the head of every version that has landed, by the first
673// two rules, and that head reaches while main does not, head itself
674// included: work a landing took onto main as one new commit, which main
675// does not reach. They are in the order of the changes' IDs and their
676// versions. Each version's landing is decided first, and head's reach is
677// read only once some version has landed.
678func (s *Snapshot) LandedUnder(head string) []string {
679 var reach map[string]bool
680 var heads []string
681 for _, n := range s.Changes {
682 for _, v := range n.Record.Versions {
683 if !s.IsLanded(n.ID, v) {
684 continue
685 }
686 if reach == nil {
687 reach = s.Reach(head)
688 }
689 if h := HeadOf(v); reach[h] {
690 heads = append(heads, h)
691 }
692 }
693 }
694 return heads
695}
696
697// Node is one head among those Nest stacks: a change's active head or a
698// branch's tip, with the commit time it is ordered by and the name ties
699// are broken by.
700type Node struct {
701 Name string
702 Head string
703 When int64
704}
705
706// Nesting is how a set of nodes stack, by ancestry alone. Each slice is
707// indexed as the nodes were given.
708type Nesting struct {
709 // Parent is the node each is nested under: the nearest node whose head
710 // strictly contains its own, or -1 for none. Where two are equally
711 // near, the one with the later commit is taken.
712 Parent []int
713 // Base is the nearest node whose head its own head strictly contains,
714 // or -1 for main. Where two are equally near, the one nested under it
715 // is taken, and otherwise the one with the later commit.
716 Base []int
717 // Inside is every node whose head strictly contains its own, in the
718 // order given.
719 Inside [][]int
720}
721
722// Nest stacks the nodes: valley pending nests its entries this way, and
723// a stack's layers each sit on their base.
724func (s *Snapshot) Nest(nodes []Node) Nesting {
725 n := len(nodes)
726 in := make([][]bool, n) // in[i][j]: node i's head strictly contains node j's
727 nest := Nesting{Parent: make([]int, n), Base: make([]int, n), Inside: make([][]int, n)}
728 for i := range nodes {
729 in[i] = make([]bool, n)
730 for j := range nodes {
731 in[i][j] = i != j && s.StrictAncestor(nodes[j].Head, nodes[i].Head)
732 if in[i][j] {
733 nest.Inside[j] = append(nest.Inside[j], i)
734 }
735 }
736 }
737 // nearest is the nodes i contains, or that contain i, with none
738 // between, the latest commit first.
739 nearest := func(i int, above bool) []int {
740 var near []int
741 for j := range nodes {
742 outer, inner := j, i
743 if !above {
744 outer, inner = i, j
745 }
746 if !in[outer][inner] {
747 continue
748 }
749 between := false
750 for k := range nodes {
751 between = between || in[outer][k] && in[k][inner]
752 }
753 if !between {
754 near = append(near, j)
755 }
756 }
757 sort.SliceStable(near, func(a, b int) bool {
758 x, y := nodes[near[a]], nodes[near[b]]
759 if x.When != y.When {
760 return x.When > y.When
761 }
762 return x.Name < y.Name
763 })
764 return near
765 }
766 for i := range nodes {
767 nest.Parent[i] = -1
768 if above := nearest(i, true); len(above) > 0 {
769 nest.Parent[i] = above[0]
770 }
771 }
772 for i := range nodes {
773 nest.Base[i] = -1
774 below := nearest(i, false)
775 for _, d := range below {
776 if nest.Parent[d] == i {
777 nest.Base[i] = d
778 break
779 }
780 }
781 if nest.Base[i] == -1 && len(below) > 0 {
782 nest.Base[i] = below[0]
783 }
784 }
785 return nest
786}