gunk-dev/the-valley

pending.go

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