gunk-dev/the-valley

pending.go

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