gunk-dev/the-valley

pending.go

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