gunk-dev/the-valley

pending.go

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