gunk-dev/the-valley

pending.go

sourcec91524503e2dmain's published tip history
19.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 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 --checks, it says how many checks the
49// policy requires of the change, 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 id string // a change's ID; "" for a branch (stack.go)
150 state string // a change's state, or - for a branch (stack.go)
151 includes []string // what includes names that is no entry here
152 notes []string // uncertain and checks
153
154 when int64 // the head's commit time
155 age, author string
156 layer string // the commits and the diff it adds to its base
157
158 parent *entry // the entry it is listed under, if any
159 kids []*entry // the entries nested right under it
160 base *entry // nil for main
161 inside []*entry // every entry whose head strictly contains its own
162 below []*entry // for the top of a stack, every entry listed under it
163 latest int64 // for the top of a stack, the latest commit time in it
164}
165
166// writePending prints one repository's entries, section by section.
167// Several repositories are each headed by their name.
168func writePending(r listed, h handleMap, l listing, w io.Writer, headed bool, t terminal) {
169 p := func(format string, args ...any) { fmt.Fprintf(w, format, args...) }
170 if r.err != nil {
171 p("%s: %v\n", r.name, r.err)
172 return
173 }
174 if headed {
175 p("%s\n%s\n", r.name, strings.Repeat("─", min(columns(r.name), t.width)))
176 }
177 all := r.entries(r.pendingView(h), h, l)
178 tops := r.snap.stack(all)
179 gap := false
180 for _, sec := range sections {
181 var here []*entry
182 for _, e := range tops {
183 if e.section == sec.name {
184 here = append(here, e)
185 }
186 }
187 if sec.name == "ready" && len(here) == 0 {
188 p("%s\n", readyElsewhere(tops))
189 gap = true
190 continue
191 }
192 if len(here) == 0 {
193 continue
194 }
195 if gap {
196 p("\n")
197 }
198 p("%s\n", sec.name)
199 for i, e := range here {
200 if i > 0 {
201 p("\n")
202 }
203 for _, line := range t.drawStack(e) {
204 p("%s\n", line)
205 }
206 }
207 gap = true
208 }
209}
210
211// entries are a repository's entries, as its pending view lists them, each
212// with its head's commit time, age and author.
213func (r listed) entries(view jsonRepo, h handleMap, l listing) []*entry {
214 s := r.snap
215 states := map[handleKey]string{}
216 for _, n := range s.all {
217 states[handleKey{r.name, n.record.Target, n.id}] = n.record.State
218 }
219 var all []*entry
220 recorded := func(section string, c jsonChange) {
221 v := c.Versions[c.Active-1]
222 e := &entry{section: section, name: fmt.Sprintf("%s v%d", c.Handle, v.N), ref: c.Handle, head: v.Head, title: readable(v.Title)}
223 if section == "drafts" && v.Branch != "" {
224 e.name += " on " + branchName(v.Branch)
225 }
226 for _, id := range c.Includes {
227 k := handleKey{r.name, c.Target, id}
228 if st := states[k]; st != change.Ready && st != change.Draft {
229 e.includes = append(e.includes, fmt.Sprintf("includes %s (%s)", h[k], st))
230 }
231 }
232 if v.Landing == uncertain {
233 e.notes = append(e.notes, "uncertain: it may have landed without its evidence being stored")
234 }
235 if l.checks {
236 e.notes = append(e.notes, s.checks(v.Head))
237 }
238 all = append(all, e)
239 }
240 for _, c := range view.Changes {
241 recorded("ready", c)
242 }
243 for _, b := range view.Branches {
244 name := branchName(b.Branch)
245 all = append(all, &entry{section: "branches", name: name, ref: name, head: b.Head})
246 }
247 for _, c := range *view.Drafts {
248 recorded("drafts", c)
249 }
250 for _, e := range all {
251 out, _ := s.g.output(true, "log", "-1", "--format=%ct%x00%cr%x00%an", e.head)
252 if fields := strings.SplitN(out, "\x00", 3); len(fields) == 3 {
253 e.when, _ = strconv.ParseInt(fields[0], 10, 64)
254 e.age, e.author = fields[1], readable(fields[2])
255 }
256 }
257 return all
258}
259
260// stack nests each entry under the nearest entry whose head strictly
261// contains its own, and gives each entry its base: the nearest entry its
262// own head strictly contains. Where two are equally near, the one with the
263// later commit is taken. It returns the entries nested under none, each the
264// top of a stack, the stack with the latest commit first. Each top lists
265// every entry nested under it, at any depth, in its below.
266func (s *snapshot) stack(all []*entry) []*entry {
267 in := make([][]bool, len(all)) // in[i][j]: entry i's head strictly contains entry j's
268 for i := range all {
269 in[i] = make([]bool, len(all))
270 for j := range all {
271 in[i][j] = i != j && s.strictAncestor(all[j].head, all[i].head)
272 if in[i][j] {
273 all[j].inside = append(all[j].inside, all[i])
274 }
275 }
276 }
277 // nearest is the entries i contains, or that contain i, with none
278 // between.
279 nearest := func(i int, above bool) []*entry {
280 var near []*entry
281 for j := range all {
282 outer, inner := j, i
283 if !above {
284 outer, inner = i, j
285 }
286 if !in[outer][inner] {
287 continue
288 }
289 between := false
290 for k := range all {
291 between = between || in[outer][k] && in[k][inner]
292 }
293 if !between {
294 near = append(near, all[j])
295 }
296 }
297 byActivity(near, func(e *entry) int64 { return e.when })
298 return near
299 }
300 for i, e := range all {
301 if above := nearest(i, true); len(above) > 0 {
302 e.parent = above[0]
303 e.parent.kids = append(e.parent.kids, e)
304 }
305 }
306 var tops []*entry
307 for i, e := range all {
308 below := nearest(i, false)
309 for _, d := range below {
310 if d.parent == e {
311 e.base = d
312 break
313 }
314 }
315 if e.base == nil && len(below) > 0 {
316 e.base = below[0]
317 }
318 s.measure(e)
319 if e.parent == nil {
320 tops = append(tops, e)
321 }
322 }
323 for _, top := range tops {
324 top.list()
325 }
326 byActivity(tops, func(e *entry) int64 { return e.latest })
327 return tops
328}
329
330// list puts every entry nested under the top of a stack in its below, each
331// before the entries it contains. Where it can, it lists next the base of
332// the entry it listed last, so a chain is listed unbroken. Otherwise it
333// lists next the entry with the latest commit. It sets latest, the latest
334// commit time in the stack.
335func (top *entry) list() {
336 nested := map[*entry]bool{}
337 var walk func(e *entry)
338 walk = func(e *entry) {
339 for _, k := range e.kids {
340 nested[k] = true
341 walk(k)
342 }
343 }
344 walk(top)
345 top.latest = top.when
346 for last := top; len(nested) > 0; {
347 var free []*entry // those every entry containing them is listed before
348 for e := range nested {
349 listable := true
350 for _, c := range e.inside {
351 listable = listable && !nested[c]
352 }
353 if listable {
354 free = append(free, e)
355 }
356 }
357 byActivity(free, func(e *entry) int64 { return e.when })
358 next := free[0]
359 for _, e := range free {
360 if e == last.base {
361 next = e
362 }
363 }
364 delete(nested, next)
365 top.below = append(top.below, next)
366 top.latest = max(top.latest, next.when)
367 last = next
368 }
369}
370
371// readyElsewhere is what the ready section says when no ready change is at
372// the top of a stack: that nothing is ready, or where the ready changes in
373// other sections' stacks are.
374func readyElsewhere(tops []*entry) string {
375 n, stacks := 0, 0
376 var where []string
377 for _, sec := range sections {
378 found := false
379 for _, top := range tops {
380 held := 0
381 for _, e := range top.below {
382 if e.section == "ready" {
383 held++
384 }
385 }
386 if top.section == sec.name && held > 0 {
387 n, stacks, found = n+held, stacks+1, true
388 }
389 }
390 if found {
391 where = append(where, sec.name)
392 }
393 }
394 if n == 0 {
395 return "nothing is ready"
396 }
397 verb, in := "are", fmt.Sprintf("%d stacks", stacks)
398 if n == 1 {
399 verb = "is"
400 }
401 if stacks == 1 {
402 in = "a stack"
403 }
404 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 "))
405}
406
407// byActivity orders entries latest first, and then by name.
408func byActivity(list []*entry, when func(*entry) int64) {
409 sort.SliceStable(list, func(i, j int) bool {
410 if a, b := when(list[i]), when(list[j]); a != b {
411 return a > b
412 }
413 return list[i].name < list[j].name
414 })
415}
416
417// measure reads what an entry adds to its base: how many commits, and the
418// diff from the base, or from its merge base with main. A branch's title
419// is the subject of the first of those commits on its first-parent line.
420func (s *snapshot) measure(e *entry) {
421 var not []string
422 from := s.tip
423 if e.base != nil {
424 not, from = append(not, "^"+e.base.head), e.base.head
425 }
426 if s.tip != "" {
427 not = append(not, "^"+s.tip)
428 }
429 if from == "" {
430 from, _ = s.g.input(true, strings.NewReader(""), "hash-object", "-t", "tree", "--stdin")
431 }
432 commits := "? commits"
433 if out, err := s.g.output(true, append([]string{"rev-list", "--count", e.head}, not...)...); err == nil {
434 n, _ := strconv.Atoi(out)
435 commits = counted(n, "commit")
436 }
437 files, added, deleted := 0, 0, 0
438 out, _ := s.g.output(true, "diff", "--numstat", from+"..."+e.head)
439 for _, line := range strings.Split(out, "\n") {
440 if f := strings.SplitN(line, "\t", 3); len(f) == 3 {
441 a, _ := strconv.Atoi(f[0]) // a binary file's counts are -, read as 0
442 d, _ := strconv.Atoi(f[1])
443 files, added, deleted = files+1, added+a, deleted+d
444 }
445 }
446 diff := "no file changes"
447 if files > 0 {
448 diff = fmt.Sprintf("%s +%d −%d", counted(files, "file"), added, deleted)
449 }
450 e.layer = commits + " · " + diff
451 if e.section == "branches" {
452 out, _ := s.g.output(true, append([]string{"log", "--first-parent", "--reverse", "--format=%s", e.head}, not...)...)
453 first, _, _ := strings.Cut(out, "\n")
454 e.title = readable(change.Title(first))
455 }
456}
457
458func counted(n int, noun string) string {
459 switch n {
460 case 0:
461 return "no " + noun + "s"
462 case 1:
463 return "1 " + noun
464 }
465 return fmt.Sprintf("%d %ss", n, noun)
466}
467
468// drawStack is the lines of a stack: the top entry's block, then the
469// block of each entry listed under it, at one indentation however deep the
470// stack is. Each listed entry is on the entry listed right after it, and
471// says "on <base>" where it is not.
472func (t terminal) drawStack(top *entry) []string {
473 list := append([]*entry{top}, top.below...)
474 var lines []string
475 for i, e := range list {
476 var next *entry
477 if i+1 < len(list) {
478 next = list[i+1]
479 }
480 first, rest := "", " "
481 switch {
482 case i > 0 && next != nil:
483 first, rest = " ├ ", " │ "
484 case i > 0:
485 first, rest = " └ ", " "
486 }
487 suffix := ""
488 if e.section != top.section {
489 for _, sec := range sections {
490 if sec.name == e.section {
491 suffix = " (" + sec.kind + ")"
492 }
493 }
494 }
495 lines = append(lines, t.nameLine(first, e.name, suffix, e, rest)...)
496 lines = append(lines, rest+t.fit(e.title, rest), rest+t.fit(e.layer, rest))
497 switch {
498 case e.base == next:
499 case e.base != nil:
500 lines = append(lines, rest+"on "+e.base.ref)
501 default:
502 lines = append(lines, rest+"on "+recordTarget)
503 }
504 lines = append(lines, prefixed(rest, e.includes)...)
505 for _, note := range e.notes {
506 lines = append(lines, rest+t.fit(note, rest))
507 }
508 if i == 0 && len(top.below) > 0 {
509 lands := fmt.Sprintf("approving it lands the %d below too", len(top.below))
510 if len(top.below) == 1 {
511 lands = "approving it lands the one below too"
512 }
513 lines = append(lines, rest+t.fit(lands, rest))
514 }
515 }
516 return lines
517}
518
519func prefixed(lead string, lines []string) []string {
520 var out []string
521 for _, l := range lines {
522 out = append(out, lead+l)
523 }
524 return out
525}
526
527// nameLine is an entry's first line: its name, in bold on a terminal, and
528// the head's age and author at the right margin. When that leaves too
529// little room, the author is cut short. When even that leaves too little,
530// the age and author go on a line of their own, indented as rest is.
531func (t terminal) nameLine(lead, name, suffix string, e *entry, rest string) []string {
532 left := lead + t.strong(name) + suffix
533 used := columns(lead + name + suffix)
534 if e.age == "" && e.author == "" {
535 return []string{left}
536 }
537 right := e.age + " · " + e.author
538 if room := t.width - used - 2; columns(right) > room {
539 short := room - columns(e.age+" · ")
540 if short < 4 {
541 return []string{left, rest + t.fit(right, rest)}
542 }
543 right = e.age + " · " + fit(e.author, short)
544 }
545 return []string{left + strings.Repeat(" ", t.width-used-columns(right)) + right}
546}
547
548// branchName is a branch's name as printed: as it is, or, when it holds a
549// character that is not printable or bytes that are not UTF-8, in the
550// $'...' form a shell reads back as the same name.
551func branchName(b string) string {
552 if printable(b) {
553 return b
554 }
555 return shellQuote(b)
556}
557
558// readable is s as text to print: valid UTF-8, with every control
559// character, which a terminal could act on, made a space.
560func readable(s string) string {
561 return strings.Map(func(r rune) rune {
562 if unicode.IsControl(r) {
563 return ' '
564 }
565 return r
566 }, strings.ToValidUTF8(s, "�"))
567}
568
569// checks says how many checks the policy requires of a head, by cost, as
570// valley checks derives them against the merge base with main. It runs
571// the valley command bin/valley names in VALLEY_COMMAND, inside the
572// repository the change is in.
573func (s *snapshot) checks(head string) string {
574 valley := os.Getenv("VALLEY_COMMAND")
575 if valley == "" {
576 valley = "valley"
577 }
578 base, err := s.g.output(true, "merge-base", s.tip, head)
579 if err != nil {
580 return "requires ? (no merge base with main)"
581 }
582 cmd := exec.Command(valley, "checks", base, head)
583 cmd.Dir = s.g.dir
584 cmd.Env = s.g.env
585 out, err := cmd.Output()
586 if err != nil {
587 return "requires ? (the policy did not derive)"
588 }
589 count := func(prefix string) int {
590 for _, line := range strings.Split(string(out), "\n") {
591 if rest, ok := strings.CutPrefix(line, prefix); ok && rest != "none" {
592 return len(strings.Split(rest, ", "))
593 }
594 }
595 return 0
596 }
597 quick, slow := count("quick: "), count("slow: ")
598 if quick+slow == 0 {
599 return "requires no checks"
600 }
601 noun := "checks"
602 if quick == 1 {
603 noun = "check"
604 }
605 return fmt.Sprintf("requires %d quick %s, %d slow", quick, noun, slow)
606}