gunk-dev/the-valley

pending.go

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