gunk-dev/the-valley

pending.go

source9e4736a353f5main's published tip history
21.0 KiB
1// valley pending: what is waiting to land, for a person to read.
2//
3// It prints three sections, in this order. ready holds the ready changes
4// whose active version has not landed, by the first two landing rules
5// (inventory.go). branches holds each branch on origin, other than main,
6// that main does not reach, that is no change's active head, and that no
7// landed version's head reaches. drafts
8// holds the changes whose record says they are drafts. When no ready
9// change is at the top of a stack, one line says so in place of ready,
10// and says where any ready change inside another section's stack is.
11//
12// Each entry is a block. Its first line is its name, with the age and
13// author of its head: the handle and version of a change, the name of a
14// branch, and for a draft its handle and version on its branch. The lines
15// indented under it give its title, then the commits and the diff the
16// entry adds to its base:
17//
18// act-on-a-change-by-handle-key-its-1902807a 9 hours ago · alice-agent-vm
19// change: share the record bounds and the c-<change ID> request name
20// 10 commits · 31 files +2412 −404
21// approving it lands the 2 below too
22// ├ find-changes-across-repos-valley-changes-1e788c4f 10 hours ago · alice-…
23// │ valley: changes --json and pending by handle, across a host's projects
24// │ 9 commits · 17 files +2701 −137
25// └ a-draft-state-valley-unready-and-what-56ed34ac 12 hours ago · alice-ag…
26// change: read a draft as a third state
27// 14 commits · 20 files +1207 −219
28//
29// A change's title is its record's, for the active version. A branch's
30// title is the subject of its first own commit: the oldest commit on its
31// first-parent line that its base does not hold. When a knot in the plan
32// graph links a change, the first knot's ID follows the title, as
33// "<title> · oc-6335749" (does.go).
34//
35// An entry's base is the nearest other entry its head strictly contains,
36// or main when there is none. That is the ancestry includes reads
37// (inventory.go). Its commits and diff are counted from the nearer of its
38// base and the head of a landed version its head contains: a landed
39// version's commits are not on main, since it landed as one new commit,
40// and its content is. A stack is an entry that no other entry contains, the
41// top, then every entry the top contains, as one list at one indentation,
42// however deep the stack is. Each entry is listed before the entries it
43// contains. The top's block says how many entries approving it lands with
44// it. Each entry is on the entry listed right after it, and says
45// "on <base>" where it is not, as at a fork, where two entries are on one
46// base and the base is listed under only one of them. An entry the top
47// does not contain is never listed under it. A stack is printed in the
48// section of its top, and a listed entry from another section says which
49// it is in.
50//
51// A change may say more, each on a line of its own. includes <handle>
52// names a change its head contains that is not an entry here, such as a
53// withdrawn one. uncertain says the active version may have landed without
54// its evidence being stored. With --checks, it says how many checks the
55// policy requires of the change, by cost, and for a ready change how many
56// of its required checks passed, failed and are pending, as valley
57// changes --checks lists them (versionchecks.go), naming those that
58// failed: "checks: 18 passed, 1 failed (valley-request)". When the host's
59// worker telemetry holds the version's builds, the line goes on with what
60// they cost and the checks that grew against their recent cost
61// (checkcost.go): "checks: 21 passed in 9m10s (eval 24s); worker-e2e
62// 431s, +68s against its recent 363s". --json then carries the same
63// checks objects.
64//
65// Within a section, the stack with the latest commit comes first, and
66// within a stack the entry with the latest commit does. Every line fits
67// stdout's terminal, or 80 columns when stdout is no terminal or does not
68// know its width. A title or an author is cut short with …; a handle or a
69// branch never is. On a terminal, names are bold, unless NO_COLOR is set.
70//
71// With --json it prints valley-pending/v1: valley-changes/v1's shape, with
72// the pending changes alone in changes, the drafts in an array of their
73// own, drafts, and the same branches.
74
75package main
76
77import (
78 "fmt"
79 "io"
80 "os"
81 "os/exec"
82 "sort"
83 "strconv"
84 "strings"
85 "unicode"
86
87 "the-valley/change"
88 "the-valley/rebase"
89)
90
91// pendingChange is a ready change whose active version has not landed.
92func pendingChange(s *snapshot, n recorded) bool {
93 return n.record.State == change.Ready && !s.isLanded(n.id, n.record.ActiveVersion())
94}
95
96// unlanded is a change in any state whose active version has not landed:
97// the changes a pending change may include.
98func unlanded(s *snapshot, n recorded) bool {
99 return !s.isLanded(n.id, n.record.ActiveVersion())
100}
101
102func isDraft(_ *snapshot, n recorded) bool {
103 return n.record.State == change.Draft
104}
105
106// pendingView is a repository as valley-pending/v1 writes it: the pending
107// changes in changes and the drafts in drafts, each with includes among
108// the changes that have not landed.
109func (l listed) pendingView(h handleMap) jsonRepo {
110 r := l.repoView(h, pendingChange, unlanded)
111 drafts := []jsonChange{}
112 if l.err == nil {
113 drafts = l.repoView(h, isDraft, unlanded).Changes
114 }
115 r.Drafts = &drafts
116 return r
117}
118
119func runPending(g git, args []string, stdout, stderr io.Writer) error {
120 l, err := parseListing("pending", args, true)
121 if err != nil {
122 return err
123 }
124 list, host, err := sources(g, l, stderr)
125 if err != nil {
126 return err
127 }
128 repos := readSources(list, newVerifier())
129 readKnots(repos, l.verbose, stderr)
130 h := handles(repos)
131 writeHandleCache(g, repos, h)
132 defer warnUnverified(repos, stderr)
133 if l.asJSON {
134 doc := jsonChanges{Schema: pendingSchema, Host: host, Repos: []jsonRepo{}}
135 c := newCosts()
136 for _, r := range repos {
137 view := r.pendingView(h)
138 if l.checks {
139 r.addChecks(&view, c, stderr)
140 }
141 utf8Branches(&view, stderr)
142 doc.Repos = append(doc.Repos, view)
143 }
144 return writeDocument(stdout, doc)
145 }
146 t := terminalOf(stdout)
147 c := newCosts()
148 for i, r := range repos {
149 if i > 0 {
150 fmt.Fprintln(stdout)
151 }
152 writePending(r, h, l, c, stdout, stderr, len(repos) > 1 || l.all || l.repo != "", t)
153 }
154 return nil
155}
156
157// sections are valley pending's sections, in the order they are printed,
158// each with the word a nested entry from it is marked with.
159var sections = []struct{ name, kind string }{
160 {"ready", "ready"}, {"branches", "branch"}, {"drafts", "draft"},
161}
162
163// entry is one block of valley pending: a ready change, a branch no record
164// is on, or a draft.
165type entry struct {
166 section string
167 name string // what the block's first line names
168 ref string // what the entry is typed as: its handle, or its branch
169 head string // the head commit
170 title string // the record's title; for a branch, read by measure
171 knot string // ID of the first knot that links the change (does.go)
172 includes []string // what includes names that is no entry here
173 notes []string // uncertain and checks
174
175 when int64 // the head's commit time
176 age, author string
177 layer string // the commits and the diff it adds to its base
178
179 parent *entry // the entry it is listed under, if any
180 kids []*entry // the entries nested right under it
181 base *entry // nil for main
182 inside []*entry // every entry whose head strictly contains its own
183 below []*entry // for the top of a stack, every entry listed under it
184 latest int64 // for the top of a stack, the latest commit time in it
185}
186
187// writePending prints one repository's entries, section by section.
188// Several repositories are each headed by their name.
189func writePending(r listed, h handleMap, l listing, c *costs, w, stderr io.Writer, headed bool, t terminal) {
190 p := func(format string, args ...any) { fmt.Fprintf(w, format, args...) }
191 if r.err != nil {
192 p("%s: %v\n", r.name, r.err)
193 return
194 }
195 if headed {
196 p("%s\n%s\n", r.name, strings.Repeat("─", min(columns(r.name), t.width)))
197 }
198 view := r.pendingView(h)
199 if l.checks {
200 r.addChecks(&view, c, stderr)
201 }
202 all := r.entries(view, h, l)
203 tops := r.snap.stack(all)
204 gap := false
205 for _, sec := range sections {
206 var here []*entry
207 for _, e := range tops {
208 if e.section == sec.name {
209 here = append(here, e)
210 }
211 }
212 if sec.name == "ready" && len(here) == 0 {
213 p("%s\n", readyElsewhere(tops))
214 gap = true
215 continue
216 }
217 if len(here) == 0 {
218 continue
219 }
220 if gap {
221 p("\n")
222 }
223 p("%s\n", sec.name)
224 for i, e := range here {
225 if i > 0 {
226 p("\n")
227 }
228 for _, line := range t.drawStack(e) {
229 p("%s\n", line)
230 }
231 }
232 gap = true
233 }
234}
235
236// entries are a repository's entries, as its pending view lists them, each
237// with its head's commit time, age and author.
238func (r listed) entries(view jsonRepo, h handleMap, l listing) []*entry {
239 s := r.snap
240 states := map[handleKey]string{}
241 for _, n := range s.all {
242 states[handleKey{r.name, n.record.Target, n.id}] = n.record.State
243 }
244 var all []*entry
245 recorded := func(section string, c jsonChange) {
246 v := c.Versions[c.Active-1]
247 e := &entry{section: section, name: fmt.Sprintf("%s v%d", c.Handle, v.N), ref: c.Handle, head: v.Head, title: readable(v.Title)}
248 if len(c.Knots) > 0 {
249 e.knot = readable(c.Knots[0].ID)
250 }
251 if section == "drafts" && v.Branch != "" {
252 e.name += " on " + branchName(v.Branch)
253 }
254 for _, id := range c.Includes {
255 k := handleKey{r.name, c.Target, id}
256 if st := states[k]; st != change.Ready && st != change.Draft {
257 e.includes = append(e.includes, fmt.Sprintf("includes %s (%s)", h[k], st))
258 }
259 }
260 if v.Landing == uncertain {
261 e.notes = append(e.notes, "uncertain: it may have landed without its evidence being stored")
262 }
263 if c.Restack != nil && c.Restack.Current {
264 name := func(id string) string { return h[handleKey{r.name, c.Target, id}] }
265 e.notes = append(e.notes, "restack: "+readable(restackSays(c.Restack.Report, name)))
266 }
267 if l.checks {
268 e.notes = append(e.notes, s.checks(v.Head))
269 }
270 if v.Checks != nil {
271 e.notes = append(e.notes, checksLine(v.Checks))
272 }
273 all = append(all, e)
274 }
275 for _, c := range view.Changes {
276 recorded("ready", c)
277 }
278 for _, b := range view.Branches {
279 name := branchName(b.Branch)
280 all = append(all, &entry{section: "branches", name: name, ref: name, head: b.Head})
281 }
282 for _, c := range *view.Drafts {
283 recorded("drafts", c)
284 }
285 for _, e := range all {
286 out, _ := s.g.output(true, "log", "-1", "--format=%ct%x00%cr%x00%an", e.head)
287 if fields := strings.SplitN(out, "\x00", 3); len(fields) == 3 {
288 e.when, _ = strconv.ParseInt(fields[0], 10, 64)
289 e.age, e.author = fields[1], readable(fields[2])
290 }
291 }
292 return all
293}
294
295// stack nests each entry under the nearest entry whose head strictly
296// contains its own, and gives each entry its base: the nearest entry its
297// own head strictly contains, as the rebase engine stacks layers
298// (rebase.Snapshot.Nest). Where two are equally near, the one with the
299// later commit is taken. It returns the entries nested under none, each the
300// top of a stack, the stack with the latest commit first. Each top lists
301// every entry nested under it, at any depth, in its below.
302func (s *snapshot) stack(all []*entry) []*entry {
303 nodes := make([]rebase.Node, len(all))
304 for i, e := range all {
305 nodes[i] = rebase.Node{Name: e.name, Head: e.head, When: e.when}
306 }
307 nest := s.land.Nest(nodes)
308 for i, e := range all {
309 for _, j := range nest.Inside[i] {
310 e.inside = append(e.inside, all[j])
311 }
312 if p := nest.Parent[i]; p >= 0 {
313 e.parent = all[p]
314 e.parent.kids = append(e.parent.kids, e)
315 }
316 }
317 var tops []*entry
318 for i, e := range all {
319 if b := nest.Base[i]; b >= 0 {
320 e.base = all[b]
321 }
322 s.measure(e)
323 if e.parent == nil {
324 tops = append(tops, e)
325 }
326 }
327 for _, top := range tops {
328 top.list()
329 }
330 byActivity(tops, func(e *entry) int64 { return e.latest })
331 return tops
332}
333
334// list puts every entry nested under the top of a stack in its below, each
335// before the entries it contains. Where it can, it lists next the base of
336// the entry it listed last, so a chain is listed unbroken. Otherwise it
337// lists next the entry with the latest commit. It sets latest, the latest
338// commit time in the stack.
339func (top *entry) list() {
340 nested := map[*entry]bool{}
341 var walk func(e *entry)
342 walk = func(e *entry) {
343 for _, k := range e.kids {
344 nested[k] = true
345 walk(k)
346 }
347 }
348 walk(top)
349 top.latest = top.when
350 for last := top; len(nested) > 0; {
351 var free []*entry // those every entry containing them is listed before
352 for e := range nested {
353 listable := true
354 for _, c := range e.inside {
355 listable = listable && !nested[c]
356 }
357 if listable {
358 free = append(free, e)
359 }
360 }
361 byActivity(free, func(e *entry) int64 { return e.when })
362 next := free[0]
363 for _, e := range free {
364 if e == last.base {
365 next = e
366 }
367 }
368 delete(nested, next)
369 top.below = append(top.below, next)
370 top.latest = max(top.latest, next.when)
371 last = next
372 }
373}
374
375// readyElsewhere is what the ready section says when no ready change is at
376// the top of a stack: that nothing is ready, or where the ready changes in
377// other sections' stacks are.
378func readyElsewhere(tops []*entry) string {
379 n, stacks := 0, 0
380 var where []string
381 for _, sec := range sections {
382 found := false
383 for _, top := range tops {
384 held := 0
385 for _, e := range top.below {
386 if e.section == "ready" {
387 held++
388 }
389 }
390 if top.section == sec.name && held > 0 {
391 n, stacks, found = n+held, stacks+1, true
392 }
393 }
394 if found {
395 where = append(where, sec.name)
396 }
397 }
398 if n == 0 {
399 return "nothing is ready"
400 }
401 verb, in := "are", fmt.Sprintf("%d stacks", stacks)
402 if n == 1 {
403 verb = "is"
404 }
405 if stacks == 1 {
406 in = "a stack"
407 }
408 return fmt.Sprintf("nothing is ready on its own; %s %s in %s under %s", counted(n, "ready change"), verb, in, strings.Join(where, " and "))
409}
410
411// byActivity orders entries latest first, and then by name.
412func byActivity(list []*entry, when func(*entry) int64) {
413 sort.SliceStable(list, func(i, j int) bool {
414 if a, b := when(list[i]), when(list[j]); a != b {
415 return a > b
416 }
417 return list[i].name < list[j].name
418 })
419}
420
421// measure reads what an entry adds to what it stands on: how many
422// commits, and the diff. It stands on the nearest of its base and every
423// landed version's head below it, as the rebase engine cuts a landed
424// version's commits from a family, or on its merge base with main when
425// there is none. A landed version's commits are not on main, since it
426// landed as one new commit, and its content is. A branch's title is the
427// subject of the first of the entry's own commits on its first-parent
428// line.
429func (s *snapshot) measure(e *entry) {
430 var below []string
431 for _, h := range s.land.LandedUnder(e.head) {
432 if h != e.head {
433 below = append(below, h)
434 }
435 }
436 if e.base != nil {
437 below = append(below, e.base.head)
438 }
439 var not []string
440 from := s.tip
441 for _, h := range below {
442 not = append(not, "^"+h)
443 // The heads below are all the entry's ancestors, and the nearest
444 // is the one that contains every other.
445 if from == s.tip || s.strictAncestor(from, h) {
446 from = h
447 }
448 }
449 if s.tip != "" {
450 not = append(not, "^"+s.tip)
451 }
452 if from == "" {
453 from, _ = s.g.input(true, strings.NewReader(""), "hash-object", "-t", "tree", "--stdin")
454 }
455 commits := "? commits"
456 if out, err := s.g.output(true, append([]string{"rev-list", "--count", e.head}, not...)...); err == nil {
457 n, _ := strconv.Atoi(out)
458 commits = counted(n, "commit")
459 }
460 files, added, deleted := 0, 0, 0
461 out, _ := s.g.output(true, "diff", "--numstat", from+"..."+e.head)
462 for _, line := range strings.Split(out, "\n") {
463 if f := strings.SplitN(line, "\t", 3); len(f) == 3 {
464 a, _ := strconv.Atoi(f[0]) // a binary file's counts are -, read as 0
465 d, _ := strconv.Atoi(f[1])
466 files, added, deleted = files+1, added+a, deleted+d
467 }
468 }
469 diff := "no file changes"
470 if files > 0 {
471 diff = fmt.Sprintf("%s +%d −%d", counted(files, "file"), added, deleted)
472 }
473 e.layer = commits + " · " + diff
474 if e.section == "branches" {
475 e.title = s.branchTitle(e.head, not)
476 }
477}
478
479// branchTitle is a branch's title: the subject of the first of its own
480// commits on its first-parent line, those its head reaches and not leaves
481// out.
482func (s *snapshot) branchTitle(head string, not []string) string {
483 out, _ := s.g.output(true, append([]string{"log", "--first-parent", "--reverse", "--format=%s", head}, not...)...)
484 first, _, _ := strings.Cut(out, "\n")
485 return readable(change.Title(first))
486}
487
488func counted(n int, noun string) string {
489 switch n {
490 case 0:
491 return "no " + noun + "s"
492 case 1:
493 return "1 " + noun
494 }
495 return fmt.Sprintf("%d %ss", n, noun)
496}
497
498// drawStack is the lines of a stack: the top entry's block, then the
499// block of each entry listed under it, at one indentation however deep the
500// stack is. Each listed entry is on the entry listed right after it, and
501// says "on <base>" where it is not.
502func (t terminal) drawStack(top *entry) []string {
503 list := append([]*entry{top}, top.below...)
504 var lines []string
505 for i, e := range list {
506 var next *entry
507 if i+1 < len(list) {
508 next = list[i+1]
509 }
510 first, rest := "", " "
511 switch {
512 case i > 0 && next != nil:
513 first, rest = " ├ ", " │ "
514 case i > 0:
515 first, rest = " └ ", " "
516 }
517 suffix := ""
518 if e.section != top.section {
519 for _, sec := range sections {
520 if sec.name == e.section {
521 suffix = " (" + sec.kind + ")"
522 }
523 }
524 }
525 lines = append(lines, t.nameLine(first, e.name, suffix, e, rest)...)
526 lines = append(lines, rest+t.titled(e, rest), rest+t.fit(e.layer, rest))
527 switch {
528 case e.base == next:
529 case e.base != nil:
530 lines = append(lines, rest+"on "+e.base.ref)
531 default:
532 lines = append(lines, rest+"on "+recordTarget)
533 }
534 lines = append(lines, prefixed(rest, e.includes)...)
535 for _, note := range e.notes {
536 lines = append(lines, rest+t.fit(note, rest))
537 }
538 if i == 0 && len(top.below) > 0 {
539 lands := fmt.Sprintf("approving it lands the %d below too", len(top.below))
540 if len(top.below) == 1 {
541 lands = "approving it lands the one below too"
542 }
543 lines = append(lines, rest+t.fit(lands, rest))
544 }
545 }
546 return lines
547}
548
549// titled formats e's title line after lead, appending " · <knot ID>" when a
550// knot links the change. Long titles are truncated so the knot ID fits in
551// full.
552func (t terminal) titled(e *entry, lead string) string {
553 if e.knot == "" {
554 return t.fit(e.title, lead)
555 }
556 tail := " · " + e.knot
557 return fit(e.title, t.width-columns(lead+tail)) + tail
558}
559
560func prefixed(lead string, lines []string) []string {
561 var out []string
562 for _, l := range lines {
563 out = append(out, lead+l)
564 }
565 return out
566}
567
568// nameLine is an entry's first line: its name, in bold on a terminal, and
569// the head's age and author at the right margin. When that leaves too
570// little room, the author is cut short. When even that leaves too little,
571// the age and author go on a line of their own, indented as rest is.
572func (t terminal) nameLine(lead, name, suffix string, e *entry, rest string) []string {
573 left := lead + t.strong(name) + suffix
574 used := columns(lead + name + suffix)
575 if e.age == "" && e.author == "" {
576 return []string{left}
577 }
578 right := e.age + " · " + e.author
579 if room := t.width - used - 2; columns(right) > room {
580 short := room - columns(e.age+" · ")
581 if short < 4 {
582 return []string{left, rest + t.fit(right, rest)}
583 }
584 right = e.age + " · " + fit(e.author, short)
585 }
586 return []string{left + strings.Repeat(" ", t.width-used-columns(right)) + right}
587}
588
589// branchName is a branch's name as printed: as it is, or, when it holds a
590// character that is not printable or bytes that are not UTF-8, in the
591// $'...' form a shell reads back as the same name.
592func branchName(b string) string {
593 if printable(b) {
594 return b
595 }
596 return shellQuote(b)
597}
598
599// readable is s as text to print: valid UTF-8, with every control
600// character, which a terminal could act on, made a space.
601func readable(s string) string {
602 return strings.Map(func(r rune) rune {
603 if unicode.IsControl(r) {
604 return ' '
605 }
606 return r
607 }, strings.ToValidUTF8(s, "�"))
608}
609
610// checks says how many checks the policy requires of a head, by cost, as
611// valley checks derives them against the merge base with main. It runs
612// the valley command bin/valley names in VALLEY_COMMAND, inside the
613// repository the change is in.
614func (s *snapshot) checks(head string) string {
615 valley := os.Getenv("VALLEY_COMMAND")
616 if valley == "" {
617 valley = "valley"
618 }
619 base, err := s.g.output(true, "merge-base", s.tip, head)
620 if err != nil {
621 return "requires ? (no merge base with main)"
622 }
623 cmd := exec.Command(valley, "checks", base, head)
624 cmd.Dir = s.g.dir
625 cmd.Env = s.g.env
626 out, err := cmd.Output()
627 if err != nil {
628 return "requires ? (the policy did not derive)"
629 }
630 count := func(prefix string) int {
631 for _, line := range strings.Split(string(out), "\n") {
632 if rest, ok := strings.CutPrefix(line, prefix); ok && rest != "none" {
633 return len(strings.Split(rest, ", "))
634 }
635 }
636 return 0
637 }
638 quick, slow := count("quick: "), count("slow: ")
639 if quick+slow == 0 {
640 return "requires no checks"
641 }
642 noun := "checks"
643 if quick == 1 {
644 noun = "check"
645 }
646 return fmt.Sprintf("requires %d quick %s, %d slow", quick, noun, slow)
647}