gunk-dev/the-valley

pending.go

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