gunk-dev/the-valley

pending.go

source1c37c8d22741main's published tip history
27.5 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 record string // the change's record commit
214 name string // what the block's first line names
215 ref string // what the entry is typed as: its handle, or its branch
216 head string // the head commit
217 title string // the record's title; for a branch, read by measure
218 knot string // ID of the first knot that links the change (does.go)
219 includes []string // what includes names that is no entry here
220 notes []string // uncertain and restack
221 requires string // with --checks, the checks the policy requires of it, by cost
222 checks string // the check state line of a ready change
223 state *jsonVersionChecks // the check state its row counts, or nil when its checks were not read
224
225 glyph, colour, says string // for a moving change, its glyph and what its row says
226
227 when int64 // the head's commit time
228 since int64 // for a change, its record's commit time: when its active version became ready
229 age, author string
230 layer string // the commits and the diff it adds to its base
231
232 parent *entry // the entry it is listed under, if any
233 kids []*entry // the entries nested right under it
234 base *entry // nil for main
235 inside []*entry // every entry whose head strictly contains its own
236 below []*entry // for the top of a stack, every entry listed under it
237 latest int64 // for the top of a stack, the latest commit time in it
238}
239
240// writePending prints the listing of every repository: the main lines,
241// needs you, moving, and the drafts and branches. named says whether each
242// line names its project.
243func writePending(repos []listed, h handleMap, l listing, c *costs, w, stderr io.Writer, t terminal, named bool) {
244 p := func(format string, args ...any) { fmt.Fprintf(w, format, args...) }
245 head := false
246 for _, r := range repos {
247 if r.err != nil {
248 p("%s: %v\n", r.name, r.err)
249 head = true
250 continue
251 }
252 for _, line := range r.mainState(h, c, stderr, t, named) {
253 p("%s\n", line)
254 head = true
255 }
256 }
257 if head {
258 p("\n")
259 }
260 var waiting, moving []*entry
261 var drafts, branches []block
262 nDrafts, nBranches := 0, 0
263 for _, r := range repos {
264 if r.err != nil {
265 continue
266 }
267 view := r.pendingView(h)
268 r.addChecks(&view, c, stderr)
269 wa, mo := r.queue(view, h, l, l.verbose)
270 waiting, moving = append(waiting, wa...), append(moving, mo...)
271 nDrafts, nBranches = nDrafts+len(*view.Drafts), nBranches+len(view.Branches)
272 if l.drafts && len(*view.Drafts) > 0 {
273 drafts = append(drafts, block{r.name, r.draftStacks(view, h, l)})
274 }
275 if l.branches && len(view.Branches) > 0 {
276 branches = append(branches, block{r.name, r.branchStacks(view)})
277 }
278 }
279 byLanding(waiting)
280 byLanding(moving)
281 for _, line := range t.rows(waiting, moving, l, named) {
282 p("%s\n", line)
283 }
284 for _, b := range []struct {
285 name string
286 blocks []block
287 }{{"drafts", drafts}, {"branches", branches}} {
288 for _, bl := range b.blocks {
289 header := b.name
290 if named {
291 header += " · " + bl.repo
292 }
293 p("\n%s\n", header)
294 for i, top := range bl.tops {
295 if i > 0 {
296 p("\n")
297 }
298 for _, line := range t.drawStack(top, "", true) {
299 p("%s\n", line)
300 }
301 }
302 }
303 }
304 var counts, flags []string
305 if n := nDrafts; n > 0 && !l.drafts {
306 counts, flags = append(counts, counted(n, "draft")), append(flags, "--drafts")
307 }
308 if n := nBranches; n > 0 && !l.branches {
309 noun := "branches"
310 if n == 1 {
311 noun = "branch"
312 }
313 counts, flags = append(counts, fmt.Sprintf("%d %s no change is on", n, noun)), append(flags, "--branches")
314 }
315 if len(counts) > 0 {
316 p("\n%s\n", strings.Join(counts, " · ")+" · valley pending "+strings.Join(flags, " "))
317 }
318}
319
320// block is one project's stacks of drafts or of branches.
321type block struct {
322 repo string
323 tops []*entry
324}
325
326// rows is needs you and moving as lines: each section's heading, then its
327// rows. A row of needs you is numbered and has its title under it; with
328// -v, a row of either is followed by its block.
329func (t terminal) rows(waiting, moving []*entry, l listing, named bool) []string {
330 var lines []string
331 projects, names := 0, 0
332 for _, e := range append(append([]*entry{}, waiting...), moving...) {
333 projects, names = max(projects, columns(e.repo)), max(names, columns(e.name))
334 }
335 // lead is a row's project and name, each padded to its column.
336 lead := func(e *entry) string {
337 s := t.strong(e.name) + strings.Repeat(" ", names-columns(e.name))
338 if named {
339 s = e.repo + strings.Repeat(" ", projects-columns(e.repo)) + " " + s
340 }
341 return s
342 }
343 width := names
344 if named {
345 width += projects + 2
346 }
347 if len(waiting) == 0 {
348 lines = append(lines, "nothing needs you")
349 } else {
350 lines = append(lines, fmt.Sprintf("needs you (%d, in landing order)", len(waiting)))
351 }
352 digits := len(strconv.Itoa(len(waiting)))
353 now := time.Now().Unix()
354 for i, e := range waiting {
355 num := fmt.Sprintf(" %*d ", digits, i+1)
356 under := strings.Repeat(" ", columns(num))
357 says := checkCount(e.state)
358 if len(e.below) > 0 {
359 says = strings.TrimPrefix(says+" · stack of "+strconv.Itoa(len(e.below)+1), " · ")
360 }
361 left := num + lead(e) + " " + says
362 used := columns(num) + width + 2 + columns(says)
363 age := ago(now, e.since)
364 if pad := t.width - used - columns(age); pad >= 2 && e.since > 0 {
365 left += strings.Repeat(" ", pad) + age
366 } else if e.since > 0 {
367 left += " " + age
368 }
369 lines = append(lines, strings.TrimRight(left, " "))
370 lines = append(lines, t.details(e, under, l)...)
371 }
372 if len(moving) == 0 {
373 return lines
374 }
375 lines = append(lines, "", fmt.Sprintf("moving (%d)", len(moving)))
376 for _, e := range moving {
377 first := " " + t.tint(e.colour, e.glyph) + " "
378 used := columns(" "+e.glyph+" ") + width + 2
379 lines = append(lines, first+lead(e)+" "+fit(e.says, t.width-used))
380 lines = append(lines, t.details(e, " ", l)...)
381 }
382 return lines
383}
384
385// details are the lines under a row, each led by under: for a row of
386// needs you, its title; with --checks, its checks; with -v, its block in
387// place of both.
388func (t terminal) details(e *entry, under string, l listing) []string {
389 if l.verbose {
390 return t.drawStack(e, under, false)
391 }
392 var lines []string
393 if e.section == "ready" && e.glyph == "" {
394 lines = append(lines, under+t.titled(e, under))
395 }
396 if l.checks {
397 for _, s := range []string{e.requires, e.checks} {
398 if s != "" {
399 lines = append(lines, under+t.fit(s, under))
400 }
401 }
402 }
403 return lines
404}
405
406// ago is how long ago then was, from now, in its largest whole unit: 40s,
407// 19m, 5h, 3d.
408func ago(now, then int64) string {
409 d := max(now-then, 0)
410 switch {
411 case d < 60:
412 return fmt.Sprintf("%ds", d)
413 case d < 3600:
414 return fmt.Sprintf("%dm", d/60)
415 case d < 2*86400:
416 return fmt.Sprintf("%dh", d/3600)
417 }
418 return fmt.Sprintf("%dd", d/86400)
419}
420
421func parseUnix(s string) int64 {
422 n, _ := strconv.ParseInt(strings.TrimSpace(s), 10, 64)
423 return n
424}
425
426// draftStacks are a repository's drafts as stacks, measured, the stack
427// with the latest commit first.
428func (r listed) draftStacks(view jsonRepo, h handleMap, l listing) []*entry {
429 states := r.states()
430 var all []*entry
431 for _, c := range *view.Drafts {
432 all = append(all, r.changeEntry("drafts", c, h, l, states))
433 }
434 r.dated(all)
435 return r.snap.stack(all, true)
436}
437
438// branchStacks are a repository's branches that no change is on as
439// stacks, measured, the stack with the latest commit first.
440func (r listed) branchStacks(view jsonRepo) []*entry {
441 var all []*entry
442 for _, b := range view.Branches {
443 name := branchName(b.Branch)
444 all = append(all, &entry{section: "branches", repo: r.name, name: name, ref: name, head: b.Head})
445 }
446 r.dated(all)
447 return r.snap.stack(all, true)
448}
449
450// mainState is the project's main state (mainstate.go) as lines, or none
451// when origin has no main or the policy at its tip declares no nix follow
452// check. named puts the project's name after main. A policy or a walk that
453// did not read, or worker telemetry that did not, is said on stderr.
454func (r listed) mainState(h handleMap, c *costs, stderr io.Writer, t terminal, named bool) []string {
455 if r.snap.tip == "" {
456 return nil
457 }
458 instance, project, done, err := policyLayers(r.g, r.snap.tip)
459 defer done()
460 if err != nil {
461 fmt.Fprintf(stderr, "valley: %s: the policy at main did not read, so main's state is not shown: %v\n", r.name, err)
462 return nil
463 }
464 walk, err := mainFollows(r.g, r.snap.tip, instance, project, io.Discard)
465 if err != nil {
466 fmt.Fprintf(stderr, "valley: %s: main's state did not read: %v\n", r.name, err)
467 return nil
468 }
469 if len(walk.checks) == 0 {
470 return nil
471 }
472 read := c.start(r.g)
473 <-read.done
474 if read.why != "" {
475 fmt.Fprintf(stderr, "valley: %s: main's state shows no worker runs: %s\n", r.name, read.why)
476 }
477 lead := "main "
478 if named {
479 lead += r.name + " "
480 }
481 return t.mainLines(walk, lead, r.name, h, read.builds, read.mains)
482}
483
484// stack nests each entry under the nearest entry whose head strictly
485// contains its own, and gives each entry its base: the nearest entry its
486// own head strictly contains, as the rebase engine stacks layers
487// (rebase.Snapshot.Nest). Where two are equally near, the one with the
488// later commit is taken. It returns the entries nested under none, each the
489// top of a stack, the stack with the latest commit first. Each top lists
490// every entry nested under it, at any depth, in its below. With measured,
491// each entry is measured for its block.
492func (s *snapshot) stack(all []*entry, measured bool) []*entry {
493 nodes := make([]rebase.Node, len(all))
494 for i, e := range all {
495 nodes[i] = rebase.Node{Name: e.name, Head: e.head, When: e.when}
496 }
497 nest := s.land.Nest(nodes)
498 for i, e := range all {
499 for _, j := range nest.Inside[i] {
500 e.inside = append(e.inside, all[j])
501 }
502 if p := nest.Parent[i]; p >= 0 {
503 e.parent = all[p]
504 e.parent.kids = append(e.parent.kids, e)
505 }
506 }
507 var tops []*entry
508 for i, e := range all {
509 if b := nest.Base[i]; b >= 0 {
510 e.base = all[b]
511 }
512 if measured {
513 s.measure(e)
514 }
515 if e.parent == nil {
516 tops = append(tops, e)
517 }
518 }
519 for _, top := range tops {
520 top.list()
521 }
522 byActivity(tops, func(e *entry) int64 { return e.latest })
523 return tops
524}
525
526// list puts every entry nested under the top of a stack in its below, each
527// before the entries it contains. Where it can, it lists next the base of
528// the entry it listed last, so a chain is listed unbroken. Otherwise it
529// lists next the entry with the latest commit. It sets latest, the latest
530// commit time in the stack.
531func (top *entry) list() {
532 nested := map[*entry]bool{}
533 var walk func(e *entry)
534 walk = func(e *entry) {
535 for _, k := range e.kids {
536 nested[k] = true
537 walk(k)
538 }
539 }
540 walk(top)
541 top.latest = top.when
542 for last := top; len(nested) > 0; {
543 var free []*entry // those every entry containing them is listed before
544 for e := range nested {
545 listable := true
546 for _, c := range e.inside {
547 listable = listable && !nested[c]
548 }
549 if listable {
550 free = append(free, e)
551 }
552 }
553 byActivity(free, func(e *entry) int64 { return e.when })
554 next := free[0]
555 for _, e := range free {
556 if e == last.base {
557 next = e
558 }
559 }
560 delete(nested, next)
561 top.below = append(top.below, next)
562 top.latest = max(top.latest, next.when)
563 last = next
564 }
565}
566
567// byActivity orders entries latest first, and then by name.
568func byActivity(list []*entry, when func(*entry) int64) {
569 sort.SliceStable(list, func(i, j int) bool {
570 if a, b := when(list[i]), when(list[j]); a != b {
571 return a > b
572 }
573 return list[i].name < list[j].name
574 })
575}
576
577// measure reads what an entry adds to what it stands on: how many
578// commits, and the diff. It stands on the nearest of its base and every
579// landed version's head below it, as the rebase engine cuts a landed
580// version's commits from a family, or on its merge base with main when
581// there is none. A landed version's commits are not on main, since it
582// landed as one new commit, and its content is. A branch's title is the
583// subject of the first of the entry's own commits on its first-parent
584// line.
585func (s *snapshot) measure(e *entry) {
586 var below []string
587 for _, h := range s.land.LandedUnder(e.head) {
588 if h != e.head {
589 below = append(below, h)
590 }
591 }
592 if e.base != nil {
593 below = append(below, e.base.head)
594 }
595 var not []string
596 from := s.tip
597 for _, h := range below {
598 not = append(not, "^"+h)
599 // The heads below are all the entry's ancestors, and the nearest
600 // is the one that contains every other.
601 if from == s.tip || s.strictAncestor(from, h) {
602 from = h
603 }
604 }
605 if s.tip != "" {
606 not = append(not, "^"+s.tip)
607 }
608 if from == "" {
609 from, _ = s.g.input(true, strings.NewReader(""), "hash-object", "-t", "tree", "--stdin")
610 }
611 commits := "? commits"
612 if out, err := s.g.output(true, append([]string{"rev-list", "--count", e.head}, not...)...); err == nil {
613 n, _ := strconv.Atoi(out)
614 commits = counted(n, "commit")
615 }
616 files, added, deleted := 0, 0, 0
617 out, _ := s.g.output(true, "diff", "--numstat", from+"..."+e.head)
618 for _, line := range strings.Split(out, "\n") {
619 if f := strings.SplitN(line, "\t", 3); len(f) == 3 {
620 a, _ := strconv.Atoi(f[0]) // a binary file's counts are -, read as 0
621 d, _ := strconv.Atoi(f[1])
622 files, added, deleted = files+1, added+a, deleted+d
623 }
624 }
625 diff := "no file changes"
626 if files > 0 {
627 diff = fmt.Sprintf("%s +%d −%d", counted(files, "file"), added, deleted)
628 }
629 e.layer = commits + " · " + diff
630 if e.section == "branches" {
631 e.title = s.branchTitle(e.head, not)
632 }
633}
634
635// branchTitle is a branch's title: the subject of the first of its own
636// commits on its first-parent line, those its head reaches and not leaves
637// out.
638func (s *snapshot) branchTitle(head string, not []string) string {
639 out, _ := s.g.output(true, append([]string{"log", "--first-parent", "--reverse", "--format=%s", head}, not...)...)
640 first, _, _ := strings.Cut(out, "\n")
641 return readable(change.Title(first))
642}
643
644func counted(n int, noun string) string {
645 switch n {
646 case 0:
647 return "no " + noun + "s"
648 case 1:
649 return "1 " + noun
650 }
651 return fmt.Sprintf("%d %ss", n, noun)
652}
653
654// drawStack is the lines of a stack, each led by lead: the top entry's
655// block, then the block of each entry listed under it, at one indentation
656// however deep the stack is. Each listed entry is on the entry listed
657// right after it, and says "on <base>" where it is not. With named false,
658// the top's name line is left out, and its other lines are at lead
659// itself, for a row that already names it.
660func (t terminal) drawStack(top *entry, lead string, named bool) []string {
661 list := append([]*entry{top}, top.below...)
662 in := lead
663 if named {
664 in = lead + " "
665 }
666 var lines []string
667 for i, e := range list {
668 var next *entry
669 if i+1 < len(list) {
670 next = list[i+1]
671 }
672 first, rest := lead, in
673 switch {
674 case i > 0 && next != nil:
675 first, rest = in+"├ ", in+"│ "
676 case i > 0:
677 first, rest = in+"└ ", in+" "
678 }
679 if i > 0 || named {
680 lines = append(lines, t.nameLine(first, e.name, e, rest)...)
681 }
682 lines = append(lines, rest+t.titled(e, rest), rest+t.fit(e.layer, rest))
683 switch {
684 case e.base == next:
685 case e.base != nil:
686 lines = append(lines, rest+"on "+e.base.ref)
687 default:
688 lines = append(lines, rest+"on "+recordTarget)
689 }
690 lines = append(lines, prefixed(rest, e.includes)...)
691 for _, note := range append(append([]string{}, e.notes...), e.requires, e.checks) {
692 if note != "" {
693 lines = append(lines, rest+t.fit(note, rest))
694 }
695 }
696 if i == 0 && len(top.below) > 0 {
697 lands := fmt.Sprintf("approving it lands the %d below too", len(top.below))
698 if len(top.below) == 1 {
699 lands = "approving it lands the one below too"
700 }
701 lines = append(lines, rest+t.fit(lands, rest))
702 }
703 }
704 return lines
705}
706
707// titled formats e's title line after lead, appending " · <knot ID>" when a
708// knot links the change. Long titles are truncated so the knot ID fits in
709// full.
710func (t terminal) titled(e *entry, lead string) string {
711 if e.knot == "" {
712 return t.fit(e.title, lead)
713 }
714 tail := " · " + e.knot
715 return fit(e.title, t.width-columns(lead+tail)) + tail
716}
717
718func prefixed(lead string, lines []string) []string {
719 var out []string
720 for _, l := range lines {
721 out = append(out, lead+l)
722 }
723 return out
724}
725
726// nameLine is an entry's first line: its name, in bold on a terminal, and
727// the head's age and author at the right margin. When that leaves too
728// little room, the author is cut short. When even that leaves too little,
729// the age and author go on a line of their own, indented as rest is.
730func (t terminal) nameLine(lead, name string, e *entry, rest string) []string {
731 left := lead + t.strong(name)
732 used := columns(lead + name)
733 if e.age == "" && e.author == "" {
734 return []string{left}
735 }
736 right := e.age + " · " + e.author
737 if room := t.width - used - 2; columns(right) > room {
738 short := room - columns(e.age+" · ")
739 if short < 4 {
740 return []string{left, rest + t.fit(right, rest)}
741 }
742 right = e.age + " · " + fit(e.author, short)
743 }
744 return []string{left + strings.Repeat(" ", t.width-used-columns(right)) + right}
745}
746
747// branchName is a branch's name as printed: as it is, or, when it holds a
748// character that is not printable or bytes that are not UTF-8, in the
749// $'...' form a shell reads back as the same name.
750func branchName(b string) string {
751 if printable(b) {
752 return b
753 }
754 return shellQuote(b)
755}
756
757// readable is s as text to print: valid UTF-8, with every control
758// character, which a terminal could act on, made a space.
759func readable(s string) string {
760 return strings.Map(func(r rune) rune {
761 if unicode.IsControl(r) {
762 return ' '
763 }
764 return r
765 }, strings.ToValidUTF8(s, "�"))
766}
767
768// checks says how many checks the policy requires of a head, by cost, as
769// valley checks derives them against the merge base with main. It runs
770// the valley command bin/valley names in VALLEY_COMMAND, inside the
771// repository the change is in.
772func (s *snapshot) checks(head string) string {
773 valley := os.Getenv("VALLEY_COMMAND")
774 if valley == "" {
775 valley = "valley"
776 }
777 base, err := s.g.output(true, "merge-base", s.tip, head)
778 if err != nil {
779 return "requires ? (no merge base with main)"
780 }
781 cmd := exec.Command(valley, "checks", base, head)
782 cmd.Dir = s.g.dir
783 cmd.Env = s.g.env
784 out, err := cmd.Output()
785 if err != nil {
786 return "requires ? (the policy did not derive)"
787 }
788 count := func(prefix string) int {
789 for _, line := range strings.Split(string(out), "\n") {
790 if rest, ok := strings.CutPrefix(line, prefix); ok && rest != "none" {
791 return len(strings.Split(rest, ", "))
792 }
793 }
794 return 0
795 }
796 quick, slow := count("quick: "), count("slow: ")
797 if quick+slow == 0 {
798 return "requires no checks"
799 }
800 noun := "checks"
801 if quick == 1 {
802 noun = "check"
803 }
804 return fmt.Sprintf("requires %d quick %s, %d slow", quick, noun, slow)
805}