gunk-dev/the-valley

pending.go

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