gunk-dev/the-valley

pending.go

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