gunk-dev/the-valley

pending.go

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