gunk-dev/the-valley

pending.go

source37f58f5c0dcfmain's published tip history
18.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 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 · patflynn-agent
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 · patfly…
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 · patflynn…
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.
31//
32// An entry's base is the nearest other entry its head strictly contains,
33// or main when there is none. That is the ancestry includes reads
34// (inventory.go). A stack is an entry that no other entry contains, the
35// top, then every entry the top contains, as one list at one indentation,
36// however deep the stack is. Each entry is listed before the entries it
37// contains. The top's block says how many entries approving it lands with
38// it. Each entry is on the entry listed right after it, and says
39// "on <base>" where it is not, as at a fork, where two entries are on one
40// base and the base is listed under only one of them. An entry the top
41// does not contain is never listed under it. A stack is printed in the
42// section of its top, and a listed entry from another section says which
43// it is in.
44//
45// A change may say more, each on a line of its own. includes <handle>
46// names a change its head contains that is not an entry here, such as a
47// withdrawn one. uncertain says the active version may have landed without
48// its evidence being stored. With --owes, it says how many checks the
49// change owes, by cost.
50//
51// Within a section, the stack with the latest commit comes first, and
52// within a stack the entry with the latest commit does. Every line fits
53// stdout's terminal, or 80 columns when stdout is no terminal or does not
54// know its width. A title or an author is cut short with …; a handle or a
55// branch never is. On a terminal, names are bold, unless NO_COLOR is set.
56//
57// With --json it prints valley-pending/v1: valley-changes/v1's shape, with
58// the pending changes alone in changes, the drafts in an array of their
59// own, drafts, and the same branches.
60
61package main
62
63import (
64 "fmt"
65 "io"
66 "os"
67 "os/exec"
68 "sort"
69 "strconv"
70 "strings"
71 "unicode"
72
73 "the-valley/change"
74)
75
76// pendingChange is a ready change whose active version has not landed.
77func pendingChange(s *snapshot, n recorded) bool {
78 return n.record.State == change.Ready && !s.isLanded(n.id, n.record.ActiveVersion())
79}
80
81// unlanded is a change in any state whose active version has not landed:
82// the changes a pending change may include.
83func unlanded(s *snapshot, n recorded) bool {
84 return !s.isLanded(n.id, n.record.ActiveVersion())
85}
86
87func isDraft(_ *snapshot, n recorded) bool {
88 return n.record.State == change.Draft
89}
90
91// pendingView is a repository as valley-pending/v1 writes it: the pending
92// changes in changes and the drafts in drafts, each with includes among
93// the changes that have not landed.
94func (l listed) pendingView(h handleMap) jsonRepo {
95 r := l.repoView(h, pendingChange, unlanded)
96 drafts := []jsonChange{}
97 if l.err == nil {
98 drafts = l.repoView(h, isDraft, unlanded).Changes
99 }
100 r.Drafts = &drafts
101 return r
102}
103
104func runPending(g git, args []string, stdout, stderr io.Writer) error {
105 l, err := parseListing("pending", args, true)
106 if err != nil {
107 return err
108 }
109 list, host, err := sources(g, l, stderr)
110 if err != nil {
111 return err
112 }
113 repos := readSources(list, verifierFromEnv())
114 h := handles(repos)
115 defer warnUnverified(repos, stderr)
116 if l.asJSON {
117 doc := jsonChanges{Schema: pendingSchema, Host: host, Repos: []jsonRepo{}}
118 for _, r := range repos {
119 view := r.pendingView(h)
120 utf8Branches(&view, stderr)
121 doc.Repos = append(doc.Repos, view)
122 }
123 return writeDocument(stdout, doc)
124 }
125 t := terminalOf(stdout)
126 for i, r := range repos {
127 if i > 0 {
128 fmt.Fprintln(stdout)
129 }
130 writePending(r, h, l, stdout, len(repos) > 1 || l.all || l.repo != "", t)
131 }
132 return nil
133}
134
135// sections are valley pending's sections, in the order they are printed,
136// each with the word a nested entry from it is marked with.
137var sections = []struct{ name, kind string }{
138 {"ready", "ready"}, {"branches", "branch"}, {"drafts", "draft"},
139}
140
141// entry is one block of valley pending: a ready change, a branch no record
142// is on, or a draft.
143type entry struct {
144 section string
145 name string // what the block's first line names
146 ref string // what the entry is typed as: its handle, or its branch
147 head string // the head commit
148 title string // the record's title; for a branch, read by measure
149 includes []string // what includes names that is no entry here
150 notes []string // uncertain and owes
151
152 when int64 // the head's commit time
153 age, author string
154 layer string // the commits and the diff it adds to its base
155
156 parent *entry // the entry it is listed under, if any
157 kids []*entry // the entries nested right under it
158 base *entry // nil for main
159 inside []*entry // every entry whose head strictly contains its own
160 below []*entry // for the top of a stack, every entry listed under it
161 latest int64 // for the top of a stack, the latest commit time in it
162}
163
164// writePending prints one repository's entries, section by section.
165// Several repositories are each headed by their name.
166func writePending(r listed, h handleMap, l listing, w io.Writer, headed bool, t terminal) {
167 p := func(format string, args ...any) { fmt.Fprintf(w, format, args...) }
168 if r.err != nil {
169 p("%s: %v\n", r.name, r.err)
170 return
171 }
172 if headed {
173 p("%s\n%s\n", r.name, strings.Repeat("─", min(columns(r.name), t.width)))
174 }
175 all := r.entries(r.pendingView(h), h, l)
176 tops := r.snap.stack(all)
177 gap := false
178 for _, sec := range sections {
179 var here []*entry
180 for _, e := range tops {
181 if e.section == sec.name {
182 here = append(here, e)
183 }
184 }
185 if sec.name == "ready" && len(here) == 0 {
186 p("%s\n", readyElsewhere(tops))
187 gap = true
188 continue
189 }
190 if len(here) == 0 {
191 continue
192 }
193 if gap {
194 p("\n")
195 }
196 p("%s\n", sec.name)
197 for i, e := range here {
198 if i > 0 {
199 p("\n")
200 }
201 for _, line := range t.drawStack(e) {
202 p("%s\n", line)
203 }
204 }
205 gap = true
206 }
207}
208
209// entries are a repository's entries, as its pending view lists them, each
210// with its head's commit time, age and author.
211func (r listed) entries(view jsonRepo, h handleMap, l listing) []*entry {
212 s := r.snap
213 states := map[handleKey]string{}
214 for _, n := range s.all {
215 states[handleKey{r.name, n.record.Target, n.id}] = n.record.State
216 }
217 var all []*entry
218 recorded := func(section string, c jsonChange) {
219 v := c.Versions[c.Active-1]
220 e := &entry{section: section, name: fmt.Sprintf("%s v%d", c.Handle, v.N), ref: c.Handle, head: v.Head, title: readable(v.Title)}
221 if section == "drafts" && v.Branch != "" {
222 e.name += " on " + branchName(v.Branch)
223 }
224 for _, id := range c.Includes {
225 k := handleKey{r.name, c.Target, id}
226 if st := states[k]; st != change.Ready && st != change.Draft {
227 e.includes = append(e.includes, fmt.Sprintf("includes %s (%s)", h[k], st))
228 }
229 }
230 if v.Landing == uncertain {
231 e.notes = append(e.notes, "uncertain: it may have landed without its evidence being stored")
232 }
233 if l.owes {
234 e.notes = append(e.notes, s.owes(v.Head))
235 }
236 all = append(all, e)
237 }
238 for _, c := range view.Changes {
239 recorded("ready", c)
240 }
241 for _, b := range view.Branches {
242 name := branchName(b.Branch)
243 all = append(all, &entry{section: "branches", name: name, ref: name, head: b.Head})
244 }
245 for _, c := range *view.Drafts {
246 recorded("drafts", c)
247 }
248 for _, e := range all {
249 out, _ := s.g.output(true, "log", "-1", "--format=%ct%x00%cr%x00%an", e.head)
250 if fields := strings.SplitN(out, "\x00", 3); len(fields) == 3 {
251 e.when, _ = strconv.ParseInt(fields[0], 10, 64)
252 e.age, e.author = fields[1], readable(fields[2])
253 }
254 }
255 return all
256}
257
258// stack nests each entry under the nearest entry whose head strictly
259// contains its own, and gives each entry its base: the nearest entry its
260// own head strictly contains. Where two are equally near, the one with the
261// later commit is taken. It returns the entries nested under none, each the
262// top of a stack, the stack with the latest commit first. Each top lists
263// every entry nested under it, at any depth, in its below.
264func (s *snapshot) stack(all []*entry) []*entry {
265 in := make([][]bool, len(all)) // in[i][j]: entry i's head strictly contains entry j's
266 for i := range all {
267 in[i] = make([]bool, len(all))
268 for j := range all {
269 in[i][j] = i != j && s.strictAncestor(all[j].head, all[i].head)
270 if in[i][j] {
271 all[j].inside = append(all[j].inside, all[i])
272 }
273 }
274 }
275 // nearest is the entries i contains, or that contain i, with none
276 // between.
277 nearest := func(i int, above bool) []*entry {
278 var near []*entry
279 for j := range all {
280 outer, inner := j, i
281 if !above {
282 outer, inner = i, j
283 }
284 if !in[outer][inner] {
285 continue
286 }
287 between := false
288 for k := range all {
289 between = between || in[outer][k] && in[k][inner]
290 }
291 if !between {
292 near = append(near, all[j])
293 }
294 }
295 byActivity(near, func(e *entry) int64 { return e.when })
296 return near
297 }
298 for i, e := range all {
299 if above := nearest(i, true); len(above) > 0 {
300 e.parent = above[0]
301 e.parent.kids = append(e.parent.kids, e)
302 }
303 }
304 var tops []*entry
305 for i, e := range all {
306 below := nearest(i, false)
307 for _, d := range below {
308 if d.parent == e {
309 e.base = d
310 break
311 }
312 }
313 if e.base == nil && len(below) > 0 {
314 e.base = below[0]
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 its base: how many commits, and the
416// diff from the base, or from its merge base with main. A branch's title
417// is the subject of the first of those commits on its first-parent line.
418func (s *snapshot) measure(e *entry) {
419 var not []string
420 from := s.tip
421 if e.base != nil {
422 not, from = append(not, "^"+e.base.head), e.base.head
423 }
424 if s.tip != "" {
425 not = append(not, "^"+s.tip)
426 }
427 if from == "" {
428 from, _ = s.g.input(true, strings.NewReader(""), "hash-object", "-t", "tree", "--stdin")
429 }
430 commits := "? commits"
431 if out, err := s.g.output(true, append([]string{"rev-list", "--count", e.head}, not...)...); err == nil {
432 n, _ := strconv.Atoi(out)
433 commits = counted(n, "commit")
434 }
435 files, added, deleted := 0, 0, 0
436 out, _ := s.g.output(true, "diff", "--numstat", from+"..."+e.head)
437 for _, line := range strings.Split(out, "\n") {
438 if f := strings.SplitN(line, "\t", 3); len(f) == 3 {
439 a, _ := strconv.Atoi(f[0]) // a binary file's counts are -, read as 0
440 d, _ := strconv.Atoi(f[1])
441 files, added, deleted = files+1, added+a, deleted+d
442 }
443 }
444 diff := "no file changes"
445 if files > 0 {
446 diff = fmt.Sprintf("%s +%d −%d", counted(files, "file"), added, deleted)
447 }
448 e.layer = commits + " · " + diff
449 if e.section == "branches" {
450 out, _ := s.g.output(true, append([]string{"log", "--first-parent", "--reverse", "--format=%s", e.head}, not...)...)
451 first, _, _ := strings.Cut(out, "\n")
452 e.title = readable(change.Title(first))
453 }
454}
455
456func counted(n int, noun string) string {
457 switch n {
458 case 0:
459 return "no " + noun + "s"
460 case 1:
461 return "1 " + noun
462 }
463 return fmt.Sprintf("%d %ss", n, noun)
464}
465
466// drawStack is the lines of a stack: the top entry's block, then the
467// block of each entry listed under it, at one indentation however deep the
468// stack is. Each listed entry is on the entry listed right after it, and
469// says "on <base>" where it is not.
470func (t terminal) drawStack(top *entry) []string {
471 list := append([]*entry{top}, top.below...)
472 var lines []string
473 for i, e := range list {
474 var next *entry
475 if i+1 < len(list) {
476 next = list[i+1]
477 }
478 first, rest := "", " "
479 switch {
480 case i > 0 && next != nil:
481 first, rest = " ├ ", " │ "
482 case i > 0:
483 first, rest = " └ ", " "
484 }
485 suffix := ""
486 if e.section != top.section {
487 for _, sec := range sections {
488 if sec.name == e.section {
489 suffix = " (" + sec.kind + ")"
490 }
491 }
492 }
493 lines = append(lines, t.nameLine(first, e.name, suffix, e, rest)...)
494 lines = append(lines, rest+t.fit(e.title, rest), rest+t.fit(e.layer, rest))
495 switch {
496 case e.base == next:
497 case e.base != nil:
498 lines = append(lines, rest+"on "+e.base.ref)
499 default:
500 lines = append(lines, rest+"on "+recordTarget)
501 }
502 lines = append(lines, prefixed(rest, e.includes)...)
503 for _, note := range e.notes {
504 lines = append(lines, rest+t.fit(note, rest))
505 }
506 if i == 0 && len(top.below) > 0 {
507 lands := fmt.Sprintf("approving it lands the %d below too", len(top.below))
508 if len(top.below) == 1 {
509 lands = "approving it lands the one below too"
510 }
511 lines = append(lines, rest+t.fit(lands, rest))
512 }
513 }
514 return lines
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// owes says how many checks a head owes under the policy, 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) owes(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 "owes ? (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 "owes ? (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 "owes nothing"
598 }
599 return fmt.Sprintf("owes %d quick, %d slow", quick, slow)
600}