gunk-dev/the-valley

pending.go

source7309e1d6b8bbmain's published tip history
29.0 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 "context"
119 "fmt"
120 "io"
121 "sort"
122 "strconv"
123 "strings"
124 "time"
125 "unicode"
126
127 "the-valley/change"
128 "the-valley/composed"
129 "the-valley/derive"
130 "the-valley/rebase"
131)
132
133// pendingChange is a ready change that has not landed as any version.
134func pendingChange(s *snapshot, n recorded) bool {
135 return n.record.State == change.Ready && !s.isLanded(n)
136}
137
138// approvedVersion reports whether a ready change's active version has an
139// integration request at its head. That is the simple rule: the integrator
140// also accepts a request that names an earlier head whose approval carries
141// to this version, which needs the delta between the two and the policy's
142// carry mode. A version approved only by carry is not counted here, so
143// valley pending lists it with the changes awaiting approval.
144func (s *snapshot) approvedVersion(id string, r *change.Record) bool {
145 return r.State == change.Ready && s.request(id, r.ActiveVersion()) != nil
146}
147
148// unlanded is a change in any state that has not landed as any version:
149// the changes a pending change may include.
150func unlanded(s *snapshot, n recorded) bool {
151 return !s.isLanded(n)
152}
153
154func isDraft(_ *snapshot, n recorded) bool {
155 return n.record.State == change.Draft
156}
157
158// pendingView is a repository as valley-pending/v1 writes it: the pending
159// changes in changes and the drafts in drafts, each with includes among
160// the changes that have not landed.
161func (l listed) pendingView(h handleMap) jsonRepo {
162 r := l.repoView(h, pendingChange, unlanded)
163 if l.err == nil {
164 for i, c := range r.Changes {
165 approved := c.Versions[c.Active-1].Request != nil
166 r.Changes[i].Approved = &approved
167 }
168 }
169 drafts := []jsonChange{}
170 if l.err == nil {
171 drafts = l.repoView(h, isDraft, unlanded).Changes
172 }
173 r.Drafts = &drafts
174 return r
175}
176
177func runPending(g git, args []string, stdout, stderr io.Writer) error {
178 l, err := parseListing("pending", args, true)
179 if err != nil {
180 return err
181 }
182 list, host, err := sources(g, l, stderr)
183 if err != nil {
184 return err
185 }
186 repos := readSources(list, newVerifier())
187 defer closeSources(repos)
188 readKnots(repos, l.verbose, stderr)
189 h := handles(repos)
190 writeHandleCache(g, repos, h)
191 defer warnUnverified(repos, stderr)
192 if l.asJSON {
193 doc := jsonChanges{Schema: pendingSchema, Host: host, Repos: []jsonRepo{}}
194 c := newCosts()
195 for _, r := range repos {
196 view := r.pendingView(h)
197 if l.checks {
198 r.addChecks(&view, c, stderr)
199 }
200 utf8Branches(&view, stderr)
201 doc.Repos = append(doc.Repos, view)
202 }
203 return writeDocument(stdout, doc)
204 }
205 writePending(repos, h, l, newCosts(), stdout, stderr, terminalOf(stdout), len(repos) > 1 || l.all || l.repo != "")
206 return nil
207}
208
209// entry is one row or block of valley pending: a ready change, a draft,
210// or a branch no record is on.
211type entry struct {
212 section string
213 repo string // the project it is in
214 id string // the change ID, for a change
215 version int // a change's active version
216 record string // the change's record commit
217 name string // what the block's first line names
218 ref string // what the entry is typed as: its handle, or its branch
219 head string // the head commit
220 title string // the record's title; for a branch, read by measure
221 knot string // ID of the first knot that links the change (does.go)
222 includes []string // what includes names that is no entry here
223 notes []string // uncertain and restack
224 requires string // with --checks, the checks the policy requires of it, by cost
225 checks string // the check state line of a ready change
226 state *jsonVersionChecks // the check state its row counts, or nil when its checks were not read
227
228 glyph, colour, says string // for a moving change, its glyph and what its row says
229
230 when int64 // the head's commit time
231 since int64 // for a change, its record's commit time: when its active version became ready
232 age, author string
233 layer string // the commits and the diff it adds to its base
234
235 parent *entry // the entry it is listed under, if any
236 kids []*entry // the entries nested right under it
237 base *entry // nil for main
238 inside []*entry // every entry whose head strictly contains its own
239 below []*entry // for the top of a stack, every entry listed under it
240 latest int64 // for the top of a stack, the latest commit time in it
241}
242
243// writePending prints the listing of every repository: the main lines,
244// needs you, moving, and the drafts and branches. named says whether each
245// line names its project.
246func writePending(repos []listed, h handleMap, l listing, c *costs, w, stderr io.Writer, t terminal, named bool) {
247 p := func(format string, args ...any) { fmt.Fprintf(w, format, args...) }
248 head := false
249 for _, r := range repos {
250 if r.err != nil {
251 p("%s: %v\n", r.name, r.err)
252 head = true
253 continue
254 }
255 for _, line := range r.mainState(h, c, stderr, t, named) {
256 p("%s\n", line)
257 head = true
258 }
259 }
260 if head {
261 p("\n")
262 }
263 defer phase("branches")()
264 var drafts, branches []block
265 nDrafts, nBranches := 0, 0
266 waiting, moving := operatorQueue(repos, h, l, c, stderr, func(r listed, view jsonRepo) {
267 nDrafts, nBranches = nDrafts+len(*view.Drafts), nBranches+len(view.Branches)
268 if l.drafts && len(*view.Drafts) > 0 {
269 drafts = append(drafts, block{r.name, r.draftStacks(view, h, l)})
270 }
271 if l.branches && len(view.Branches) > 0 {
272 branches = append(branches, block{r.name, r.branchStacks(view)})
273 }
274 })
275 for _, line := range t.rows(waiting, moving, l, named) {
276 p("%s\n", line)
277 }
278 for _, b := range []struct {
279 name string
280 blocks []block
281 }{{"drafts", drafts}, {"branches", branches}} {
282 for _, bl := range b.blocks {
283 header := b.name
284 if named {
285 header += " · " + bl.repo
286 }
287 p("\n%s\n", header)
288 for i, top := range bl.tops {
289 if i > 0 {
290 p("\n")
291 }
292 for _, line := range t.drawStack(top, "", true) {
293 p("%s\n", line)
294 }
295 }
296 }
297 }
298 var counts, flags []string
299 if n := nDrafts; n > 0 && !l.drafts {
300 counts, flags = append(counts, counted(n, "draft")), append(flags, "--drafts")
301 }
302 if n := nBranches; n > 0 && !l.branches {
303 noun := "branches"
304 if n == 1 {
305 noun = "branch"
306 }
307 counts, flags = append(counts, fmt.Sprintf("%d %s no change is on", n, noun)), append(flags, "--branches")
308 }
309 if len(counts) > 0 {
310 p("\n%s\n", strings.Join(counts, " · ")+" · valley pending "+strings.Join(flags, " "))
311 }
312}
313
314// block is one project's stacks of drafts or of branches.
315type block struct {
316 repo string
317 tops []*entry
318}
319
320// rows is needs you and moving as lines: each section's heading, then its
321// rows. A row of needs you is numbered and has its title under it; with
322// -v, a row of either is followed by its block.
323func (t terminal) rows(waiting, moving []*entry, l listing, named bool) []string {
324 var lines []string
325 projects, names := 0, 0
326 for _, e := range append(append([]*entry{}, waiting...), moving...) {
327 projects, names = max(projects, columns(e.repo)), max(names, columns(e.name))
328 }
329 // lead is a row's project and name, each padded to its column.
330 lead := func(e *entry) string {
331 s := t.strong(e.name) + strings.Repeat(" ", names-columns(e.name))
332 if named {
333 s = e.repo + strings.Repeat(" ", projects-columns(e.repo)) + " " + s
334 }
335 return s
336 }
337 width := names
338 if named {
339 width += projects + 2
340 }
341 if len(waiting) == 0 {
342 lines = append(lines, "nothing needs you")
343 } else {
344 lines = append(lines, fmt.Sprintf("needs you (%d, in landing order)", len(waiting)))
345 }
346 digits := len(strconv.Itoa(len(waiting)))
347 now := time.Now().Unix()
348 for i, e := range waiting {
349 num := fmt.Sprintf(" %*d ", digits, i+1)
350 under := strings.Repeat(" ", columns(num))
351 says := checkCount(e.state)
352 if len(e.below) > 0 {
353 says = strings.TrimPrefix(says+" · stack of "+strconv.Itoa(len(e.below)+1), " · ")
354 }
355 left := num + lead(e) + " " + says
356 used := columns(num) + width + 2 + columns(says)
357 age := ago(now, e.since)
358 if pad := t.width - used - columns(age); pad >= 2 && e.since > 0 {
359 left += strings.Repeat(" ", pad) + age
360 } else if e.since > 0 {
361 left += " " + age
362 }
363 lines = append(lines, strings.TrimRight(left, " "))
364 lines = append(lines, t.details(e, under, l)...)
365 }
366 if len(moving) == 0 {
367 return lines
368 }
369 lines = append(lines, "", fmt.Sprintf("moving (%d)", len(moving)))
370 for _, e := range moving {
371 first := " " + t.tint(e.colour, e.glyph) + " "
372 used := columns(" "+e.glyph+" ") + width + 2
373 lines = append(lines, first+lead(e)+" "+fit(e.says, t.width-used))
374 lines = append(lines, t.details(e, " ", l)...)
375 }
376 return lines
377}
378
379// details are the lines under a row, each led by under: for a row of
380// needs you, its title; with --checks, its checks; with -v, its block in
381// place of both.
382func (t terminal) details(e *entry, under string, l listing) []string {
383 if l.verbose {
384 return t.drawStack(e, under, false)
385 }
386 var lines []string
387 if e.section == "ready" && e.glyph == "" {
388 lines = append(lines, under+t.titled(e, under))
389 }
390 if l.checks {
391 for _, s := range []string{e.requires, e.checks} {
392 if s != "" {
393 lines = append(lines, under+t.fit(s, under))
394 }
395 }
396 }
397 return lines
398}
399
400// ago is how long ago then was, from now, in its largest whole unit: 40s,
401// 19m, 5h, 3d.
402func ago(now, then int64) string {
403 d := max(now-then, 0)
404 switch {
405 case d < 60:
406 return fmt.Sprintf("%ds", d)
407 case d < 3600:
408 return fmt.Sprintf("%dm", d/60)
409 case d < 2*86400:
410 return fmt.Sprintf("%dh", d/3600)
411 }
412 return fmt.Sprintf("%dd", d/86400)
413}
414
415func parseUnix(s string) int64 {
416 n, _ := strconv.ParseInt(strings.TrimSpace(s), 10, 64)
417 return n
418}
419
420// draftStacks are a repository's drafts as stacks, measured, the stack
421// with the latest commit first.
422func (r listed) draftStacks(view jsonRepo, h handleMap, l listing) []*entry {
423 states := r.states()
424 var all []*entry
425 for _, c := range *view.Drafts {
426 all = append(all, r.changeEntry("drafts", c, h, l, states))
427 }
428 r.dated(all)
429 return r.snap.stack(all, true)
430}
431
432// branchStacks are a repository's branches that no change is on as
433// stacks, measured, the stack with the latest commit first.
434func (r listed) branchStacks(view jsonRepo) []*entry {
435 var all []*entry
436 for _, b := range view.Branches {
437 name := branchName(b.Branch)
438 all = append(all, &entry{section: "branches", repo: r.name, name: name, ref: name, head: b.Head})
439 }
440 r.dated(all)
441 return r.snap.stack(all, true)
442}
443
444// mainState is the project's main state (mainstate.go) as lines, or none
445// when origin has no main or the policy at its tip declares no nix follow
446// check. named puts the project's name after main. A policy or a walk that
447// did not read, or worker telemetry that did not, is said on stderr.
448func (r listed) mainState(h handleMap, c *costs, stderr io.Writer, t terminal, named bool) []string {
449 if r.snap.tip == "" {
450 return nil
451 }
452 end := phase("policy")
453 _, err := r.snap.layers()
454 end()
455 defer phase("main")()
456 if err != nil {
457 fmt.Fprintf(stderr, "valley: %s: the policy at main did not read, so main's state is not shown: %v\n", r.name, err)
458 return nil
459 }
460 model, err := r.snap.model(false)
461 walk := mainWalk{}
462 if err == nil {
463 walk, err = mainFollows(r.g, r.snap.tip, model, io.Discard)
464 }
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 at main's tip requires of a
769// head, by cost, derived against the merge base with main.
770func (s *snapshot) checks(head string) string {
771 base, err := s.g.output(true, "merge-base", s.tip, head)
772 if err != nil {
773 return "requires ? (no merge base with main)"
774 }
775 model, err := s.model(false)
776 if err != nil {
777 return "requires ? (the policy did not derive)"
778 }
779 processStarted()
780 paths, err := derive.Diff(context.Background(), s.g.dir, s.g.env, base, head)
781 if err != nil {
782 return "requires ? (the policy did not derive)"
783 }
784 res, err := derive.Derive(model, paths)
785 if err != nil {
786 return "requires ? (the policy did not derive)"
787 }
788 quick, slow := 0, 0
789 for _, q := range res.Required {
790 if costOf(q) == "slow" {
791 slow++
792 } else {
793 quick++
794 }
795 }
796 if quick+slow == 0 {
797 return "requires no checks"
798 }
799 noun := "checks"
800 if quick == 1 {
801 noun = "check"
802 }
803 return fmt.Sprintf("requires %d quick %s, %d slow", quick, noun, slow)
804}
805
806// tipPolicy is the policy at main's tip on origin, read once for every
807// reader of a snapshot: mainState, the version checks and the check
808// counts. Nothing is read until a reader asks, and a failure is kept, so
809// each reader says it its own way.
810type tipPolicy struct {
811 read bool
812 src layerSource
813 done func()
814 err error
815 pinned *composed.Model
816 unpinned *composed.Model
817 failed map[bool]error
818}
819
820// layers are the two policy layers at main's tip.
821func (s *snapshot) layers() (layerSource, error) {
822 p := &s.policy
823 if !p.read {
824 p.read = true
825 p.src, p.done, p.err = resolveLayers(s.g, s.tip, "", "")
826 }
827 return p.src, p.err
828}
829
830// model is the policy the layers at main's tip compose. pinned asks for
831// each requirement's pin (policyModel); a model read pinned serves a
832// reader that does not ask for pins too.
833func (s *snapshot) model(pinned bool) (*composed.Model, error) {
834 p := &s.policy
835 switch {
836 case p.pinned != nil:
837 return p.pinned, nil
838 case !pinned && p.unpinned != nil:
839 return p.unpinned, nil
840 case p.failed[pinned] != nil:
841 return nil, p.failed[pinned]
842 }
843 m, err := func() (*composed.Model, error) {
844 src, err := s.layers()
845 if err != nil {
846 return nil, err
847 }
848 schema, err := schemaFile(s.g, "")
849 if err != nil {
850 return nil, err
851 }
852 return policyModel(schema, src.instance, src.project, pinned)
853 }()
854 switch {
855 case err != nil:
856 if p.failed == nil {
857 p.failed = map[bool]error{}
858 }
859 p.failed[pinned] = err
860 case pinned:
861 p.pinned = m
862 default:
863 p.unpinned = m
864 }
865 return m, err
866}
867
868// close removes the layers the snapshot read.
869func (s *snapshot) close() {
870 if s.policy.done != nil {
871 s.policy.done()
872 s.policy.done = nil
873 }
874}