gunk-dev/the-valley

pending.go

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