gunk-dev/the-valley

pending.go

source40b311d8f0demain's published tip history
34.6 KiB
1// valley pending: what waits on the operator, and what is moving, for a
2// person to read.
3//
4// It opens with main's state (mainstate.go), one line for each project
5// whose policy has classes that checks follow: clear, clearing or muddy.
6// A project with no follow check has no line. A project that did not read
7// says why on a line of its own.
8//
9// Then come two sections over every project listed, from the queue
10// (queue.go). needs you holds the ready changes that wait on an approval,
11// one row each, numbered in landing order. A stack of them is one row, its
12// top's, which says how many changes it holds: approving the top lands
13// every layer. Each row gives the change's handle and active version, its
14// checks, and how long it has been ready, and its title goes on the line
15// under it:
16//
17// needs you (2, in landing order)
18// 1 smuk v4 checks 18/18 · stack of 2 19m
19// each ready change shows its active version's checks · oc-6335749
20// 2 wnzs v2 2 checks pending 42m
21// the guest's tools follow main
22//
23// moving holds the ready changes that need no approval now, one line each,
24// in the same order: an approved change, which waits on its checks and the
25// integrator, with its checks; a change whose checks failed, naming them;
26// and a change a restack holds, saying what its report says. A change is
27// approved by a request at its active version's head, or at an earlier
28// version's head whose approval carries to the active version (addCarried):
29//
30// moving (3)
31// ◐ mytm v5 approved · 6 checks pending
32// ✗ rwzt v2 worker-e2e failed
33// ✗ xzus v3 restack: a conflict rebasing xzus onto main at a1b2c3d
34//
35// Under a row of either section, one line names the project's other
36// ready changes it conflicts with, by the merge the integrator makes of
37// one once the other lands (conflicts.go): "conflicts with mytm, wnzs".
38// With --checks or -v, a line for each such change names the conflicted
39// paths, "conflicts with mytm: go.mod, docs/guide.md". These lines follow
40// the checks lines. One line under the sections counts the pairs not
41// compared and says why, "2 pairs not compared: awaiting restack", so a
42// pair not compared never reads as one that does not conflict.
43//
44// Checks are counted as valley changes --checks reads them
45// (versionchecks.go): for each project with a ready change, or with a
46// draft that --drafts --checks lists, one read of the policy and one
47// attest verify for each head, over all of its notes, and nothing for a
48// project without one.
49// When nothing waits on an approval, one line says so in place of needs
50// you, and moving is left out when nothing moves. Older versions of a
51// change are never listed.
52//
53// A last line counts the drafts and the branches on origin that no change
54// is on, with the flags that list them in full. --drafts and --branches
55// each print a section of blocks in place of their count. A block's first
56// line is its name, with the age and author of its head: the handle and
57// version of a draft on its branch, or the name of a branch. The lines
58// indented under it give its title, then the commits and the diff the
59// entry adds to its base:
60//
61// deep-4 3 weeks ago · alice-agent-vm
62// share the record bounds and the c-<change ID> request name
63// 10 commits · 31 files +2412 −404
64// approving it lands the 2 below too
65// ├ deep-3 3 weeks ago · alice-agent-vm
66// │ valley: changes --json and pending by handle, across a host's projects
67// │ 9 commits · 17 files +2701 −137
68// └ deep-2 3 weeks ago · alice-agent-vm
69// change: read a draft as a third state
70// 14 commits · 20 files +1207 −219
71//
72// With -v, each row of needs you and moving is followed by its block,
73// without the name line the row already gives, and a row's stack is
74// drawn in full. branches holds each branch on origin, other than main,
75// that main does not reach, that is no change's active head, and that no
76// landed version's head reaches. drafts holds the changes whose record
77// says they are drafts.
78//
79// A change's title is its record's, for the active version. A branch's
80// title is the subject of its first own commit: the oldest commit on its
81// first-parent line that its base does not hold. When a knot in the plan
82// graph links a change, the first knot's ID follows the title, as
83// "<title> · oc-6335749" (does.go).
84//
85// Each listing stacks the entries it lists, and only those. An entry's
86// base is the nearest other listed entry its head strictly contains, or
87// main when there is none. That is the ancestry includes reads
88// (inventory.go). Its commits and diff are counted from the nearer of its
89// base and the head of a landed version its head contains: a landed
90// version's commits are not on main, since it landed as one new commit,
91// and its content is. A stack is an entry that no other entry contains,
92// the top, then every entry the top contains, as one list at one
93// indentation, however deep the stack is. Each entry is listed before the
94// entries it contains. The top's block says how many entries approving it
95// lands with it. Each entry is on the entry listed right after it, and
96// says "on <base>" where it is not, as at a fork, where two entries are on
97// one base and the base is listed under only one of them. In drafts and
98// branches, the stack with the latest commit comes first, and within a
99// stack the entry with the latest commit does.
100//
101// A block may say more, each on a line of its own. includes <handle>
102// names a change its head contains that is not listed, such as a
103// withdrawn one. uncertain says the active version may have landed
104// without its evidence being stored, and restack what a current restack
105// report says. With --checks, a row says how many checks the policy
106// requires of the change, by cost, and the full check state, as valley
107// changes --checks lists it, naming those that failed: "checks: 18
108// passed, 1 failed (valley-request)". When the host's worker telemetry
109// holds the version's builds, the line goes on with what they cost and
110// the checks that grew against their recent cost on the same capacity
111// (checkcost.go): "checks: 21 passed in 9m10s (eval 24s); worker-e2e
112// 431s, +68s against its recent 363s". When no note records a failure
113// and the worker's newest build of a pending check failed, the row says
114// "✗ valley-request failed in the worker's build, 5m ago" in place of its
115// count, an approved row says it after approved, the line says it after
116// the pending count, "checks: 18 passed, 1 pending (valley-request failed
117// in the worker's build, 5m ago)", and a line under it reads the worker's
118// report: "see: valley telemetry read --source worker --logs"
119// (versionchecks.go). -v gives the full check state with or without
120// --checks. With --drafts and --checks, a draft's block carries the same
121// lines, and its name line says its checks in a row's words: "checks
122// 18/18", "2 checks pending", "✗ valley-request failed in the worker's
123// build, 5m ago", or "✗ valley-request failed". A draft's checks are read
124// only when it is listed.
125//
126// Several projects, as --all or --repo lists them, make one listing: each
127// main line and each row names its project, and the rows of every project
128// are numbered in one landing order.
129//
130// Every line fits stdout's terminal, or 80 columns when stdout is no
131// terminal or does not know its width. A title or an author is cut short
132// with …; a handle or a branch never is. On a terminal, names are bold and
133// glyphs coloured, unless NO_COLOR is set.
134//
135// With --json it prints valley-pending/v1: valley-changes/v1's shape, with
136// the pending changes alone in changes, each marked approved or not, the
137// drafts in an array of their own, drafts, and the same branches. Each
138// pending change carries conflicts and conflicts_unknown. --checks gives
139// each pending change its checks object, and with --drafts each draft that
140// has not landed too.
141
142package main
143
144import (
145 "context"
146 "fmt"
147 "io"
148 "sort"
149 "strconv"
150 "strings"
151 "time"
152 "unicode"
153
154 "the-valley/change"
155 "the-valley/composed"
156 "the-valley/derive"
157 "the-valley/rebase"
158)
159
160// pendingChange is a ready change that has not landed as any version.
161func pendingChange(s *snapshot, n recorded) bool {
162 return n.record.State == change.Ready && !s.isLanded(n)
163}
164
165// approvedVersion reports whether a ready change's active version has an
166// integration request at its head. The integrator also accepts a request
167// that names an earlier head whose approval carries to this version, which
168// needs the delta between the two and the policy's carry mode: valley
169// pending reads that too (addCarried), and this rule does not.
170func (s *snapshot) approvedVersion(id string, r *change.Record) bool {
171 return r.State == change.Ready && s.request(id, r.ActiveVersion()) != nil
172}
173
174// unlanded is a change in any state that has not landed as any version:
175// the changes a pending change may include.
176func unlanded(s *snapshot, n recorded) bool {
177 return !s.isLanded(n)
178}
179
180func isDraft(_ *snapshot, n recorded) bool {
181 return n.record.State == change.Draft
182}
183
184// pendingView is a repository as valley-pending/v1 writes it: the pending
185// changes in changes, each marked approved when its active version has an
186// integration request at its head, and the drafts in drafts, each with
187// includes among the changes that have not landed. addCarried marks the
188// approvals that carry.
189func (l listed) pendingView(h handleMap) jsonRepo {
190 r := l.repoView(h, pendingChange, unlanded)
191 if l.err == nil {
192 for i, c := range r.Changes {
193 approved := c.Versions[c.Active-1].Request != nil
194 r.Changes[i].Approved = &approved
195 }
196 }
197 drafts := []jsonChange{}
198 if l.err == nil {
199 drafts = l.repoView(h, isDraft, unlanded).Changes
200 }
201 r.Drafts = &drafts
202 return r
203}
204
205// addCarried marks approved each pending change in view whose active
206// version has no request at its head, when the greatest earlier version
207// with one carries its approval to the active version. Carry's own rules
208// decide (carryBetween, carry.go), as review decides whether an answer
209// about the version it showed carries to the one the change moved to, so
210// the change is listed as the integrator will take it. A carry that does
211// not read leaves the change unapproved, and says so on stderr.
212func (l listed) addCarried(view *jsonRepo, stderr io.Writer) {
213 if l.err != nil {
214 return
215 }
216 s := l.snap
217 for i, c := range view.Changes {
218 if c.Approved == nil || *c.Approved {
219 continue
220 }
221 from := 0
222 for _, v := range c.Versions[:c.Active-1] {
223 if v.Request != nil {
224 from = v.N
225 }
226 }
227 if from == 0 {
228 continue
229 }
230 h, err := historyOf(s.g, s.o, s.all, len(s.unread) > 0, c.ChangeID)
231 verdict := ""
232 if err == nil {
233 _, verdict, _, _, err = carryBetween(s.g, h, from, c.Active, s.model)
234 }
235 if err != nil {
236 fmt.Fprintf(stderr, "valley: %s: whether the approval of %s v%d carries to v%d did not read, so it waits on an approval: %v\n",
237 l.name, c.Handle, from, c.Active, err)
238 continue
239 }
240 if verdict == "carries" {
241 approved := true
242 view.Changes[i].Approved = &approved
243 }
244 }
245}
246
247func runPending(g git, args []string, stdout, stderr io.Writer) error {
248 l, err := parseListing("pending", args, true)
249 if err != nil {
250 return err
251 }
252 list, host, err := sources(g, l, stderr)
253 if err != nil {
254 return err
255 }
256 // The worker's telemetry, which main's lines and the checks read, is
257 // read while origin is, so they wait on it only once the rest is read.
258 // A read nobody waited for is cancelled as the command ends.
259 c := newCosts()
260 defer c.close()
261 if !l.asJSON || l.checks {
262 for _, s := range list {
263 c.start(s.g)
264 }
265 }
266 repos := readSources(list, newVerifier())
267 defer closeSources(repos)
268 readKnots(repos, l.verbose, stderr)
269 h := handles(repos)
270 writeHandleCache(g, repos, h)
271 defer warnUnverified(repos, stderr)
272 if l.asJSON {
273 doc := jsonChanges{Schema: pendingSchema, Host: host, Repos: []jsonRepo{}}
274 p := newPairing()
275 for _, r := range repos {
276 view := r.pendingView(h)
277 r.addCarried(&view, stderr)
278 r.addConflicts(&view, p, stderr)
279 if l.checks {
280 r.addChecks(&view, l.drafts, c, listEvidence, stderr)
281 }
282 utf8Branches(&view, stderr)
283 doc.Repos = append(doc.Repos, view)
284 }
285 return writeDocument(stdout, doc)
286 }
287 writePending(repos, h, l, c, stdout, stderr, terminalOf(stdout), len(repos) > 1 || l.all || l.repo != "")
288 return nil
289}
290
291// entry is one row or block of valley pending: a ready change, a draft,
292// or a branch no record is on.
293type entry struct {
294 section string
295 repo string // the project it is in
296 id string // the change ID, for a change
297 version int // a change's active version
298 record string // the change's record commit
299 name string // what the block's first line names
300 ref string // what the entry is typed as: its handle, or its branch
301 head string // the head commit
302 title string // the record's title; for a branch, read by measure
303 knot string // ID of the first knot that links the change (does.go)
304 includes []string // what includes names that is no entry here
305 notes []string // uncertain and restack
306 requires string // with --checks, the checks the policy requires of it, by cost
307 checks string // the check state line of a ready change
308 see string // the line under checks that reads the worker's report of a failure, if any
309 conflicts []string // the lines naming the other ready changes it conflicts with (conflictLines)
310 unknown []jsonConflictUnknown // the other ready changes it was not compared with
311 state *jsonVersionChecks // the check state its row counts, or nil when its checks were not read
312
313 glyph, colour, says string // for a moving change, its glyph and what its row says
314
315 when int64 // the head's commit time
316 since int64 // for a change, its record's commit time: when its active version became ready
317 age, author string
318 layer string // the commits and the diff it adds to its base
319
320 parent *entry // the entry it is listed under, if any
321 kids []*entry // the entries nested right under it
322 base *entry // nil for main
323 inside []*entry // every entry whose head strictly contains its own
324 below []*entry // for the top of a stack, every entry listed under it
325 latest int64 // for the top of a stack, the latest commit time in it
326}
327
328// writePending prints the listing of every repository: the main lines,
329// needs you, moving, and the drafts and branches. named says whether each
330// line names its project.
331func writePending(repos []listed, h handleMap, l listing, c *costs, w, stderr io.Writer, t terminal, named bool) {
332 p := func(format string, args ...any) { fmt.Fprintf(w, format, args...) }
333 head := false
334 for _, r := range repos {
335 if r.err != nil {
336 p("%s: %v\n", r.name, r.err)
337 head = true
338 continue
339 }
340 for _, line := range r.mainState(h, c, stderr, t, named) {
341 p("%s\n", line)
342 head = true
343 }
344 }
345 if head {
346 p("\n")
347 }
348 defer phase("branches")()
349 var drafts, branches []block
350 nDrafts, nBranches := 0, 0
351 waiting, moving := operatorQueue(repos, h, l, c, newPairing(), listEvidence, stderr, func(r listed, view jsonRepo) {
352 nDrafts, nBranches = nDrafts+len(*view.Drafts), nBranches+len(view.Branches)
353 if l.drafts && len(*view.Drafts) > 0 {
354 drafts = append(drafts, block{r.name, r.draftStacks(view, h, l)})
355 }
356 if l.branches && len(view.Branches) > 0 {
357 branches = append(branches, block{r.name, r.branchStacks(view)})
358 }
359 })
360 for _, line := range t.rows(waiting, moving, l, named) {
361 p("%s\n", line)
362 }
363 for _, b := range []struct {
364 name string
365 blocks []block
366 }{{"drafts", drafts}, {"branches", branches}} {
367 for _, bl := range b.blocks {
368 header := b.name
369 if named {
370 header += " · " + bl.repo
371 }
372 p("\n%s\n", header)
373 for i, top := range bl.tops {
374 if i > 0 {
375 p("\n")
376 }
377 for _, line := range t.drawStack(top, "", true) {
378 p("%s\n", line)
379 }
380 }
381 }
382 }
383 var counts, flags []string
384 if n := nDrafts; n > 0 && !l.drafts {
385 counts, flags = append(counts, counted(n, "draft")), append(flags, "--drafts")
386 }
387 if n := nBranches; n > 0 && !l.branches {
388 noun := "branches"
389 if n == 1 {
390 noun = "branch"
391 }
392 counts, flags = append(counts, fmt.Sprintf("%d %s no change is on", n, noun)), append(flags, "--branches")
393 }
394 if len(counts) > 0 {
395 p("\n%s\n", strings.Join(counts, " · ")+" · valley pending "+strings.Join(flags, " "))
396 }
397}
398
399// block is one project's stacks of drafts or of branches.
400type block struct {
401 repo string
402 tops []*entry
403}
404
405// rows is needs you and moving as lines: each section's heading, then its
406// rows. A row of needs you is numbered and has its title under it; with
407// -v, a row of either is followed by its block.
408func (t terminal) rows(waiting, moving []*entry, l listing, named bool) []string {
409 var lines []string
410 projects, names := 0, 0
411 for _, e := range append(append([]*entry{}, waiting...), moving...) {
412 projects, names = max(projects, columns(e.repo)), max(names, columns(e.name))
413 }
414 // lead is a row's project and name, each padded to its column.
415 lead := func(e *entry) string {
416 s := t.strong(e.name) + strings.Repeat(" ", names-columns(e.name))
417 if named {
418 s = e.repo + strings.Repeat(" ", projects-columns(e.repo)) + " " + s
419 }
420 return s
421 }
422 width := names
423 if named {
424 width += projects + 2
425 }
426 if len(waiting) == 0 {
427 lines = append(lines, "nothing needs you")
428 } else {
429 lines = append(lines, fmt.Sprintf("needs you (%d, in landing order)", len(waiting)))
430 }
431 digits := len(strconv.Itoa(len(waiting)))
432 now := time.Now().Unix()
433 for i, e := range waiting {
434 num := fmt.Sprintf(" %*d ", digits, i+1)
435 under := strings.Repeat(" ", columns(num))
436 glyph, says := rowChecks(e.state)
437 if len(e.below) > 0 {
438 says = strings.TrimPrefix(says+" · stack of "+strconv.Itoa(len(e.below)+1), " · ")
439 }
440 left := num + lead(e) + " "
441 used := columns(num) + width + 2
442 age := ago(now, e.since)
443 if glyph != "" {
444 // What the worker reports is cut short to leave the age room.
445 left, used = left+t.tint(colourRefused, glyph)+" ", used+columns(glyph)+1
446 room := t.width - used
447 if e.since > 0 {
448 room -= 2 + columns(age)
449 }
450 says = fit(says, room)
451 }
452 left, used = left+says, used+columns(says)
453 if pad := t.width - used - columns(age); pad >= 2 && e.since > 0 {
454 left += strings.Repeat(" ", pad) + age
455 } else if e.since > 0 {
456 left += " " + age
457 }
458 lines = append(lines, strings.TrimRight(left, " "))
459 lines = append(lines, t.details(e, under, l)...)
460 }
461 if len(moving) > 0 {
462 lines = append(lines, "", fmt.Sprintf("moving (%d)", len(moving)))
463 }
464 for _, e := range moving {
465 first := " " + t.tint(e.colour, e.glyph) + " "
466 used := columns(" "+e.glyph+" ") + width + 2
467 lines = append(lines, first+lead(e)+" "+fit(e.says, t.width-used))
468 lines = append(lines, t.details(e, " ", l)...)
469 }
470 all := append([]*entry{}, moving...)
471 for _, e := range waiting {
472 all = append(append(all, e), e.below...)
473 }
474 if u := uncompared(all); u != "" {
475 lines = append(lines, "", t.fit(u, ""))
476 }
477 return lines
478}
479
480// details are the lines under a row, each led by under: for a row of
481// needs you, its title; with --checks, its checks; then the changes it
482// conflicts with; with -v, its block in place of all three.
483func (t terminal) details(e *entry, under string, l listing) []string {
484 if l.verbose {
485 return t.drawStack(e, under, false)
486 }
487 var lines []string
488 if e.section == "ready" && e.glyph == "" {
489 lines = append(lines, under+t.titled(e, under))
490 }
491 if l.checks {
492 for _, s := range []string{e.requires, e.checks} {
493 if s != "" {
494 lines = append(lines, under+t.fit(s, under))
495 }
496 }
497 if e.see != "" {
498 lines = append(lines, under+" "+t.fit(e.see, under+" "))
499 }
500 }
501 for _, s := range e.conflicts {
502 lines = append(lines, under+t.fit(s, under))
503 }
504 return lines
505}
506
507// ago is how long ago then was, from now, in its largest whole unit: 40s,
508// 19m, 5h, 3d.
509func ago(now, then int64) string {
510 d := max(now-then, 0)
511 switch {
512 case d < 60:
513 return fmt.Sprintf("%ds", d)
514 case d < 3600:
515 return fmt.Sprintf("%dm", d/60)
516 case d < 2*86400:
517 return fmt.Sprintf("%dh", d/3600)
518 }
519 return fmt.Sprintf("%dd", d/86400)
520}
521
522func parseUnix(s string) int64 {
523 n, _ := strconv.ParseInt(strings.TrimSpace(s), 10, 64)
524 return n
525}
526
527// draftStacks are a repository's drafts as stacks, measured, the stack
528// with the latest commit first.
529func (r listed) draftStacks(view jsonRepo, h handleMap, l listing) []*entry {
530 states := r.states()
531 var all []*entry
532 for _, c := range *view.Drafts {
533 all = append(all, r.changeEntry("drafts", c, h, l, states))
534 }
535 r.dated(all)
536 return r.snap.stack(all, true)
537}
538
539// branchStacks are a repository's branches that no change is on as
540// stacks, measured, the stack with the latest commit first.
541func (r listed) branchStacks(view jsonRepo) []*entry {
542 var all []*entry
543 for _, b := range view.Branches {
544 name := branchName(b.Branch)
545 all = append(all, &entry{section: "branches", repo: r.name, name: name, ref: name, head: b.Head})
546 }
547 r.dated(all)
548 return r.snap.stack(all, true)
549}
550
551// mainState is the project's main state (mainstate.go) as lines, or none
552// when origin has no main or the policy at its tip declares no nix follow
553// check. named puts the project's name after main. A policy or a walk that
554// did not read, or worker telemetry that did not, is said on stderr.
555func (r listed) mainState(h handleMap, c *costs, stderr io.Writer, t terminal, named bool) []string {
556 if r.snap.tip == "" {
557 return nil
558 }
559 end := phase("policy")
560 _, err := r.snap.layers()
561 end()
562 defer phase("main")()
563 if err != nil {
564 fmt.Fprintf(stderr, "valley: %s: the policy at main did not read, so main's state is not shown: %v\n", r.name, err)
565 return nil
566 }
567 model, err := r.snap.model()
568 walk := mainWalk{}
569 if err == nil {
570 keys := hostKeys{use: listEvidence}
571 defer keys.done()
572 walk, err = mainFollows(r.g, r.snap.tip, model, &keys, r.snap.evidence(), io.Discard)
573 }
574 if err != nil {
575 fmt.Fprintf(stderr, "valley: %s: main's state did not read: %v\n", r.name, err)
576 return nil
577 }
578 if len(walk.checks) == 0 {
579 return nil
580 }
581 read := c.start(r.g)
582 waited := phase("telemetry")
583 <-read.done
584 waited()
585 if read.why != "" {
586 fmt.Fprintf(stderr, "valley: %s: main's state shows no worker runs: %s\n", r.name, read.why)
587 }
588 lead := "main "
589 if named {
590 lead += r.name + " "
591 }
592 return t.mainLines(walk, lead, r.name, h, read.builds, read.mains)
593}
594
595// stack nests each entry under the nearest entry whose head strictly
596// contains its own, and gives each entry its base: the nearest entry its
597// own head strictly contains, as the rebase engine stacks layers
598// (rebase.Snapshot.Nest). Where two are equally near, the one with the
599// later commit is taken. It returns the entries nested under none, each the
600// top of a stack, the stack with the latest commit first. Each top lists
601// every entry nested under it, at any depth, in its below. With measured,
602// each entry is measured for its block.
603func (s *snapshot) stack(all []*entry, measured bool) []*entry {
604 nodes := make([]rebase.Node, len(all))
605 for i, e := range all {
606 nodes[i] = rebase.Node{Name: e.name, Head: e.head, When: e.when}
607 }
608 nest := s.land.Nest(nodes)
609 for i, e := range all {
610 for _, j := range nest.Inside[i] {
611 e.inside = append(e.inside, all[j])
612 }
613 if p := nest.Parent[i]; p >= 0 {
614 e.parent = all[p]
615 e.parent.kids = append(e.parent.kids, e)
616 }
617 }
618 var tops []*entry
619 for i, e := range all {
620 if b := nest.Base[i]; b >= 0 {
621 e.base = all[b]
622 }
623 if measured {
624 s.measure(e)
625 }
626 if e.parent == nil {
627 tops = append(tops, e)
628 }
629 }
630 for _, top := range tops {
631 top.list()
632 }
633 byActivity(tops, func(e *entry) int64 { return e.latest })
634 return tops
635}
636
637// list puts every entry nested under the top of a stack in its below, each
638// before the entries it contains. Where it can, it lists next the base of
639// the entry it listed last, so a chain is listed unbroken. Otherwise it
640// lists next the entry with the latest commit. It sets latest, the latest
641// commit time in the stack.
642func (top *entry) list() {
643 nested := map[*entry]bool{}
644 var walk func(e *entry)
645 walk = func(e *entry) {
646 for _, k := range e.kids {
647 nested[k] = true
648 walk(k)
649 }
650 }
651 walk(top)
652 top.latest = top.when
653 for last := top; len(nested) > 0; {
654 var free []*entry // those every entry containing them is listed before
655 for e := range nested {
656 listable := true
657 for _, c := range e.inside {
658 listable = listable && !nested[c]
659 }
660 if listable {
661 free = append(free, e)
662 }
663 }
664 byActivity(free, func(e *entry) int64 { return e.when })
665 next := free[0]
666 for _, e := range free {
667 if e == last.base {
668 next = e
669 }
670 }
671 delete(nested, next)
672 top.below = append(top.below, next)
673 top.latest = max(top.latest, next.when)
674 last = next
675 }
676}
677
678// byActivity orders entries latest first, and then by name.
679func byActivity(list []*entry, when func(*entry) int64) {
680 sort.SliceStable(list, func(i, j int) bool {
681 if a, b := when(list[i]), when(list[j]); a != b {
682 return a > b
683 }
684 return list[i].name < list[j].name
685 })
686}
687
688// measure reads what an entry adds to what it stands on: how many
689// commits, and the diff. It stands on the nearest of its base and every
690// landed version's head below it, as the rebase engine cuts a landed
691// version's commits from a family, or on its merge base with main when
692// there is none. A landed version's commits are not on main, since it
693// landed as one new commit, and its content is. A branch's title is the
694// subject of the first of the entry's own commits on its first-parent
695// line.
696func (s *snapshot) measure(e *entry) {
697 var below []string
698 for _, h := range s.land.LandedUnder(e.head) {
699 if h != e.head {
700 below = append(below, h)
701 }
702 }
703 if e.base != nil {
704 below = append(below, e.base.head)
705 }
706 var not []string
707 from := s.tip
708 for _, h := range below {
709 not = append(not, "^"+h)
710 // The heads below are all the entry's ancestors, and the nearest
711 // is the one that contains every other.
712 if from == s.tip || s.strictAncestor(from, h) {
713 from = h
714 }
715 }
716 if s.tip != "" {
717 not = append(not, "^"+s.tip)
718 }
719 if from == "" {
720 from, _ = s.g.input(true, strings.NewReader(""), "hash-object", "-t", "tree", "--stdin")
721 }
722 commits := "? commits"
723 if out, err := s.g.output(true, append([]string{"rev-list", "--count", e.head}, not...)...); err == nil {
724 n, _ := strconv.Atoi(out)
725 commits = counted(n, "commit")
726 }
727 files, added, deleted := 0, 0, 0
728 out, _ := s.g.output(true, "diff", "--numstat", from+"..."+e.head)
729 for _, line := range strings.Split(out, "\n") {
730 if f := strings.SplitN(line, "\t", 3); len(f) == 3 {
731 a, _ := strconv.Atoi(f[0]) // a binary file's counts are -, read as 0
732 d, _ := strconv.Atoi(f[1])
733 files, added, deleted = files+1, added+a, deleted+d
734 }
735 }
736 diff := "no file changes"
737 if files > 0 {
738 diff = fmt.Sprintf("%s +%d −%d", counted(files, "file"), added, deleted)
739 }
740 e.layer = commits + " · " + diff
741 if e.section == "branches" {
742 e.title = s.branchTitle(e.head, not)
743 }
744}
745
746// branchTitle is a branch's title: the subject of the first of its own
747// commits on its first-parent line, those its head reaches and not leaves
748// out.
749func (s *snapshot) branchTitle(head string, not []string) string {
750 out, _ := s.g.output(true, append([]string{"log", "--first-parent", "--reverse", "--format=%s", head}, not...)...)
751 first, _, _ := strings.Cut(out, "\n")
752 return readable(change.Title(first))
753}
754
755func counted(n int, noun string) string {
756 switch n {
757 case 0:
758 return "no " + noun + "s"
759 case 1:
760 return "1 " + noun
761 }
762 return fmt.Sprintf("%d %ss", n, noun)
763}
764
765// drawStack is the lines of a stack, each led by lead: the top entry's
766// block, then the block of each entry listed under it, at one indentation
767// however deep the stack is. Each listed entry is on the entry listed
768// right after it, and says "on <base>" where it is not. With named false,
769// the top's name line is left out, and its other lines are at lead
770// itself, for a row that already names it.
771func (t terminal) drawStack(top *entry, lead string, named bool) []string {
772 list := append([]*entry{top}, top.below...)
773 in := lead
774 if named {
775 in = lead + " "
776 }
777 var lines []string
778 for i, e := range list {
779 var next *entry
780 if i+1 < len(list) {
781 next = list[i+1]
782 }
783 first, rest := lead, in
784 switch {
785 case i > 0 && next != nil:
786 first, rest = in+"├ ", in+"│ "
787 case i > 0:
788 first, rest = in+"└ ", in+" "
789 }
790 if i > 0 || named {
791 lines = append(lines, t.nameLine(first, e.name, e, rest)...)
792 }
793 lines = append(lines, rest+t.titled(e, rest), rest+t.fit(e.layer, rest))
794 switch {
795 case e.base == next:
796 case e.base != nil:
797 lines = append(lines, rest+"on "+e.base.ref)
798 default:
799 lines = append(lines, rest+"on "+recordTarget)
800 }
801 lines = append(lines, prefixed(rest, e.includes)...)
802 for _, note := range append(append([]string{}, e.notes...), e.requires, e.checks) {
803 if note != "" {
804 lines = append(lines, rest+t.fit(note, rest))
805 }
806 }
807 if e.see != "" {
808 lines = append(lines, rest+" "+t.fit(e.see, rest+" "))
809 }
810 for _, s := range e.conflicts {
811 lines = append(lines, rest+t.fit(s, rest))
812 }
813 if i == 0 && len(top.below) > 0 {
814 lands := fmt.Sprintf("approving it lands the %d below too", len(top.below))
815 if len(top.below) == 1 {
816 lands = "approving it lands the one below too"
817 }
818 lines = append(lines, rest+t.fit(lands, rest))
819 }
820 }
821 return lines
822}
823
824// titled formats e's title line after lead, appending " · <knot ID>" when a
825// knot links the change. Long titles are truncated so the knot ID fits in
826// full.
827func (t terminal) titled(e *entry, lead string) string {
828 if e.knot == "" {
829 return t.fit(e.title, lead)
830 }
831 tail := " · " + e.knot
832 return fit(e.title, t.width-columns(lead+tail)) + tail
833}
834
835func prefixed(lead string, lines []string) []string {
836 var out []string
837 for _, l := range lines {
838 out = append(out, lead+l)
839 }
840 return out
841}
842
843// nameLine is an entry's first line: its name, in bold on a terminal,
844// then, for a draft whose checks were read, what they are as a row says a
845// ready change's (draftChecks), cut short to fit, and the head's age and
846// author at the right margin. When that leaves too little room, the
847// author is cut short. When even that leaves too little, the age and
848// author go on a line of their own, indented as rest is.
849func (t terminal) nameLine(lead, name string, e *entry, rest string) []string {
850 left := lead + t.strong(name)
851 used := columns(lead + name)
852 if glyph, says := draftChecks(e); says != "" {
853 left, used = left+" ", used+2
854 if glyph != "" {
855 left, used = left+t.tint(colourRefused, glyph)+" ", used+columns(glyph)+1
856 }
857 says = fit(says, t.width-used)
858 left, used = left+says, used+columns(says)
859 }
860 if e.age == "" && e.author == "" {
861 return []string{left}
862 }
863 right := e.age + " · " + e.author
864 if room := t.width - used - 2; columns(right) > room {
865 short := room - columns(e.age+" · ")
866 if short < 4 {
867 return []string{left, rest + t.fit(right, rest)}
868 }
869 right = e.age + " · " + fit(e.author, short)
870 }
871 return []string{left + strings.Repeat(" ", t.width-used-columns(right)) + right}
872}
873
874// draftChecks is a draft's checks as its name line says them, in the
875// words a ready change's row uses: passed out of required, how many are
876// pending, or, with the glyph ✗, what the worker reports of a pending
877// check's failed build (rowChecks), or the checks that failed. says is ""
878// for another entry, or a draft whose checks were not read.
879func draftChecks(e *entry) (glyph, says string) {
880 switch {
881 case e.section != "drafts" || e.state == nil:
882 return "", ""
883 case e.state.State == checkFailed:
884 return "✗", failedNames(e.state) + " failed"
885 }
886 return rowChecks(e.state)
887}
888
889// branchName is a branch's name as printed: as it is, or, when it holds a
890// character that is not printable or bytes that are not UTF-8, in the
891// $'...' form a shell reads back as the same name.
892func branchName(b string) string {
893 if printable(b) {
894 return b
895 }
896 return shellQuote(b)
897}
898
899// readable is s as text to print: valid UTF-8, with every control
900// character, which a terminal could act on, made a space.
901func readable(s string) string {
902 return strings.Map(func(r rune) rune {
903 if unicode.IsControl(r) {
904 return ' '
905 }
906 return r
907 }, strings.ToValidUTF8(s, "�"))
908}
909
910// checks says how many checks the policy at main's tip requires of a
911// head, by cost, derived against the merge base with main.
912func (s *snapshot) checks(head string) string {
913 base, err := s.g.output(true, "merge-base", s.tip, head)
914 if err != nil {
915 return "requires ? (no merge base with main)"
916 }
917 model, err := s.model()
918 if err != nil {
919 return "requires ? (the policy did not derive)"
920 }
921 processStarted()
922 paths, err := derive.Diff(context.Background(), s.g.dir, s.g.env, base, head)
923 if err != nil {
924 return "requires ? (the policy did not derive)"
925 }
926 res, err := derive.Derive(model, paths)
927 if err != nil {
928 return "requires ? (the policy did not derive)"
929 }
930 quick, slow := 0, 0
931 for _, q := range res.Required {
932 if costOf(q) == "slow" {
933 slow++
934 } else {
935 quick++
936 }
937 }
938 if quick+slow == 0 {
939 return "requires no checks"
940 }
941 noun := "checks"
942 if quick == 1 {
943 noun = "check"
944 }
945 return fmt.Sprintf("requires %d quick %s, %d slow", quick, noun, slow)
946}
947
948// tipPolicy is the policy at main's tip on origin, read once for every
949// reader of a snapshot: mainState, the carry verdicts, the version checks
950// and the check counts. Nothing is read until a reader asks, and a failure
951// is kept, so each reader says it its own way.
952type tipPolicy struct {
953 read bool
954 src layerSource
955 done func()
956 err error
957 modelRead bool
958 model *composed.Model
959 modelErr error
960}
961
962// layers are the two policy layers at main's tip.
963func (s *snapshot) layers() (layerSource, error) {
964 p := &s.policy
965 if !p.read {
966 p.read = true
967 p.src, p.done, p.err = resolveLayers(s.g, s.tip, "", "")
968 }
969 return p.src, p.err
970}
971
972// model is the policy the layers at main's tip compose, read without
973// asking which requirements are mandatory (composed.ReadUnpinned): what
974// each reader of a snapshot prints or decides comes from which checks a
975// change requires, how each runs and what it costs, and the carry mode,
976// never from a requirement's pin.
977func (s *snapshot) model() (*composed.Model, error) {
978 p := &s.policy
979 if !p.modelRead {
980 p.modelRead = true
981 p.model, p.modelErr = func() (*composed.Model, error) {
982 src, err := s.layers()
983 if err != nil {
984 return nil, err
985 }
986 schema, err := schemaFile(s.g, "")
987 if err != nil {
988 return nil, err
989 }
990 return policyModel(schema, src.instance, src.project, false)
991 }()
992 }
993 return p.model, p.modelErr
994}
995
996// close removes the layers the snapshot read.
997func (s *snapshot) close() {
998 if s.policy.done != nil {
999 s.policy.done()
1000 s.policy.done = nil
1001 }
1002}