gunk-dev/the-valley

pending.go

source2886163c0514main'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 --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 "the-valley/rebase"
75)
76
77// pendingChange is a ready change whose active version has not landed.
78func pendingChange(s *snapshot, n recorded) bool {
79 return n.record.State == change.Ready && !s.isLanded(n.id, n.record.ActiveVersion())
80}
81
82// unlanded is a change in any state whose active version has not landed:
83// the changes a pending change may include.
84func unlanded(s *snapshot, n recorded) bool {
85 return !s.isLanded(n.id, n.record.ActiveVersion())
86}
87
88func isDraft(_ *snapshot, n recorded) bool {
89 return n.record.State == change.Draft
90}
91
92// pendingView is a repository as valley-pending/v1 writes it: the pending
93// changes in changes and the drafts in drafts, each with includes among
94// the changes that have not landed.
95func (l listed) pendingView(h handleMap) jsonRepo {
96 r := l.repoView(h, pendingChange, unlanded)
97 drafts := []jsonChange{}
98 if l.err == nil {
99 drafts = l.repoView(h, isDraft, unlanded).Changes
100 }
101 r.Drafts = &drafts
102 return r
103}
104
105func runPending(g git, args []string, stdout, stderr io.Writer) error {
106 l, err := parseListing("pending", args, true)
107 if err != nil {
108 return err
109 }
110 list, host, err := sources(g, l, stderr)
111 if err != nil {
112 return err
113 }
114 repos := readSources(list, verifierFromEnv())
115 h := handles(repos)
116 writeHandleCache(g, repos, h)
117 defer warnUnverified(repos, stderr)
118 if l.asJSON {
119 doc := jsonChanges{Schema: pendingSchema, Host: host, Repos: []jsonRepo{}}
120 for _, r := range repos {
121 view := r.pendingView(h)
122 utf8Branches(&view, stderr)
123 doc.Repos = append(doc.Repos, view)
124 }
125 return writeDocument(stdout, doc)
126 }
127 t := terminalOf(stdout)
128 for i, r := range repos {
129 if i > 0 {
130 fmt.Fprintln(stdout)
131 }
132 writePending(r, h, l, stdout, len(repos) > 1 || l.all || l.repo != "", t)
133 }
134 return nil
135}
136
137// sections are valley pending's sections, in the order they are printed,
138// each with the word a nested entry from it is marked with.
139var sections = []struct{ name, kind string }{
140 {"ready", "ready"}, {"branches", "branch"}, {"drafts", "draft"},
141}
142
143// entry is one block of valley pending: a ready change, a branch no record
144// is on, or a draft.
145type entry struct {
146 section string
147 name string // what the block's first line names
148 ref string // what the entry is typed as: its handle, or its branch
149 head string // the head commit
150 title string // the record's title; for a branch, read by measure
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 c.Restack != nil && c.Restack.Current {
236 name := func(id string) string { return h[handleKey{r.name, c.Target, id}] }
237 e.notes = append(e.notes, "restack: "+readable(restackSays(c.Restack.Report, name)))
238 }
239 if l.checks {
240 e.notes = append(e.notes, s.checks(v.Head))
241 }
242 all = append(all, e)
243 }
244 for _, c := range view.Changes {
245 recorded("ready", c)
246 }
247 for _, b := range view.Branches {
248 name := branchName(b.Branch)
249 all = append(all, &entry{section: "branches", name: name, ref: name, head: b.Head})
250 }
251 for _, c := range *view.Drafts {
252 recorded("drafts", c)
253 }
254 for _, e := range all {
255 out, _ := s.g.output(true, "log", "-1", "--format=%ct%x00%cr%x00%an", e.head)
256 if fields := strings.SplitN(out, "\x00", 3); len(fields) == 3 {
257 e.when, _ = strconv.ParseInt(fields[0], 10, 64)
258 e.age, e.author = fields[1], readable(fields[2])
259 }
260 }
261 return all
262}
263
264// stack nests each entry under the nearest entry whose head strictly
265// contains its own, and gives each entry its base: the nearest entry its
266// own head strictly contains, as the rebase engine stacks layers
267// (rebase.Snapshot.Nest). Where two are equally near, the one with the
268// later commit is taken. It returns the entries nested under none, each the
269// top of a stack, the stack with the latest commit first. Each top lists
270// every entry nested under it, at any depth, in its below.
271func (s *snapshot) stack(all []*entry) []*entry {
272 nodes := make([]rebase.Node, len(all))
273 for i, e := range all {
274 nodes[i] = rebase.Node{Name: e.name, Head: e.head, When: e.when}
275 }
276 nest := s.land.Nest(nodes)
277 for i, e := range all {
278 for _, j := range nest.Inside[i] {
279 e.inside = append(e.inside, all[j])
280 }
281 if p := nest.Parent[i]; p >= 0 {
282 e.parent = all[p]
283 e.parent.kids = append(e.parent.kids, e)
284 }
285 }
286 var tops []*entry
287 for i, e := range all {
288 if b := nest.Base[i]; b >= 0 {
289 e.base = all[b]
290 }
291 s.measure(e)
292 if e.parent == nil {
293 tops = append(tops, e)
294 }
295 }
296 for _, top := range tops {
297 top.list()
298 }
299 byActivity(tops, func(e *entry) int64 { return e.latest })
300 return tops
301}
302
303// list puts every entry nested under the top of a stack in its below, each
304// before the entries it contains. Where it can, it lists next the base of
305// the entry it listed last, so a chain is listed unbroken. Otherwise it
306// lists next the entry with the latest commit. It sets latest, the latest
307// commit time in the stack.
308func (top *entry) list() {
309 nested := map[*entry]bool{}
310 var walk func(e *entry)
311 walk = func(e *entry) {
312 for _, k := range e.kids {
313 nested[k] = true
314 walk(k)
315 }
316 }
317 walk(top)
318 top.latest = top.when
319 for last := top; len(nested) > 0; {
320 var free []*entry // those every entry containing them is listed before
321 for e := range nested {
322 listable := true
323 for _, c := range e.inside {
324 listable = listable && !nested[c]
325 }
326 if listable {
327 free = append(free, e)
328 }
329 }
330 byActivity(free, func(e *entry) int64 { return e.when })
331 next := free[0]
332 for _, e := range free {
333 if e == last.base {
334 next = e
335 }
336 }
337 delete(nested, next)
338 top.below = append(top.below, next)
339 top.latest = max(top.latest, next.when)
340 last = next
341 }
342}
343
344// readyElsewhere is what the ready section says when no ready change is at
345// the top of a stack: that nothing is ready, or where the ready changes in
346// other sections' stacks are.
347func readyElsewhere(tops []*entry) string {
348 n, stacks := 0, 0
349 var where []string
350 for _, sec := range sections {
351 found := false
352 for _, top := range tops {
353 held := 0
354 for _, e := range top.below {
355 if e.section == "ready" {
356 held++
357 }
358 }
359 if top.section == sec.name && held > 0 {
360 n, stacks, found = n+held, stacks+1, true
361 }
362 }
363 if found {
364 where = append(where, sec.name)
365 }
366 }
367 if n == 0 {
368 return "nothing is ready"
369 }
370 verb, in := "are", fmt.Sprintf("%d stacks", stacks)
371 if n == 1 {
372 verb = "is"
373 }
374 if stacks == 1 {
375 in = "a stack"
376 }
377 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 "))
378}
379
380// byActivity orders entries latest first, and then by name.
381func byActivity(list []*entry, when func(*entry) int64) {
382 sort.SliceStable(list, func(i, j int) bool {
383 if a, b := when(list[i]), when(list[j]); a != b {
384 return a > b
385 }
386 return list[i].name < list[j].name
387 })
388}
389
390// measure reads what an entry adds to its base: how many commits, and the
391// diff from the base, or from its merge base with main. A branch's title
392// is the subject of the first of those commits on its first-parent line.
393func (s *snapshot) measure(e *entry) {
394 var not []string
395 from := s.tip
396 if e.base != nil {
397 not, from = append(not, "^"+e.base.head), e.base.head
398 }
399 if s.tip != "" {
400 not = append(not, "^"+s.tip)
401 }
402 if from == "" {
403 from, _ = s.g.input(true, strings.NewReader(""), "hash-object", "-t", "tree", "--stdin")
404 }
405 commits := "? commits"
406 if out, err := s.g.output(true, append([]string{"rev-list", "--count", e.head}, not...)...); err == nil {
407 n, _ := strconv.Atoi(out)
408 commits = counted(n, "commit")
409 }
410 files, added, deleted := 0, 0, 0
411 out, _ := s.g.output(true, "diff", "--numstat", from+"..."+e.head)
412 for _, line := range strings.Split(out, "\n") {
413 if f := strings.SplitN(line, "\t", 3); len(f) == 3 {
414 a, _ := strconv.Atoi(f[0]) // a binary file's counts are -, read as 0
415 d, _ := strconv.Atoi(f[1])
416 files, added, deleted = files+1, added+a, deleted+d
417 }
418 }
419 diff := "no file changes"
420 if files > 0 {
421 diff = fmt.Sprintf("%s +%d −%d", counted(files, "file"), added, deleted)
422 }
423 e.layer = commits + " · " + diff
424 if e.section == "branches" {
425 e.title = s.branchTitle(e.head, not)
426 }
427}
428
429// branchTitle is a branch's title: the subject of the first of its own
430// commits on its first-parent line, those its head reaches and not leaves
431// out.
432func (s *snapshot) branchTitle(head string, not []string) string {
433 out, _ := s.g.output(true, append([]string{"log", "--first-parent", "--reverse", "--format=%s", head}, not...)...)
434 first, _, _ := strings.Cut(out, "\n")
435 return readable(change.Title(first))
436}
437
438func counted(n int, noun string) string {
439 switch n {
440 case 0:
441 return "no " + noun + "s"
442 case 1:
443 return "1 " + noun
444 }
445 return fmt.Sprintf("%d %ss", n, noun)
446}
447
448// drawStack is the lines of a stack: the top entry's block, then the
449// block of each entry listed under it, at one indentation however deep the
450// stack is. Each listed entry is on the entry listed right after it, and
451// says "on <base>" where it is not.
452func (t terminal) drawStack(top *entry) []string {
453 list := append([]*entry{top}, top.below...)
454 var lines []string
455 for i, e := range list {
456 var next *entry
457 if i+1 < len(list) {
458 next = list[i+1]
459 }
460 first, rest := "", " "
461 switch {
462 case i > 0 && next != nil:
463 first, rest = " ├ ", " │ "
464 case i > 0:
465 first, rest = " └ ", " "
466 }
467 suffix := ""
468 if e.section != top.section {
469 for _, sec := range sections {
470 if sec.name == e.section {
471 suffix = " (" + sec.kind + ")"
472 }
473 }
474 }
475 lines = append(lines, t.nameLine(first, e.name, suffix, e, rest)...)
476 lines = append(lines, rest+t.fit(e.title, rest), rest+t.fit(e.layer, rest))
477 switch {
478 case e.base == next:
479 case e.base != nil:
480 lines = append(lines, rest+"on "+e.base.ref)
481 default:
482 lines = append(lines, rest+"on "+recordTarget)
483 }
484 lines = append(lines, prefixed(rest, e.includes)...)
485 for _, note := range e.notes {
486 lines = append(lines, rest+t.fit(note, rest))
487 }
488 if i == 0 && len(top.below) > 0 {
489 lands := fmt.Sprintf("approving it lands the %d below too", len(top.below))
490 if len(top.below) == 1 {
491 lands = "approving it lands the one below too"
492 }
493 lines = append(lines, rest+t.fit(lands, rest))
494 }
495 }
496 return lines
497}
498
499func prefixed(lead string, lines []string) []string {
500 var out []string
501 for _, l := range lines {
502 out = append(out, lead+l)
503 }
504 return out
505}
506
507// nameLine is an entry's first line: its name, in bold on a terminal, and
508// the head's age and author at the right margin. When that leaves too
509// little room, the author is cut short. When even that leaves too little,
510// the age and author go on a line of their own, indented as rest is.
511func (t terminal) nameLine(lead, name, suffix string, e *entry, rest string) []string {
512 left := lead + t.strong(name) + suffix
513 used := columns(lead + name + suffix)
514 if e.age == "" && e.author == "" {
515 return []string{left}
516 }
517 right := e.age + " · " + e.author
518 if room := t.width - used - 2; columns(right) > room {
519 short := room - columns(e.age+" · ")
520 if short < 4 {
521 return []string{left, rest + t.fit(right, rest)}
522 }
523 right = e.age + " · " + fit(e.author, short)
524 }
525 return []string{left + strings.Repeat(" ", t.width-used-columns(right)) + right}
526}
527
528// branchName is a branch's name as printed: as it is, or, when it holds a
529// character that is not printable or bytes that are not UTF-8, in the
530// $'...' form a shell reads back as the same name.
531func branchName(b string) string {
532 if printable(b) {
533 return b
534 }
535 return shellQuote(b)
536}
537
538// readable is s as text to print: valid UTF-8, with every control
539// character, which a terminal could act on, made a space.
540func readable(s string) string {
541 return strings.Map(func(r rune) rune {
542 if unicode.IsControl(r) {
543 return ' '
544 }
545 return r
546 }, strings.ToValidUTF8(s, "�"))
547}
548
549// checks says how many checks the policy requires of a head, by cost, as
550// valley checks derives them against the merge base with main. It runs
551// the valley command bin/valley names in VALLEY_COMMAND, inside the
552// repository the change is in.
553func (s *snapshot) checks(head string) string {
554 valley := os.Getenv("VALLEY_COMMAND")
555 if valley == "" {
556 valley = "valley"
557 }
558 base, err := s.g.output(true, "merge-base", s.tip, head)
559 if err != nil {
560 return "requires ? (no merge base with main)"
561 }
562 cmd := exec.Command(valley, "checks", base, head)
563 cmd.Dir = s.g.dir
564 cmd.Env = s.g.env
565 out, err := cmd.Output()
566 if err != nil {
567 return "requires ? (the policy did not derive)"
568 }
569 count := func(prefix string) int {
570 for _, line := range strings.Split(string(out), "\n") {
571 if rest, ok := strings.CutPrefix(line, prefix); ok && rest != "none" {
572 return len(strings.Split(rest, ", "))
573 }
574 }
575 return 0
576 }
577 quick, slow := count("quick: "), count("slow: ")
578 if quick+slow == 0 {
579 return "requires no checks"
580 }
581 noun := "checks"
582 if quick == 1 {
583 noun = "check"
584 }
585 return fmt.Sprintf("requires %d quick %s, %d slow", quick, noun, slow)
586}