gunk-dev/the-valley

reviewpage.go

source8c40ee5f164cmain's published tip history
20.8 KiB
1package main
2
3// What review shows of a change: the page, set against the change's
4// approved version; the pager it is read in; the notes the reviewer
5// inserts into it; and the checks line above the prompt.
6//
7// The page is set against the change's approved version: the greatest
8// version below it whose head a request or an outcome on origin names
9// (compare.go). none has no approved version to compare with, so review
10// pages the whole diff, under any note compare gives, such as an approved
11// version it could not compare. clean has the approved version's file
12// delta: review prints that in a few lines, with the landings between the
13// two bases, and pages nothing. changed pages the files whose change
14// differs, with the landings that edited them, the range-diff when a
15// commit was edited, and the shown version's diff of those files. A note
16// taken beside the range-diff is unanchored, since its hunks carry no line
17// numbers; the last diff is in git's ordinary form, so a note taken there
18// keeps its file and line. [v]iew full diff pages the whole diff at every
19// prompt. The comparison files no request and skips no check.
20//
21// The page is a file rather than a pipe, so less's v key has something to
22// hand the editor: editing it is how notes are written. Whatever comes
23// back with lines inserted is read as notes: no marker, no syntax, no
24// mode. An inserted line is a note because it was not there before, and
25// it is anchored to the file and the new-side line number of the diff
26// line above it, which is the pair a reviewer would otherwise copy out by
27// hand. Notes are kept in $XDG_STATE_HOME/valley/notes, since they are
28// neither config nor cache, and losing them loses judgment.
29
30import (
31 "bytes"
32 "fmt"
33 "io"
34 "os"
35 "os/exec"
36 "path/filepath"
37 "regexp"
38 "strconv"
39 "strings"
40 "syscall"
41 "time"
42)
43
44// showReview shows a change alone. A change that is not ready says so
45// first, before anything else shown of it, and that notice becomes the
46// heading, so the change's knots follow it.
47func (r *review) showReview(branch string) {
48 head := r.changeHead(branch)
49 // [a]pprove approves exactly the head shown here (bind).
50 if r.c.id == "" {
51 r.approveHead = head
52 }
53 held := notReady(r.c.handle, r.c.version, r.c.state, r.c.owner)
54 r.newScratch()
55 kind, compared := r.compareShown(r.c.id, r.c.version, head)
56 r.showCompared(branch, head, held, r.doesOf(r.c.id), kind, compared, func(w io.Writer) { r.fullDiff(w, branch, head) })
57 r.checksClause = r.checksLine(r.c.id, false)
58}
59
60// viewFull is [v]iew full diff for a change alone: its whole diff paged,
61// and the notes taken in it kept.
62func (r *review) viewFull(branch string) {
63 head := r.changeHead(branch)
64 dir := r.newScratch()
65 var b bytes.Buffer
66 r.fullDiff(&b, branch, head)
67 r.writePage(dir, b.Bytes())
68 r.pageBuffer(branch, r.short(head))
69}
70
71// compareShown sets the version shown against the change's approved
72// version, against main's tip as the fetch left it. It returns none,
73// clean or changed, and the text to show. A plain branch is none, and so
74// is a comparison that could not be made, with a warning.
75func (r *review) compareShown(id, version, head string) (kind, text string) {
76 if id == "" {
77 return compareNone, ""
78 }
79 var out bytes.Buffer
80 compared := false
81 if tip := r.ref("refs/remotes/origin/main"); tip != "" {
82 args := []string{"--tip", tip, id, version, head}
83 if r.verbose {
84 args = append([]string{"-v"}, args...)
85 }
86 if err := runCompare(r.g, args, &out); err != nil {
87 fmt.Fprintf(r.stderr, "valley: %s\n", err)
88 } else {
89 compared = true
90 }
91 }
92 if !compared {
93 fmt.Fprintf(r.stderr, "valley: warning: could not compare v%s of change %s with its approved version; reviewing it in full\n", version, id)
94 return compareNone, ""
95 }
96 kind, text, _ = strings.Cut(out.String(), "\n")
97 return kind, text
98}
99
100// showCompared shows what compareShown found, under the heading when
101// there is one. A clean restack is printed, and nothing is paged. A
102// changed version pages the comparison. Otherwise the writer writes the
103// whole diff, and it is paged. Notes taken in a page are kept under key,
104// against head.
105//
106// Knots follow the heading when there is one. Otherwise they follow the
107// first line of the comparison or the whole diff, which names the change.
108func (r *review) showCompared(key, head, heading, knots, kind, compared string, writer func(io.Writer)) {
109 sha := r.short(head)
110 var body bytes.Buffer
111 body.WriteString(compared)
112 if kind == compareNone {
113 writer(&body)
114 }
115 var page bytes.Buffer
116 if heading != "" {
117 page.WriteString(heading + "\n")
118 if knots != "" {
119 page.WriteString(knots + "\n")
120 }
121 page.Write(body.Bytes())
122 } else if body.Len() > 0 {
123 first, rest, _ := strings.Cut(body.String(), "\n")
124 page.WriteString(first + "\n")
125 if knots != "" {
126 page.WriteString(knots + "\n")
127 }
128 page.WriteString(rest)
129 }
130 r.mu.Lock()
131 dir := r.scratch
132 r.mu.Unlock()
133 r.writePage(dir, page.Bytes())
134 if kind == compareClean {
135 f, err := os.Open(filepath.Join(dir, "review.diff"))
136 if err == nil {
137 runStyle(nil, f, r.stdout)
138 f.Close()
139 }
140 r.dropScratch()
141 return
142 }
143 r.pageBuffer(key, sha)
144}
145
146// writePage writes the page to review.diff in dir.
147func (r *review) writePage(dir string, page []byte) {
148 if err := os.WriteFile(filepath.Join(dir, "review.diff"), page, 0o600); err != nil {
149 r.die(fmt.Sprintf("could not write the page: %v", err))
150 }
151}
152
153// fullDiff writes the whole diff of a change alone: its log and its diff
154// against origin/main. main is read by its exact name, since git would
155// take a tag named origin/main for it. A main that cannot be read ends the
156// review, as a page it cannot write does (gitTo).
157func (r *review) fullDiff(w io.Writer, branch, head string) {
158 sha := r.short(head)
159 tip := r.ref("refs/remotes/origin/main")
160 if tip == "" {
161 r.exit(1)
162 }
163 if r.c.head != "" {
164 fmt.Fprintf(w, "change %s v%s at %s, on branch %s, log against origin/main:\n\n", r.c.handle, r.c.version, sha, branch)
165 } else {
166 fmt.Fprintf(w, "branch %s, log against origin/main:\n\n", branch)
167 }
168 r.commitLog(w, tip+".."+head)
169 r.gitTo(w, "--no-pager", "diff", tip+"..."+head)
170}
171
172// commitLog writes each commit in the range, newest first: its short hash
173// and subject, its body indented four spaces, and a blank line. The whole
174// message is shown because a change lands with its head commit's. The
175// indent keeps a body line from reading as a diff header, to the notes'
176// anchors and to the diff pager alike.
177func (r *review) commitLog(w io.Writer, revs string) {
178 r.gitTo(w, "--no-pager", "log", "--format=%h %s%n%w(0,4,4)%b", revs)
179}
180
181// gitTo runs git with its output written to w. A git that fails ends the
182// review with git's status, having said why: the page would be incomplete,
183// and no answer is asked about a page the operator could not read whole.
184func (r *review) gitTo(w io.Writer, args ...string) {
185 cmd := exec.Command("git", args...)
186 cmd.Env, cmd.Stdout, cmd.Stderr = r.g.env, w, r.stderr
187 processStarted()
188 if err := cmd.Run(); err != nil {
189 r.exit(exitCode(err))
190 }
191}
192
193// pageBuffer pages the page written to the scratch directory, keeps the
194// notes taken in it under key, against the commit shown, and removes it.
195func (r *review) pageBuffer(key, sha string) {
196 r.mu.Lock()
197 dir := r.scratch
198 r.mu.Unlock()
199 page := filepath.Join(dir, "review.diff")
200 orig := filepath.Join(dir, "review.orig")
201 if data, err := os.ReadFile(page); err == nil {
202 if err := os.WriteFile(orig, data, 0o600); err != nil {
203 r.die(fmt.Sprintf("could not keep the page: %v", err))
204 }
205 }
206 r.page(page)
207 r.collectNotes(key, sha, orig, page)
208 r.dropScratch()
209}
210
211// diffPager is the pager git would use for a diff: pager.diff first, as
212// per-command pager configurations set it and leave core.pager alone,
213// then git var GIT_PAGER (core.pager, GIT_PAGER, PAGER, less). pager.diff
214// may legally be a boolean; true, false and an empty value are taken as
215// unset. The value is a shell command line.
216func (r *review) diffPager() string {
217 pager, _ := r.g.output(false, "config", "--get", "pager.diff")
218 switch pager {
219 case "", "true", "false":
220 pager, _ = r.g.output(false, "var", "GIT_PAGER")
221 }
222 return pager
223}
224
225// pageEdit is what less's v key runs (LESSEDIT): the editor less's %E
226// names, VISUAL, then EDITOR, then vi, each a shell command line, on the
227// raw page, and then the rendering again, so the view less reopens shows
228// the notes in place. Paths reach it through the environment, since
229// LESSEDIT is a prompt string in which % ? . : and \ are special.
230const pageEdit = `eval "${VISUAL:-${EDITOR:-vi}} \"\$@\" \"\$VALLEY_PAGE_RAW\""
231 sh -c "$VALLEY_PAGE_RENDER" < "$VALLEY_PAGE_RAW" > "$VALLEY_PAGE_SHOWN"`
232
233// page shows file to the operator. Off a terminal it is printed.
234//
235// The configured diff pager is the renderer, run once as a filter into a
236// sibling file that less pages, with style (style.go) after it, so the
237// pager never reads style's escapes and the raw page has none. v runs
238// pageEdit. What this costs is the line number: v opens the editor at
239// +%lm, a line of the rendered view, so a filter that restructures the
240// diff, as delta's default rendering does, opens it near the cursor
241// rather than on it. A structure-preserving filter (pager.diff = `delta
242// --color-only`) makes it exact. No anchor depends on it: a note is
243// anchored by where it was inserted, not by where the editor opened.
244//
245// A pager that is less already keeps its options, and style alone renders.
246// Without less there is no editor key, and the pager reads the page
247// through a pipe.
248func (r *review) page(file string) {
249 if _, tty := windowColumns(os.Stdout); !tty {
250 if data, err := os.ReadFile(file); err == nil {
251 r.stdout.Write(data)
252 }
253 return
254 }
255 shown := strings.TrimSuffix(file, ".diff") + ".shown"
256 pager, view := r.diffPager(), "less"
257 exe, exeErr := os.Executable()
258 first := pager
259 if i := strings.IndexAny(pager, " \t\n\v\f\r"); i >= 0 {
260 first = pager[:i]
261 }
262 if first == "less" || strings.HasSuffix(first, "/less") {
263 if exeErr != nil {
264 r.shell(pager+` "$1"`, nil, nil, nil, file)
265 return
266 }
267 view, pager = pager, "cat"
268 }
269 if _, err := exec.LookPath("less"); err != nil {
270 in, err := os.Open(file)
271 if err == nil {
272 r.shell(pager, in, nil, nil)
273 in.Close()
274 }
275 return
276 }
277 if exeErr == nil {
278 pager += " | " + shellQuote(exe) + " style --paged"
279 }
280 in, err := os.Open(file)
281 if err != nil {
282 return
283 }
284 out, err := os.Create(shown)
285 if err == nil {
286 r.shell(pager, in, out, nil)
287 out.Close()
288 }
289 in.Close()
290 // -R because the filter's colour is the whole point of running it. No
291 // LESSOPEN, since the filter has run and less answers v on a file read
292 // through one with a warning, then runs the editor on whatever key comes
293 // next, q included; and so no LESSCLOSE.
294 env := []string{}
295 for _, kv := range os.Environ() {
296 name, _, _ := strings.Cut(kv, "=")
297 switch name {
298 case "LESSOPEN", "LESSCLOSE", "LESSEDIT", "VALLEY_PAGE_RAW", "VALLEY_PAGE_SHOWN", "VALLEY_PAGE_RENDER", "VALLEY_PAGE_EDIT":
299 continue
300 }
301 env = append(env, kv)
302 }
303 env = append(env, "VALLEY_PAGE_RAW="+file, "VALLEY_PAGE_SHOWN="+shown, "VALLEY_PAGE_RENDER="+pager,
304 "VALLEY_PAGE_EDIT="+pageEdit, `LESSEDIT=sh -c "$VALLEY_PAGE_EDIT" sh ?lm+%lm.`)
305 r.shell(view+` -R -- "$1"`, nil, nil, env, shown)
306}
307
308// shell runs a shell command line in the foreground, with the arguments
309// given as $1 and on, stdin and stdout the terminal's unless given.
310func (r *review) shell(line string, stdin io.Reader, stdout io.Writer, env []string, args ...string) {
311 cmd := exec.Command("sh", append([]string{"-c", line, "sh"}, args...)...)
312 cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, r.stdout, r.stderr
313 if stdin != nil {
314 cmd.Stdin = stdin
315 }
316 if stdout != nil {
317 cmd.Stdout = stdout
318 }
319 cmd.Env = env
320 r.inForeground(func() { _ = cmd.Run() })
321}
322
323// anchor is where a line of the page sits: the file it belongs to, and
324// the new-side line number. No path is above every file (the log); line 0
325// is a file header, above every hunk.
326type anchor struct {
327 path string
328 line int
329}
330
331// diffHeader is a diff's file header, its b/ side the name a rename will
332// have.
333var diffHeader = regexp.MustCompile(`^diff --git a/(.*) b/(.*)$`)
334
335// pageLines are the lines of data that end in a newline.
336func pageLines(data []byte) []string {
337 s := string(data)
338 if i := strings.LastIndexByte(s, '\n'); i >= 0 {
339 return strings.Split(s[:i], "\n")
340 }
341 return nil
342}
343
344// leadingNumber is the number s starts with, or 0.
345func leadingNumber(s string) int {
346 end := 0
347 for end < len(s) && s[end] >= '0' && s[end] <= '9' {
348 end++
349 }
350 n, _ := strconv.Atoi(s[:end])
351 return n
352}
353
354// anchors is the anchor of every line of the page, by line, built in one
355// pass so that anchoring a note is a lookup.
356func anchors(page []byte) []anchor {
357 var all []anchor
358 path, at, next, inHunk := "", 0, 0, false
359 for _, line := range pageLines(page) {
360 // Header lines are only headers outside a hunk: inside one, every
361 // line carries a +/-/space prefix, so a diff of a diff cannot be
362 // misread.
363 if inHunk {
364 switch {
365 case line == "" || line[0] == ' ' || line[0] == '+':
366 at = next // this line's own new-side number
367 next++
368 case line[0] == '-' || line[0] == '\\':
369 // a removal or the no-newline marker: no new-side line
370 default:
371 inHunk = false
372 }
373 }
374 if !inHunk {
375 switch {
376 case strings.HasPrefix(line, "diff --git "):
377 path = ""
378 if m := diffHeader.FindStringSubmatch(line); m != nil {
379 path = m[2]
380 }
381 at = 0
382 case strings.HasPrefix(line, "@@ "):
383 _, rest, _ := strings.Cut(line, "+") // -12,7 +34,9 @@ -> 34,9 @@
384 at = leadingNumber(rest)
385 next, inHunk = at, true
386 }
387 }
388 all = append(all, anchor{path, at})
389 }
390 return all
391}
392
393// anchorOf is the anchor of a note inserted after page line n, as it is
394// written down.
395func anchorOf(all []anchor, n int) string {
396 if n < 1 || n > len(all) || all[n-1].path == "" {
397 return "(unanchored)"
398 }
399 if a := all[n-1]; a.line != 0 {
400 return fmt.Sprintf("%s:%d", a.path, a.line)
401 }
402 return all[n-1].path
403}
404
405// notesIn is the notes in an edited page, one `anchor: text` line each.
406// git says where the reviewer's lines landed: a hunk that removes nothing
407// is an insertion, and the line it was inserted after is the anchor. A
408// hunk that removes something is an edit of the diff itself, which
409// anchors to nothing, since the line it would name is the line it
410// changed, so it is dropped with a count.
411func (r *review) notesIn(orig, edited string) []string {
412 page, _ := os.ReadFile(orig)
413 all := anchors(page)
414 cmd := exec.Command("git", "--no-pager", "diff", "--no-ext-diff", "--no-index", "-U0", "--", orig, edited)
415 cmd.Env, cmd.Stderr = r.g.env, r.stderr
416 processStarted()
417 out, _ := cmd.Output()
418 var notes []string
419 at, insert, touched := 0, false, 0
420 for _, line := range pageLines(out) {
421 switch {
422 case strings.HasPrefix(line, "@@ "):
423 rest := strings.TrimPrefix(line, "@@ -") // 12,0 +13,2 @@
424 at = leadingNumber(rest)
425 rest = strings.TrimLeft(rest, "0123456789")
426 old := 1
427 if strings.HasPrefix(rest, ",") {
428 old = leadingNumber(rest[1:])
429 }
430 insert = old == 0
431 if !insert {
432 touched += old
433 }
434 case strings.HasPrefix(line, "+"):
435 // Only inside an insertion hunk: the +++ of git's own header is
436 // not a note, and neither is the new side of an edit.
437 if !insert {
438 continue
439 }
440 text := strings.TrimLeft(line[1:], " \t\n\v\f\r")
441 if text == "" { // a blank line says nothing
442 continue
443 }
444 notes = append(notes, anchorOf(all, at)+": "+text)
445 }
446 }
447 if touched != 0 {
448 fmt.Fprintf(r.stderr, "valley: warning: %d changed or deleted diff line(s) ignored — a note is a line you insert\n", touched)
449 }
450 return notes
451}
452
453// notesFile is where the notes taken under key live.
454func notesFile(key string) string {
455 state := os.Getenv("XDG_STATE_HOME")
456 if state == "" {
457 state = os.Getenv("HOME") + "/.local/state"
458 }
459 return state + "/valley/notes/" + key + ".md"
460}
461
462// collectNotes reads the notes out of the paged page and keeps them:
463// appended to the notes file under key, under the commit they were taken
464// against, and held for the print that follows the verdict. A notes file
465// that cannot be written is a warning, never a failure: the notes are
466// still printed, and a review is not undone by a missing directory.
467func (r *review) collectNotes(key, sha, orig, edited string) {
468 found := r.notesIn(orig, edited)
469 if len(found) == 0 {
470 return
471 }
472 r.notes = append(r.notes, found...)
473 file := notesFile(key)
474 text := fmt.Sprintf("## %s at %s\n\n%s\n\n", key, sha, strings.Join(found, "\n"))
475 if os.MkdirAll(filepath.Dir(file), 0o777) == nil {
476 if f, err := os.OpenFile(file, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o666); err == nil {
477 _, err = f.WriteString(text)
478 if f.Close() == nil && err == nil {
479 return
480 }
481 }
482 }
483 fmt.Fprintf(r.stderr, "valley: warning: could not write %s — the notes are printed only\n", file)
484}
485
486// printNotes prints the notes taken under key, after the verdict.
487func (r *review) printNotes(key string, notes []string) {
488 if len(notes) == 0 {
489 return
490 }
491 fmt.Fprintf(r.stdout, "\n%d note(s) on %s, appended to %s:\n", len(notes), key, notesFile(key))
492 for _, n := range notes {
493 fmt.Fprintf(r.stdout, " %s\n", n)
494 }
495}
496
497// readDoes reads the plan graph once for every change in the review, for
498// the knots each does, and starts reading their checks. A missing or
499// unreadable graph shows no knots; -v warns on stderr.
500func (r *review) readDoes() {
501 var ids []string
502 if len(r.layers) > 1 {
503 for _, l := range r.layers {
504 if l.id != "" {
505 ids = append(ids, l.id)
506 }
507 }
508 } else if r.c.id != "" {
509 ids = []string{r.c.id}
510 }
511 if len(ids) == 0 {
512 return
513 }
514 r.does = readDoers(r.g, project(r.g), r.verbose, r.stderr)
515 r.startChecksRead(&checksRead{ids: ids, verbose: r.verbose})
516}
517
518// doesOf is the `does ...` lines of one change.
519func (r *review) doesOf(id string) string {
520 if id == "" {
521 return ""
522 }
523 var lines []string
524 for _, k := range r.does[id] {
525 lines = append(lines, k.line())
526 }
527 return strings.Join(lines, "\n")
528}
529
530// checksRead is the read of the changes' checks lines, which takes
531// seconds: it reads the policy and the host's telemetry. It runs this
532// program's checkline (versionchecks.go) in the background, in a process
533// group of its own, so that a Ctrl-C the operator gives the pager does not
534// reach it, while the page is shown, and the line is printed just before
535// the prompt when the read has finished. It never waits for the read,
536// unless VALLEY_REVIEW_CHECKS_WAIT gives the seconds to wait for it.
537type checksRead struct {
538 ids []string
539 verbose bool // pass on what the read said on stderr
540 cmd *exec.Cmd
541 out, err bytes.Buffer
542 done chan struct{}
543 shown map[string]bool // the changes whose line is not shown again
544}
545
546// startChecksRead starts the read c names, in place of any read started.
547func (r *review) startChecksRead(c *checksRead) {
548 r.mu.Lock()
549 old := r.checks
550 r.checks = nil
551 r.mu.Unlock()
552 old.stop()
553 c = &checksRead{ids: c.ids, verbose: c.verbose, done: make(chan struct{}), shown: map[string]bool{}}
554 exe, err := os.Executable()
555 if err != nil {
556 close(c.done)
557 } else {
558 c.cmd = exec.Command(exe, append([]string{"checkline"}, c.ids...)...)
559 c.cmd.Stdout, c.cmd.Stderr = &c.out, &c.err
560 c.cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
561 processStarted()
562 if c.cmd.Start() != nil {
563 c.cmd = nil
564 close(c.done)
565 } else {
566 go func() {
567 _ = c.cmd.Wait()
568 close(c.done)
569 }()
570 }
571 }
572 r.mu.Lock()
573 exiting := r.exiting
574 if !exiting {
575 r.checks = c
576 }
577 r.mu.Unlock()
578 if exiting {
579 c.stop()
580 }
581}
582
583// restartChecksRead reads the checks again, as for heads that moved, when
584// a read was started.
585func (r *review) restartChecksRead() {
586 r.mu.Lock()
587 c := r.checks
588 r.mu.Unlock()
589 if c != nil {
590 r.startChecksRead(c)
591 }
592}
593
594// stop stops the read, if it still runs, with everything it started.
595func (c *checksRead) stop() {
596 if c == nil || c.cmd == nil {
597 return
598 }
599 select {
600 case <-c.done:
601 default:
602 _ = syscall.Kill(-c.cmd.Process.Pid, syscall.SIGTERM)
603 }
604}
605
606// checksLine is the `checks: …` line of one change, if the read has
607// finished and gave it one, or "". mark says it is not shown again.
608func (r *review) checksLine(id string, mark bool) string {
609 r.mu.Lock()
610 c := r.checks
611 r.mu.Unlock()
612 if c == nil || id == "" || c.shown[id] {
613 return ""
614 }
615 // Normally the read has had the whole time the page was read in. A host
616 // that wants the line at the prompt can have review wait for it.
617 wait := os.Getenv("VALLEY_REVIEW_CHECKS_WAIT")
618 seconds, err := strconv.Atoi(wait)
619 if err != nil || strings.Trim(wait, "0123456789") != "" {
620 seconds = 0
621 }
622 select {
623 case <-c.done:
624 default:
625 select {
626 case <-c.done:
627 case <-time.After(time.Duration(seconds) * time.Second):
628 return ""
629 }
630 }
631 if c.verbose && c.err.Len() > 0 {
632 r.stderr.Write(c.err.Bytes())
633 c.err.Reset()
634 }
635 var found []string
636 for _, line := range pageLines(c.out.Bytes()) {
637 if changeID, text, _ := strings.Cut(line, "\t"); changeID == id {
638 found = append(found, text)
639 if mark {
640 c.shown[id] = true
641 }
642 }
643 }
644 return strings.Join(found, "\n")
645}