gunk-dev/the-valley

pending.go

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