gunk-dev/the-valley

pending.go

source6d46e06e6fc3main's published tip history
16.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//
10// Each entry is a block. Its first line is its name, with the age and
11// author of its head: the handle and version of a change, the name of a
12// branch, and for a draft its handle and version on its branch. The lines
13// indented under it give its title, then the commits and the diff the
14// entry adds to its base:
15//
16// act-on-a-change-by-handle-key-its-1902807a 9 hours ago · patflynn-agent
17// change: share the record bounds and the c-<change ID> request name
18// 10 commits · 31 files +2412 −404
19// └ find-changes-across-repos-valley-changes-1e788c4f 10 hours ago · patfly…
20// valley: changes --json and pending by handle, across a host's projects
21// 9 commits · 17 files +2701 −137
22//
23// A change's title is its record's, for the active version. A branch's
24// title is the subject of its first own commit: the oldest commit on its
25// first-parent line that its base does not hold.
26//
27// An entry's base is the nearest other entry its head strictly contains,
28// or main when there is none. That is the ancestry includes reads
29// (inventory.go). Each entry is nested under the nearest entry that
30// contains it, so approving the entry at the top of a stack lands every
31// entry nested under it. A stack is printed in the section of its top
32// entry, and a nested entry from another section says which it is in. Past
33// the third level the stack is drawn no deeper, and an entry whose base is
34// not drawn right under it says "on <base>".
35//
36// A change may say more, each on a line of its own. includes <handle>
37// names a change its head contains that is not an entry here, such as a
38// withdrawn one. uncertain says the active version may have landed without
39// its evidence being stored. With --owes, it says how many checks the
40// change owes, by cost.
41//
42// Within a section, the stack with the latest commit comes first, and
43// within a stack the entry with the latest commit does. Every line fits
44// stdout's terminal, or 80 columns when stdout is no terminal or does not
45// know its width. A title or an author is cut short with …; a handle or a
46// branch never is. On a terminal, names are bold, unless NO_COLOR is set.
47//
48// With --json it prints valley-pending/v1: valley-changes/v1's shape, with
49// the pending changes alone in changes, the drafts in an array of their
50// own, drafts, and the same branches.
51
52package main
53
54import (
55 "fmt"
56 "io"
57 "os"
58 "os/exec"
59 "sort"
60 "strconv"
61 "strings"
62 "unicode"
63
64 "the-valley/change"
65)
66
67// pendingChange is a ready change whose active version has not landed.
68func pendingChange(s *snapshot, n recorded) bool {
69 return n.record.State == change.Ready && !s.isLanded(n.id, n.record.ActiveVersion())
70}
71
72// unlanded is a change in any state whose active version has not landed:
73// the changes a pending change may include.
74func unlanded(s *snapshot, n recorded) bool {
75 return !s.isLanded(n.id, n.record.ActiveVersion())
76}
77
78func isDraft(_ *snapshot, n recorded) bool {
79 return n.record.State == change.Draft
80}
81
82// pendingView is a repository as valley-pending/v1 writes it: the pending
83// changes in changes and the drafts in drafts, each with includes among
84// the changes that have not landed.
85func (l listed) pendingView(h handleMap) jsonRepo {
86 r := l.repoView(h, pendingChange, unlanded)
87 drafts := []jsonChange{}
88 if l.err == nil {
89 drafts = l.repoView(h, isDraft, unlanded).Changes
90 }
91 r.Drafts = &drafts
92 return r
93}
94
95func runPending(g git, args []string, stdout, stderr io.Writer) error {
96 l, err := parseListing("pending", args, true)
97 if err != nil {
98 return err
99 }
100 list, host, err := sources(g, l, stderr)
101 if err != nil {
102 return err
103 }
104 repos := readSources(list, verifierFromEnv())
105 h := handles(repos)
106 defer warnUnverified(repos, stderr)
107 if l.asJSON {
108 doc := jsonChanges{Schema: pendingSchema, Host: host, Repos: []jsonRepo{}}
109 for _, r := range repos {
110 view := r.pendingView(h)
111 utf8Branches(&view, stderr)
112 doc.Repos = append(doc.Repos, view)
113 }
114 return writeDocument(stdout, doc)
115 }
116 t := terminalOf(stdout)
117 for i, r := range repos {
118 if i > 0 {
119 fmt.Fprintln(stdout)
120 }
121 writePending(r, h, l, stdout, len(repos) > 1 || l.all || l.repo != "", t)
122 }
123 return nil
124}
125
126// sections are valley pending's sections, in the order they are printed,
127// each with the word a nested entry from it is marked with.
128var sections = []struct{ name, kind string }{
129 {"ready", "ready"}, {"branches", "branch"}, {"drafts", "draft"},
130}
131
132// maxDepth is the deepest level a stack is drawn at. The top is level 0.
133const maxDepth = 2
134
135// entry is one block of valley pending: a ready change, a branch no record
136// is on, or a draft.
137type entry struct {
138 section string
139 name string // what the block's first line names
140 ref string // what the entry is typed as: its handle, or its branch
141 head string // the head commit
142 title string // the record's title; for a branch, read by measure
143 includes []string // what includes names that is not nested under it
144 notes []string // uncertain and owes
145
146 when int64 // the head's commit time
147 age, author string
148 layer string // the commits and the diff it adds to its base
149
150 parent *entry
151 kids []*entry
152 base *entry // nil for main
153 latest int64 // the latest commit time in the stack it tops
154}
155
156// writePending prints one repository's entries, section by section.
157// Several repositories are each headed by their name.
158func writePending(r listed, h handleMap, l listing, w io.Writer, headed bool, t terminal) {
159 p := func(format string, args ...any) { fmt.Fprintf(w, format, args...) }
160 if r.err != nil {
161 p("%s: %v\n", r.name, r.err)
162 return
163 }
164 if headed {
165 p("%s\n%s\n", r.name, strings.Repeat("─", min(columns(r.name), t.width)))
166 }
167 all := r.entries(r.pendingView(h), h, l)
168 tops := r.snap.stack(all)
169 gap := false
170 for _, sec := range sections {
171 var here []*entry
172 for _, e := range tops {
173 if e.section == sec.name {
174 here = append(here, e)
175 }
176 }
177 if sec.name == "ready" && len(here) == 0 {
178 nested := false
179 for _, e := range all {
180 nested = nested || e.section == "ready"
181 }
182 if nested {
183 p("nothing is ready at the top of a stack\n")
184 } else {
185 p("nothing is ready\n")
186 }
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, the
262// stack with the latest commit first, with every list of nested entries
263// ordered the same way.
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 }
271 }
272 // nearest is the entries i contains, or that contain i, with none
273 // between.
274 nearest := func(i int, above bool) []*entry {
275 var near []*entry
276 for j := range all {
277 outer, inner := j, i
278 if !above {
279 outer, inner = i, j
280 }
281 if !in[outer][inner] {
282 continue
283 }
284 between := false
285 for k := range all {
286 between = between || in[outer][k] && in[k][inner]
287 }
288 if !between {
289 near = append(near, all[j])
290 }
291 }
292 byActivity(near, func(e *entry) int64 { return e.when })
293 return near
294 }
295 for i, e := range all {
296 if above := nearest(i, true); len(above) > 0 {
297 e.parent = above[0]
298 e.parent.kids = append(e.parent.kids, e)
299 }
300 }
301 var tops []*entry
302 for i, e := range all {
303 below := nearest(i, false)
304 for _, d := range below {
305 if d.parent == e {
306 e.base = d
307 break
308 }
309 }
310 if e.base == nil && len(below) > 0 {
311 e.base = below[0]
312 }
313 s.measure(e)
314 if e.parent == nil {
315 tops = append(tops, e)
316 }
317 }
318 var latest func(e *entry) int64
319 latest = func(e *entry) int64 {
320 e.latest = e.when
321 for _, k := range e.kids {
322 e.latest = max(e.latest, latest(k))
323 }
324 byActivity(e.kids, func(e *entry) int64 { return e.latest })
325 return e.latest
326 }
327 for _, e := range tops {
328 latest(e)
329 }
330 byActivity(tops, func(e *entry) int64 { return e.latest })
331 return tops
332}
333
334// byActivity orders entries latest first, and then by name.
335func byActivity(list []*entry, when func(*entry) int64) {
336 sort.SliceStable(list, func(i, j int) bool {
337 if a, b := when(list[i]), when(list[j]); a != b {
338 return a > b
339 }
340 return list[i].name < list[j].name
341 })
342}
343
344// measure reads what an entry adds to its base: how many commits, and the
345// diff from the base, or from its merge base with main. A branch's title
346// is the subject of the first of those commits on its first-parent line.
347func (s *snapshot) measure(e *entry) {
348 var not []string
349 from := s.tip
350 if e.base != nil {
351 not, from = append(not, "^"+e.base.head), e.base.head
352 }
353 if s.tip != "" {
354 not = append(not, "^"+s.tip)
355 }
356 if from == "" {
357 from, _ = s.g.input(true, strings.NewReader(""), "hash-object", "-t", "tree", "--stdin")
358 }
359 commits := "? commits"
360 if out, err := s.g.output(true, append([]string{"rev-list", "--count", e.head}, not...)...); err == nil {
361 n, _ := strconv.Atoi(out)
362 commits = counted(n, "commit")
363 }
364 files, added, deleted := 0, 0, 0
365 out, _ := s.g.output(true, "diff", "--numstat", from+"..."+e.head)
366 for _, line := range strings.Split(out, "\n") {
367 if f := strings.SplitN(line, "\t", 3); len(f) == 3 {
368 a, _ := strconv.Atoi(f[0]) // a binary file's counts are -, read as 0
369 d, _ := strconv.Atoi(f[1])
370 files, added, deleted = files+1, added+a, deleted+d
371 }
372 }
373 diff := "no file changes"
374 if files > 0 {
375 diff = fmt.Sprintf("%s +%d −%d", counted(files, "file"), added, deleted)
376 }
377 e.layer = commits + " · " + diff
378 if e.section == "branches" {
379 out, _ := s.g.output(true, append([]string{"log", "--first-parent", "--reverse", "--format=%s", e.head}, not...)...)
380 first, _, _ := strings.Cut(out, "\n")
381 e.title = readable(change.Title(first))
382 }
383}
384
385func counted(n int, noun string) string {
386 switch n {
387 case 0:
388 return "no " + noun + "s"
389 case 1:
390 return "1 " + noun
391 }
392 return fmt.Sprintf("%d %ss", n, noun)
393}
394
395// drawStack is the lines of a stack: each entry's block, every nested
396// entry indented under the one that contains it, and joined to it by a
397// line drawn in the margin.
398func (t terminal) drawStack(top *entry) []string {
399 type drawn struct {
400 e *entry
401 depth int
402 last bool // no later entry at its depth before one nearer the top
403 }
404 var list []drawn
405 var walk func(e *entry, depth int)
406 walk = func(e *entry, depth int) {
407 list = append(list, drawn{e: e, depth: min(depth, maxDepth)})
408 for _, k := range e.kids {
409 walk(k, depth+1)
410 }
411 }
412 walk(top, 0)
413 for i := range list {
414 list[i].last = true
415 for j := i + 1; j < len(list) && list[j].depth >= list[i].depth; j++ {
416 if list[j].depth == list[i].depth {
417 list[i].last = false
418 break
419 }
420 }
421 }
422 rail := func(more bool) string {
423 if more {
424 return "│ "
425 }
426 return " "
427 }
428 var lines []string
429 more := make([]bool, maxDepth+1) // more[k]: the entry last drawn at depth k has more after it
430 for _, d := range list {
431 more[d.depth] = !d.last
432 first, rest := "", " "
433 if d.depth > 0 {
434 lead := " "
435 for k := 1; k < d.depth; k++ {
436 lead += rail(more[k])
437 }
438 first, rest = lead+"├ ", lead+rail(!d.last)
439 if d.last {
440 first = lead + "└ "
441 }
442 }
443 e := d.e
444 suffix := ""
445 if e.section != top.section {
446 for _, sec := range sections {
447 if sec.name == e.section {
448 suffix = " (" + sec.kind + ")"
449 }
450 }
451 }
452 lines = append(lines, t.nameLine(first, e.name, suffix, e, rest)...)
453 lines = append(lines, rest+t.fit(e.title, rest), rest+t.fit(e.layer, rest))
454 if e.base != nil && (e.base.parent != e || d.depth == maxDepth) {
455 lines = append(lines, rest+"on "+e.base.ref)
456 }
457 lines = append(lines, prefixed(rest, e.includes)...)
458 for _, note := range e.notes {
459 lines = append(lines, rest+t.fit(note, rest))
460 }
461 }
462 return lines
463}
464
465func prefixed(lead string, lines []string) []string {
466 var out []string
467 for _, l := range lines {
468 out = append(out, lead+l)
469 }
470 return out
471}
472
473// nameLine is an entry's first line: its name, in bold on a terminal, and
474// the head's age and author at the right margin. When that leaves too
475// little room, the author is cut short. When even that leaves too little,
476// the age and author go on a line of their own, indented as rest is.
477func (t terminal) nameLine(lead, name, suffix string, e *entry, rest string) []string {
478 left := lead + t.strong(name) + suffix
479 used := columns(lead + name + suffix)
480 if e.age == "" && e.author == "" {
481 return []string{left}
482 }
483 right := e.age + " · " + e.author
484 if room := t.width - used - 2; columns(right) > room {
485 short := room - columns(e.age+" · ")
486 if short < 4 {
487 return []string{left, rest + t.fit(right, rest)}
488 }
489 right = e.age + " · " + fit(e.author, short)
490 }
491 return []string{left + strings.Repeat(" ", t.width-used-columns(right)) + right}
492}
493
494// branchName is a branch's name as printed: as it is, or, when it holds a
495// character that is not printable or bytes that are not UTF-8, in the
496// $'...' form a shell reads back as the same name.
497func branchName(b string) string {
498 if printable(b) {
499 return b
500 }
501 return shellQuote(b)
502}
503
504// readable is s as text to print: valid UTF-8, with every control
505// character, which a terminal could act on, made a space.
506func readable(s string) string {
507 return strings.Map(func(r rune) rune {
508 if unicode.IsControl(r) {
509 return ' '
510 }
511 return r
512 }, strings.ToValidUTF8(s, "�"))
513}
514
515// owes says how many checks a head owes under the policy, by cost, as
516// valley checks derives them against the merge base with main. It runs
517// the valley command bin/valley names in VALLEY_COMMAND, inside the
518// repository the change is in.
519func (s *snapshot) owes(head string) string {
520 valley := os.Getenv("VALLEY_COMMAND")
521 if valley == "" {
522 valley = "valley"
523 }
524 base, err := s.g.output(true, "merge-base", s.tip, head)
525 if err != nil {
526 return "owes ? (no merge base with main)"
527 }
528 cmd := exec.Command(valley, "checks", base, head)
529 cmd.Dir = s.g.dir
530 cmd.Env = s.g.env
531 out, err := cmd.Output()
532 if err != nil {
533 return "owes ? (the policy did not derive)"
534 }
535 count := func(prefix string) int {
536 for _, line := range strings.Split(string(out), "\n") {
537 if rest, ok := strings.CutPrefix(line, prefix); ok && rest != "none" {
538 return len(strings.Split(rest, ", "))
539 }
540 }
541 return 0
542 }
543 quick, slow := count("quick: "), count("slow: ")
544 if quick+slow == 0 {
545 return "owes nothing"
546 }
547 return fmt.Sprintf("owes %d quick, %d slow", quick, slow)
548}