gunk-dev/the-valley

pending.go

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