gunk-dev/the-valley

pending.go

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