gunk-dev/the-valley

pending.go

sourced5649addb600main's published tip history
18.5 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 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, as the rebase engine stacks layers
263// (rebase.Snapshot.Nest). Where two are equally near, the one with the
264// later commit is taken. It returns the entries nested under none, each the
265// top of a stack, the stack with the latest commit first. Each top lists
266// every entry nested under it, at any depth, in its below.
267func (s *snapshot) stack(all []*entry) []*entry {
268 nodes := make([]rebase.Node, len(all))
269 for i, e := range all {
270 nodes[i] = rebase.Node{Name: e.name, Head: e.head, When: e.when}
271 }
272 nest := s.land.Nest(nodes)
273 for i, e := range all {
274 for _, j := range nest.Inside[i] {
275 e.inside = append(e.inside, all[j])
276 }
277 if p := nest.Parent[i]; p >= 0 {
278 e.parent = all[p]
279 e.parent.kids = append(e.parent.kids, e)
280 }
281 }
282 var tops []*entry
283 for i, e := range all {
284 if b := nest.Base[i]; b >= 0 {
285 e.base = all[b]
286 }
287 s.measure(e)
288 if e.parent == nil {
289 tops = append(tops, e)
290 }
291 }
292 for _, top := range tops {
293 top.list()
294 }
295 byActivity(tops, func(e *entry) int64 { return e.latest })
296 return tops
297}
298
299// list puts every entry nested under the top of a stack in its below, each
300// before the entries it contains. Where it can, it lists next the base of
301// the entry it listed last, so a chain is listed unbroken. Otherwise it
302// lists next the entry with the latest commit. It sets latest, the latest
303// commit time in the stack.
304func (top *entry) list() {
305 nested := map[*entry]bool{}
306 var walk func(e *entry)
307 walk = func(e *entry) {
308 for _, k := range e.kids {
309 nested[k] = true
310 walk(k)
311 }
312 }
313 walk(top)
314 top.latest = top.when
315 for last := top; len(nested) > 0; {
316 var free []*entry // those every entry containing them is listed before
317 for e := range nested {
318 listable := true
319 for _, c := range e.inside {
320 listable = listable && !nested[c]
321 }
322 if listable {
323 free = append(free, e)
324 }
325 }
326 byActivity(free, func(e *entry) int64 { return e.when })
327 next := free[0]
328 for _, e := range free {
329 if e == last.base {
330 next = e
331 }
332 }
333 delete(nested, next)
334 top.below = append(top.below, next)
335 top.latest = max(top.latest, next.when)
336 last = next
337 }
338}
339
340// readyElsewhere is what the ready section says when no ready change is at
341// the top of a stack: that nothing is ready, or where the ready changes in
342// other sections' stacks are.
343func readyElsewhere(tops []*entry) string {
344 n, stacks := 0, 0
345 var where []string
346 for _, sec := range sections {
347 found := false
348 for _, top := range tops {
349 held := 0
350 for _, e := range top.below {
351 if e.section == "ready" {
352 held++
353 }
354 }
355 if top.section == sec.name && held > 0 {
356 n, stacks, found = n+held, stacks+1, true
357 }
358 }
359 if found {
360 where = append(where, sec.name)
361 }
362 }
363 if n == 0 {
364 return "nothing is ready"
365 }
366 verb, in := "are", fmt.Sprintf("%d stacks", stacks)
367 if n == 1 {
368 verb = "is"
369 }
370 if stacks == 1 {
371 in = "a stack"
372 }
373 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 "))
374}
375
376// byActivity orders entries latest first, and then by name.
377func byActivity(list []*entry, when func(*entry) int64) {
378 sort.SliceStable(list, func(i, j int) bool {
379 if a, b := when(list[i]), when(list[j]); a != b {
380 return a > b
381 }
382 return list[i].name < list[j].name
383 })
384}
385
386// measure reads what an entry adds to its base: how many commits, and the
387// diff from the base, or from its merge base with main. A branch's title
388// is the subject of the first of those commits on its first-parent line.
389func (s *snapshot) measure(e *entry) {
390 var not []string
391 from := s.tip
392 if e.base != nil {
393 not, from = append(not, "^"+e.base.head), e.base.head
394 }
395 if s.tip != "" {
396 not = append(not, "^"+s.tip)
397 }
398 if from == "" {
399 from, _ = s.g.input(true, strings.NewReader(""), "hash-object", "-t", "tree", "--stdin")
400 }
401 commits := "? commits"
402 if out, err := s.g.output(true, append([]string{"rev-list", "--count", e.head}, not...)...); err == nil {
403 n, _ := strconv.Atoi(out)
404 commits = counted(n, "commit")
405 }
406 files, added, deleted := 0, 0, 0
407 out, _ := s.g.output(true, "diff", "--numstat", from+"..."+e.head)
408 for _, line := range strings.Split(out, "\n") {
409 if f := strings.SplitN(line, "\t", 3); len(f) == 3 {
410 a, _ := strconv.Atoi(f[0]) // a binary file's counts are -, read as 0
411 d, _ := strconv.Atoi(f[1])
412 files, added, deleted = files+1, added+a, deleted+d
413 }
414 }
415 diff := "no file changes"
416 if files > 0 {
417 diff = fmt.Sprintf("%s +%d −%d", counted(files, "file"), added, deleted)
418 }
419 e.layer = commits + " · " + diff
420 if e.section == "branches" {
421 e.title = s.branchTitle(e.head, not)
422 }
423}
424
425// branchTitle is a branch's title: the subject of the first of its own
426// commits on its first-parent line, those its head reaches and not leaves
427// out.
428func (s *snapshot) branchTitle(head string, not []string) string {
429 out, _ := s.g.output(true, append([]string{"log", "--first-parent", "--reverse", "--format=%s", head}, not...)...)
430 first, _, _ := strings.Cut(out, "\n")
431 return readable(change.Title(first))
432}
433
434func counted(n int, noun string) string {
435 switch n {
436 case 0:
437 return "no " + noun + "s"
438 case 1:
439 return "1 " + noun
440 }
441 return fmt.Sprintf("%d %ss", n, noun)
442}
443
444// drawStack is the lines of a stack: the top entry's block, then the
445// block of each entry listed under it, at one indentation however deep the
446// stack is. Each listed entry is on the entry listed right after it, and
447// says "on <base>" where it is not.
448func (t terminal) drawStack(top *entry) []string {
449 list := append([]*entry{top}, top.below...)
450 var lines []string
451 for i, e := range list {
452 var next *entry
453 if i+1 < len(list) {
454 next = list[i+1]
455 }
456 first, rest := "", " "
457 switch {
458 case i > 0 && next != nil:
459 first, rest = " ├ ", " │ "
460 case i > 0:
461 first, rest = " └ ", " "
462 }
463 suffix := ""
464 if e.section != top.section {
465 for _, sec := range sections {
466 if sec.name == e.section {
467 suffix = " (" + sec.kind + ")"
468 }
469 }
470 }
471 lines = append(lines, t.nameLine(first, e.name, suffix, e, rest)...)
472 lines = append(lines, rest+t.fit(e.title, rest), rest+t.fit(e.layer, rest))
473 switch {
474 case e.base == next:
475 case e.base != nil:
476 lines = append(lines, rest+"on "+e.base.ref)
477 default:
478 lines = append(lines, rest+"on "+recordTarget)
479 }
480 lines = append(lines, prefixed(rest, e.includes)...)
481 for _, note := range e.notes {
482 lines = append(lines, rest+t.fit(note, rest))
483 }
484 if i == 0 && len(top.below) > 0 {
485 lands := fmt.Sprintf("approving it lands the %d below too", len(top.below))
486 if len(top.below) == 1 {
487 lands = "approving it lands the one below too"
488 }
489 lines = append(lines, rest+t.fit(lands, rest))
490 }
491 }
492 return lines
493}
494
495func prefixed(lead string, lines []string) []string {
496 var out []string
497 for _, l := range lines {
498 out = append(out, lead+l)
499 }
500 return out
501}
502
503// nameLine is an entry's first line: its name, in bold on a terminal, and
504// the head's age and author at the right margin. When that leaves too
505// little room, the author is cut short. When even that leaves too little,
506// the age and author go on a line of their own, indented as rest is.
507func (t terminal) nameLine(lead, name, suffix string, e *entry, rest string) []string {
508 left := lead + t.strong(name) + suffix
509 used := columns(lead + name + suffix)
510 if e.age == "" && e.author == "" {
511 return []string{left}
512 }
513 right := e.age + " · " + e.author
514 if room := t.width - used - 2; columns(right) > room {
515 short := room - columns(e.age+" · ")
516 if short < 4 {
517 return []string{left, rest + t.fit(right, rest)}
518 }
519 right = e.age + " · " + fit(e.author, short)
520 }
521 return []string{left + strings.Repeat(" ", t.width-used-columns(right)) + right}
522}
523
524// branchName is a branch's name as printed: as it is, or, when it holds a
525// character that is not printable or bytes that are not UTF-8, in the
526// $'...' form a shell reads back as the same name.
527func branchName(b string) string {
528 if printable(b) {
529 return b
530 }
531 return shellQuote(b)
532}
533
534// readable is s as text to print: valid UTF-8, with every control
535// character, which a terminal could act on, made a space.
536func readable(s string) string {
537 return strings.Map(func(r rune) rune {
538 if unicode.IsControl(r) {
539 return ' '
540 }
541 return r
542 }, strings.ToValidUTF8(s, "�"))
543}
544
545// checks says how many checks the policy requires of a head, by cost, as
546// valley checks derives them against the merge base with main. It runs
547// the valley command bin/valley names in VALLEY_COMMAND, inside the
548// repository the change is in.
549func (s *snapshot) checks(head string) string {
550 valley := os.Getenv("VALLEY_COMMAND")
551 if valley == "" {
552 valley = "valley"
553 }
554 base, err := s.g.output(true, "merge-base", s.tip, head)
555 if err != nil {
556 return "requires ? (no merge base with main)"
557 }
558 cmd := exec.Command(valley, "checks", base, head)
559 cmd.Dir = s.g.dir
560 cmd.Env = s.g.env
561 out, err := cmd.Output()
562 if err != nil {
563 return "requires ? (the policy did not derive)"
564 }
565 count := func(prefix string) int {
566 for _, line := range strings.Split(string(out), "\n") {
567 if rest, ok := strings.CutPrefix(line, prefix); ok && rest != "none" {
568 return len(strings.Split(rest, ", "))
569 }
570 }
571 return 0
572 }
573 quick, slow := count("quick: "), count("slow: ")
574 if quick+slow == 0 {
575 return "requires no checks"
576 }
577 noun := "checks"
578 if quick == 1 {
579 noun = "check"
580 }
581 return fmt.Sprintf("requires %d quick %s, %d slow", quick, noun, slow)
582}