gunk-dev/the-valley

review.go

source78684ec35c8emain's published tip history
27.5 KiB
1package main
2
3// valley review: a change, or a stack layer by layer, paged for the
4// operator to approve, reject or skip. With no change it walks what needs
5// the operator (walk.go), and each step of the walk runs this verb again,
6// for one change, through the valley command. bin/valley hands the verb
7// to this program.
8//
9// A change is resolved before origin is fetched, as approve resolves it,
10// and shown at the head its record names, or a plain branch at its tip on
11// origin. A stack is read first (stack.go), and reviewed one layer at a
12// time (reviewstack.go). Each page is set against the change's approved
13// version (compare.go), paged through the configured diff pager into
14// less, and read back for notes (reviewpage.go). The prompt is verdict.go's.
15// [a]pprove is approve's attempt (approve.go), [b]ase onto main is the
16// rebase verb's (rebase.go), and before either acts, and before
17// [r]eject, the change is read again (standing.go, carry.go).
18//
19// A review that is a walk's step is told what the walker's queue held of
20// the change, in VALLEY_WALK_QUEUED, and writes how it ended to the file
21// VALLEY_WALK_OUTCOME names, as walk.go's header gives.
22//
23// SIGINT and SIGTERM end the review with status 130, its outcome
24// interrupted. One that arrives while a program it runs in the foreground
25// has the terminal, such as less or the editor less starts, ends it once
26// that program has ended: less takes Ctrl-C itself. During [a]pprove's
27// attempt, SIGINT is the attempt's to act on: it stops the checks, and the
28// attempt ends the review through exitWith. SIGHUP ends the review at
29// once, with status 129. However it ends, the review leaves nothing of its
30// own behind: its pages, the background read of the checks, and the
31// published known-signers file the reads wrote out.
32
33import (
34 "bytes"
35 "fmt"
36 "io"
37 "os"
38 "os/exec"
39 "os/signal"
40 "strconv"
41 "strings"
42 "sync"
43 "syscall"
44)
45
46const reviewUsage = "usage: valley review [-v] [--build-here] [<change> | --repo <name>]"
47
48// shownChange is the change review acts on: the one it was given, or a
49// layer of its stack (useLayer). For a change with a record, id, handle,
50// version, head, state and owner are its record's, with head the active
51// version's. A plain branch has a name and a branch alone.
52type shownChange struct {
53 name, id, handle, version, head, branch, state, owner string
54}
55
56// review is one review of a change and the stack under it.
57type review struct {
58 g git
59 stdout, stderr io.Writer
60 verbose, buildHere bool
61
62 c shownChange
63 approveHead, approveVersion string // what [a]pprove files (bind)
64 carried bool // the answer carried to the version the change moved to
65 checksFailedAt string // the head [a]pprove's checks failed at
66 checksClause string // the checks line for the prompt's header
67 topName string // the name review was given
68 layers []reviewLayer
69 notes []string // taken in the pages since the last layer began
70 does doers
71 checks *checksRead
72
73 walkQueued, walkFile string
74 walkWritten, walkRefused bool
75
76 exitProcess func(int) // main's exitWith
77 mu sync.Mutex
78 scratch string // the directory holding the page being shown
79 armed bool // whether an exit says how the review ended
80 exiting bool
81 foreground int // programs the review waits on with signals held
82 pending bool // a signal held until they end
83}
84
85func runReview(g git, args []string, stdout, stderr io.Writer) int {
86 var name, repo string
87 var verbose, buildHere, repoGiven bool
88 for i := 0; i < len(args); i++ {
89 switch a := args[i]; {
90 case a == "-v":
91 verbose = true
92 case a == "--build-here":
93 buildHere = true
94 case a == "--repo":
95 if i+1 >= len(args) {
96 fmt.Fprintf(stderr, "valley: %s\n", reviewUsage)
97 return 1
98 }
99 repo, repoGiven = args[i+1], true
100 i++
101 case strings.HasPrefix(a, "-") || name != "":
102 fmt.Fprintf(stderr, "valley: %s\n", reviewUsage)
103 return 1
104 default:
105 name = a
106 }
107 }
108 if name == "" {
109 var walk []string
110 if verbose {
111 walk = append(walk, "-v")
112 }
113 if buildHere {
114 walk = append(walk, "--build-here")
115 }
116 if repoGiven {
117 walk = append(walk, "--repo", repo)
118 }
119 if err := fetchOrigin(g, stdout, stderr); err != nil {
120 return exitCode(err)
121 }
122 return runWalk(g, walk, stdout, stderr)
123 }
124 if repoGiven {
125 fmt.Fprintf(stderr, "valley: %s\n", reviewUsage)
126 return 1
127 }
128 os.Unsetenv("VALLEY_COMMAND")
129 commandTimed = false
130 r := &review{g: g, stdout: stdout, stderr: stderr, verbose: verbose, buildHere: buildHere,
131 walkQueued: os.Getenv("VALLEY_WALK_QUEUED"), walkFile: os.Getenv("VALLEY_WALK_OUTCOME"),
132 exitProcess: exitWith}
133 os.Unsetenv("VALLEY_WALK_QUEUED")
134 os.Unsetenv("VALLEY_WALK_OUTCOME")
135 exitWith = r.exit
136 r.listen()
137 return r.finish(r.run(name))
138}
139
140// run is the review of the change named, and its exit status.
141func (r *review) run(name string) int {
142 if err := r.resolve(name); err != nil {
143 fmt.Fprintf(r.stderr, "valley: %s\n", err)
144 return 1
145 }
146 if err := fetchOrigin(r.g, r.stdout, r.stderr); err != nil {
147 return exitCode(err)
148 }
149 if !r.queued() {
150 return 0
151 }
152 // Notes are kept under the branch, and [r]eject deletes it. approve
153 // files the head alone, so it approves such a change.
154 if r.c.id != "" && r.c.branch == "" {
155 fmt.Fprintf(r.stderr, "valley: change %s v%s records no branch, and review acts on a change's branch. Approve its head alone: valley approve --head %s %s\n",
156 r.c.handle, r.c.version, r.c.head, r.c.handle)
157 return 1
158 }
159 branch := r.c.branch
160 r.topName = name
161 if r.ref("refs/remotes/origin/"+branch) == "" {
162 fmt.Fprintf(r.stderr, "valley: no such branch on origin: %s\n", branch)
163 return 1
164 }
165 r.bind()
166 r.mu.Lock()
167 r.armed = true
168 r.mu.Unlock()
169 // The verdict disposes of the change; the notes are what the human made
170 // of it, so they are printed whatever the verdict was. A stack that
171 // cannot be read is reviewed whole against main, as a change with
172 // nothing under it is.
173 if !r.readStack() {
174 fmt.Fprintf(r.stderr, "valley: warning: the stack under %s could not be read; reviewing it whole, against main\n", name)
175 r.layers = nil
176 }
177 r.readDoes()
178 if len(r.layers) > 1 {
179 r.reviewStack()
180 r.printStackNotes()
181 } else {
182 r.showReview(branch)
183 r.decide(branch, "", 0)
184 r.printNotes(branch, r.notes)
185 }
186 return 0
187}
188
189// fetchOrigin brings this checkout's remote-tracking refs up to date.
190func fetchOrigin(g git, stdout, stderr io.Writer) error {
191 fetch := exec.Command("git", "fetch", "--prune", "--quiet", "origin")
192 fetch.Env, fetch.Stdout, fetch.Stderr = g.env, stdout, stderr
193 processStarted()
194 return fetch.Run()
195}
196
197// listen takes SIGINT, SIGTERM and SIGHUP for the rest of the review.
198func (r *review) listen() {
199 c := make(chan os.Signal, 1)
200 signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
201 go func() {
202 for s := range c {
203 if s == syscall.SIGHUP {
204 r.exit(128 + int(syscall.SIGHUP))
205 }
206 r.mu.Lock()
207 held := r.foreground > 0
208 r.pending = r.pending || held
209 r.mu.Unlock()
210 if !held {
211 r.exit(interruptedStatus)
212 }
213 }
214 }()
215}
216
217// inForeground runs f, which runs a program that has the terminal or
218// handles signals itself, holding any signal until it returns.
219func (r *review) inForeground(f func()) {
220 r.mu.Lock()
221 r.foreground++
222 r.mu.Unlock()
223 f()
224 r.mu.Lock()
225 r.foreground--
226 act := r.foreground == 0 && r.pending
227 r.mu.Unlock()
228 if act {
229 r.exit(interruptedStatus)
230 }
231}
232
233// cleanup says how the review ended, when nothing has yet, and removes
234// what it leaves outside the repository. Only the first call acts: it
235// reports false to any other, whose caller leaves the process to the
236// first.
237func (r *review) cleanup(status int) bool {
238 r.mu.Lock()
239 if r.exiting {
240 r.mu.Unlock()
241 return false
242 }
243 r.exiting = true
244 unsaid := r.armed && !r.walkWritten
245 scratch, checks := r.scratch, r.checks
246 r.scratch, r.checks = "", nil
247 r.mu.Unlock()
248 if unsaid {
249 if status == interruptedStatus {
250 r.writeOutcome("interrupted")
251 } else {
252 r.writeOutcome("error")
253 }
254 }
255 if scratch != "" {
256 os.RemoveAll(scratch)
257 }
258 checks.stop()
259 verification.done()
260 return true
261}
262
263// finish ends a review that ran to its end, with status.
264func (r *review) finish(status int) int {
265 if !r.cleanup(status) {
266 select {} // the exit under way ends the process
267 }
268 return status
269}
270
271// exit ends the review and the process from anywhere, with status.
272func (r *review) exit(status int) {
273 if !r.cleanup(status) {
274 select {}
275 }
276 r.exitProcess(status)
277}
278
279// die ends the review: nothing is left to offer.
280func (r *review) die(msg string) {
281 fmt.Fprintf(r.stderr, "valley: %s\n", msg)
282 r.exit(1)
283}
284
285// refuse reports what was not done, without leaving the review: the
286// change is still under review and the operator can still answer. It
287// returns false.
288func (r *review) refuse(msg string) bool {
289 fmt.Fprintf(r.stderr, "valley: %s\n", msg)
290 return false
291}
292
293// newScratch makes the directory the next page is written to.
294func (r *review) newScratch() string {
295 dir, err := os.MkdirTemp("", "valley-review-")
296 if err != nil {
297 r.die(fmt.Sprintf("no scratch directory for the review: %v", err))
298 }
299 r.mu.Lock()
300 if r.exiting {
301 r.mu.Unlock()
302 os.RemoveAll(dir)
303 select {}
304 }
305 r.scratch = dir
306 r.mu.Unlock()
307 return dir
308}
309
310// dropScratch removes the page's directory.
311func (r *review) dropScratch() {
312 r.mu.Lock()
313 dir := r.scratch
314 r.scratch = ""
315 r.mu.Unlock()
316 if dir != "" {
317 os.RemoveAll(dir)
318 }
319}
320
321// writeOutcome writes how a walk's step ended, as one line of
322// tab-separated fields for the walker. The last one written stands.
323func (r *review) writeOutcome(fields ...string) {
324 if r.walkFile == "" {
325 return
326 }
327 if err := os.WriteFile(r.walkFile, []byte(strings.Join(fields, "\t")+"\n"), 0o666); err != nil {
328 fmt.Fprintf(r.stderr, "valley: %v\n", err)
329 return
330 }
331 r.mu.Lock()
332 r.walkWritten = true
333 r.mu.Unlock()
334}
335
336// outcome writes how the step ended, unless the review is already exiting
337// and says so itself.
338func (r *review) outcome(fields ...string) {
339 r.mu.Lock()
340 exiting := r.exiting
341 r.mu.Unlock()
342 if !exiting {
343 r.writeOutcome(fields...)
344 }
345}
346
347// skipped is the outcome of a step whose review was skipped or stopped:
348// refused when an answer was refused first.
349func (r *review) skipped() {
350 if r.walkRefused {
351 r.outcome("refused")
352 } else {
353 r.outcome("skipped")
354 }
355}
356
357// queued compares a walk's step with what the walker's queue held of it.
358// A change that landed, is no longer ready or has no branch on origin is
359// not reviewed, and the step ends; one at another version is reviewed at
360// it, saying so first. It reports false when the step ends here.
361func (r *review) queued() bool {
362 if r.walkQueued == "" {
363 return true
364 }
365 s, _ := r.readStanding()
366 why := ""
367 switch {
368 case s.landed != "":
369 why = "it landed as " + s.landed
370 case r.c.state != "ready":
371 why = "it is " + strings.Replace(r.c.state, "draft", "a draft", 1)
372 case r.c.branch == "" || r.ref("refs/remotes/origin/"+r.c.branch) == "":
373 why = "its branch is gone from origin"
374 }
375 if why != "" {
376 fmt.Fprintf(r.stdout, "%s is not reviewed: %s\n", r.c.handle, why)
377 r.outcome("not-reviewed", why)
378 return false
379 }
380 if strings.Join(strings.Fields(r.walkQueued), " ") != r.c.id+" "+r.c.version+" "+r.c.head {
381 fmt.Fprintf(r.stdout, "%s moved to v%s since the queue was read\n", r.c.handle, r.c.version)
382 }
383 return true
384}
385
386// resolve reads the name as approve and rebase read a change's name: a
387// change's ID, handle, or the branch its active version names, or else a
388// plain branch.
389func (r *review) resolve(name string) error {
390 r.c = shownChange{name: name}
391 if !r.g.succeeds(true, "rev-parse", "--git-dir") {
392 return failure("not a git repository")
393 }
394 res, err := resolveRecorded(r.g, name)
395 if err != nil {
396 return err
397 }
398 r.c.branch = res.branch
399 if res.id != "" {
400 r.c.id, r.c.handle, r.c.version, r.c.head = res.id, res.handle, strconv.Itoa(res.version), res.head
401 r.c.state, r.c.owner = res.state, res.owner
402 }
403 return nil
404}
405
406// ref is the object ID a ref holds, read by its exact name, or "".
407func (r *review) ref(name string) string {
408 oid, ok, err := r.g.ref(name)
409 if err != nil || !ok {
410 return ""
411 }
412 return oid
413}
414
415func (r *review) short(oid string) string {
416 s, _ := r.g.output(false, "rev-parse", "--short", oid)
417 return s
418}
419
420// changeHead is the commit review acts on: the recorded head for a change
421// with a record, and otherwise the branch's head on origin.
422func (r *review) changeHead(branch string) string {
423 if r.c.head != "" {
424 return r.c.head
425 }
426 return r.ref("refs/remotes/origin/" + branch)
427}
428
429// fastForwards reports whether commit fast-forwards from main's tip as the
430// fetch left it. A main that cannot be read is not one it fast-forwards
431// from.
432func (r *review) fastForwards(commit string) bool {
433 tip := r.ref("refs/remotes/origin/main")
434 return tip != "" && r.g.succeeds(false, "merge-base", "--is-ancestor", tip, commit)
435}
436
437// bind binds [a]pprove to the active version's head of a change with a
438// record. A plain branch is bound to the head review pages, when it pages
439// it (showReview, useLayer).
440func (r *review) bind() {
441 r.approveHead, r.approveVersion = "", ""
442 if r.c.id != "" {
443 r.approveHead, r.approveVersion = r.c.head, r.c.version
444 }
445}
446
447// readStanding reads where the change under review stands now. A plain
448// branch has no record, and reads as nothing. It reports false, having
449// said why, when origin cannot be read.
450func (r *review) readStanding() (standing, bool) {
451 if r.c.id == "" {
452 return standing{}, true
453 }
454 s, err := standingOf(r.g, r.c.id)
455 if err != nil {
456 fmt.Fprintf(r.stderr, "valley: %s\n", err)
457 return standing{}, false
458 }
459 return s, true
460}
461
462// notReady is the line review shows for a change whose record is not
463// ready, above its diff and in its prompt, or "" for a ready change and a
464// plain branch. A draft is often a change an agent is still working on,
465// so the prompt then offers only [v]iew diff and [s]kip: [a]pprove would
466// be refused, and [r]eject records nothing on the change, but deletes the
467// branch its owner may still be working on.
468func notReady(handle, version, state, owner string) string {
469 switch state {
470 case "draft":
471 return fmt.Sprintf("%s v%s is a draft: its owner (%s) hasn't marked it ready, so it can't be approved yet.", handle, version, owner)
472 case "withdrawn":
473 return handle + " is withdrawn: there is nothing to approve."
474 }
475 return ""
476}
477
478// answer reads one answer from the terminal, a byte at a time so that
479// nothing after it is taken from whatever reads the input next, with the
480// spaces and tabs around it trimmed. ok is false when the input ends
481// before the line does.
482func answer() (string, bool) {
483 var line []byte
484 b := make([]byte, 1)
485 for {
486 n, err := os.Stdin.Read(b)
487 if n == 1 {
488 if b[0] == '\n' {
489 return strings.Trim(string(line), " \t"), true
490 }
491 line = append(line, b[0])
492 }
493 if err != nil {
494 return "", false
495 }
496 }
497}
498
499// mustAnswer is answer, ending the review when the input has ended.
500func (r *review) mustAnswer() string {
501 choice, ok := answer()
502 if !ok {
503 r.die("stdin closed before an answer; nothing done")
504 }
505 return choice
506}
507
508// prompt prints review's prompt: the header's clauses, the empty ones
509// left out, and the keys.
510func (r *review) prompt(header []string, keys ...string) {
511 var shown []string
512 for _, h := range header {
513 if h != "" {
514 shown = append(shown, h)
515 }
516 }
517 fmt.Fprint(r.stdout, promptLines(terminalOf(r.stdout), shown, keys))
518}
519
520// decide takes the verdict on a change alone, and on the top of a stack
521// of n, named name. Its prompt is one header line, the change and what
522// stands in its way, and the keys it takes. A change is named by its
523// handle and version, a plain branch by its name, and a change alone
524// carries the checks line review read for it. The top of a stack says that
525// approving it lands all n layers. [v]iew diff pages the change's whole
526// diff, or the top layer's.
527//
528// A change that is not ready says so in its header, and is offered only
529// [v]iew diff and [s]kip, or [s]top. The top of a stack with a layer under
530// it that is not ready says why it can't be approved (layerHeld), as does
531// a change whose checks failed at the head shown, and neither is offered
532// [a]pprove. A change that can be approved and does not fast-forward from
533// main says so (behindMain). Before [a]pprove and [r]eject act, moved
534// reads the change again, and ends its review when it moved.
535func (r *review) decide(branch, name string, n int) {
536 approve, reject, stop := "[a]pprove", "[r]eject", "[s]kip"
537 stopped := "skipped " + branch + "; nothing done"
538 header := []string{branch}
539 own, held, behind := "", "", ""
540 if r.c.id != "" {
541 header = []string{r.c.handle + " v" + r.c.version}
542 switch r.c.state {
543 case "draft":
544 own = "draft (its owner, " + r.c.owner + ", has not readied it)"
545 case "withdrawn":
546 own = "withdrawn"
547 }
548 }
549 if n > 0 {
550 header = append(header, fmt.Sprintf("stack of %d", n))
551 approve, reject, stop = fmt.Sprintf("[a]pprove all %d", n), "[r]eject "+name, "[s]top"
552 stopped = fmt.Sprintf("stopped reviewing %s at change %d of %d; nothing done", name, n, n)
553 held = r.layerHeld(n - 1)
554 } else if r.checksClause != "" {
555 header = append(header, r.checksClause)
556 }
557 if own == "" && held == "" {
558 behind = r.behindMain(branch)
559 }
560 for {
561 var clause, answers string
562 var keys []string
563 failed := ""
564 switch {
565 case own != "":
566 clause, keys, answers = own, []string{"[v]iew diff", stop}, "v or s"
567 case held != "":
568 clause, keys, answers = held, []string{"[v]iew diff", reject, stop}, "v, r, or s"
569 default:
570 if failed = r.approveFailedAt(branch); failed != "" {
571 clause, keys, answers = "checks failed at "+failed, []string{"[v]iew diff", reject, stop}, "v, r, or s"
572 } else {
573 clause, keys, answers = behind, []string{approve, "[v]iew diff", reject, stop}, "a, v, r, or s"
574 }
575 }
576 r.prompt(append(append([]string{}, header...), clause), keys...)
577 // A refusal from approve is not a verdict: it says what it did not
578 // do and the prompt comes back, so the branch can still be rejected
579 // or skipped. When the checks failed, approving the same head again
580 // is no longer offered, nor is approving a change that is not ready.
581 // A change that moved since it was shown is not acted on, and its
582 // review ends.
583 switch r.mustAnswer() {
584 case "a":
585 if failed != "" || own != "" || held != "" {
586 fmt.Fprintln(r.stdout, "answer "+answers)
587 } else if r.moved(true) || r.approve(branch) {
588 return
589 }
590 case "v":
591 if n > 0 {
592 r.viewLayer(n - 1)
593 } else {
594 r.viewFull(branch)
595 }
596 case "r":
597 if own != "" {
598 fmt.Fprintln(r.stdout, "answer "+answers)
599 } else if r.moved(false) || r.reject(branch) {
600 return
601 }
602 case "s":
603 fmt.Fprintln(r.stdout, stopped)
604 r.skipped()
605 return
606 default:
607 fmt.Fprintln(r.stdout, "answer "+answers)
608 }
609 }
610}
611
612// approveFailedAt is the head the checks failed at in this review, short,
613// while the change is still at it, or "". Approving that head again would
614// run the same checks over the same tree and fail the same way, so the
615// prompt stops offering [a]pprove until the change has a new head.
616func (r *review) approveFailedAt(branch string) string {
617 if r.checksFailedAt == "" || r.checksFailedAt != r.changeHead(branch) {
618 return ""
619 }
620 return r.short(r.checksFailedAt)
621}
622
623// behindMain is the clause review's prompt shows for a change that does
624// not fast-forward from main, or "". Being behind main asks nothing of the
625// operator: the integrator applies the change's delta onto main as main
626// stands, with the evidence for the head approved, and the host's
627// restacker rebases ready changes itself. When the restacker reports that
628// rebasing the change conflicted, the clause says so instead, and
629// [a]pprove stays offered: the integrator decides whether the change
630// applies.
631func (r *review) behindMain(branch string) string {
632 if r.fastForwards(r.changeHead(branch)) {
633 return ""
634 }
635 if s, _ := r.readStanding(); s.conflict == "conflict" {
636 return "conflicts with main (owner resolving)"
637 }
638 return "behind main (integrator merges)"
639}
640
641// moved reads a change with a record again before review acts on an
642// answer about it: another principal may return it to draft, ready a new
643// version, or withdraw it while the operator reads, and it may land. When
644// it is no longer what review showed, moved says in one line what changed
645// and what happens next, and the review of that change ends: the prompt's
646// answers were about what was shown, so it is not asked again. A new
647// version the answer carries to does not end it (carried), nor does
648// approving the new version in place, which moved offers for an approval.
649// It reports false when the change is still as shown, the answer carries
650// or the new version is to be approved, and for a plain branch, which
651// approve and reject check themselves.
652func (r *review) moved(approving bool) bool {
653 h := r.c.handle
654 r.carried = false
655 if r.c.id == "" {
656 return false
657 }
658 s, ok := r.readStanding()
659 switch {
660 case !ok:
661 fmt.Fprintf(r.stdout, "could not read %s again from origin; nothing done\n", h)
662 r.outcome("error")
663 return true
664 case s.state == "withdrawn":
665 fmt.Fprintf(r.stdout, "%s changed while you were reviewing: it was withdrawn (since %s), so there is nothing to approve.\n", h, s.since)
666 case s.state == "draft":
667 fmt.Fprintf(r.stdout, "%s changed while you were reviewing: it was returned to draft (since %s), so there is nothing to approve now. It comes back when it is ready again.\n", h, s.since)
668 case s.landed != "":
669 fmt.Fprintf(r.stdout, "%s landed as %s while you were reviewing; there is nothing left to approve.\n", h, s.landed)
670 case s.version == r.c.version && s.head == r.c.head:
671 return false
672 default:
673 if r.carriedTo(s, approving) {
674 return false
675 }
676 }
677 r.outcome("moved")
678 return true
679}
680
681// carriedTo reports whether the answer about the version review showed
682// carries to the version s the change moved to, as carry decides
683// (carry.go). When it does, it says so in one line, and the answer stays
684// bound to the head shown: an approval names what the reviewer read, and
685// the integrator applies its delta onto main as main stands. When it does
686// not, it says why in one line and offers to page only what changed since
687// the version shown. Answering an approval, it also offers to approve the
688// version the change moved to, when carry says: at once, or after the
689// page. [a] binds the approval to that version's head, and the attempt
690// reads the record again before it files. It reports false unless the
691// answer carries or [a] is taken.
692func (r *review) carriedTo(s standing, approving bool) bool {
693 h := r.c.handle
694 r.bind()
695 dir := r.newScratch()
696 defer r.dropScratch()
697 var out bytes.Buffer
698 verdict, reason, offer, text := "", "", "", ""
699 if err := runCarry(r.g, []string{r.c.id, r.c.version, s.version}, &out); err != nil {
700 fmt.Fprintf(r.stderr, "valley: %s\n", err)
701 } else {
702 first, rest, _ := strings.Cut(out.String(), "\n")
703 f := strings.Fields(first)
704 if len(f) > 0 {
705 verdict = f[0]
706 }
707 if t := strings.Split(first, "\t"); len(t) > 1 {
708 reason = t[1]
709 if len(t) > 2 {
710 offer = t[2]
711 }
712 }
713 text = rest
714 }
715 if !approving {
716 offer = "none"
717 }
718 switch verdict {
719 case "carries":
720 fmt.Fprintf(r.stdout, "%s moved to v%s while you were reviewing (%s) · your answer about v%s stands\n", h, s.version, reason, r.c.version)
721 r.carried = true
722 return true
723 case "review":
724 keys := "[v]iew what changed since v" + r.c.version + ", [s]kip?"
725 switch offer {
726 case "approve":
727 keys = "[a]pprove v" + s.version + ", " + keys
728 case "view":
729 default:
730 offer, keys = "", "review it again to approve it · "+keys
731 }
732 fmt.Fprintf(r.stdout, "%s moved to v%s while you were reviewing (%s) · %s ", h, s.version, reason, keys)
733 choice, _ := answer()
734 if choice == "v" {
735 changed := dir + "/changed"
736 if err := os.WriteFile(changed, []byte(text), 0o600); err == nil {
737 r.page(changed)
738 }
739 if offer != "" {
740 offer = "approve"
741 fmt.Fprintf(r.stdout, "[a]pprove v%s, [s]kip? ", s.version)
742 choice, _ = answer()
743 }
744 }
745 if choice == "a" && offer == "approve" {
746 r.approveVersion, r.approveHead = s.version, s.head
747 return true
748 }
749 default:
750 fmt.Fprintf(r.stdout, "%s moved to v%s while you were reviewing; review it again to approve what would land.\n", h, s.version)
751 }
752 return false
753}
754
755// approve is review's [a]pprove: one attempt of approve's own for each
756// answer, a stack's layers included (approve.go), told the change and head
757// review bound and the name as typed, which it reads again before filing.
758// It ends approved, with what it filed; checks-failed, with the head the
759// checks failed at, which the prompt stops offering [a]pprove for
760// (approveFailedAt); refused or unknown; or interrupted, when the attempt
761// has ended the review itself. It reports false unless it filed.
762func (r *review) approve(branch string) bool {
763 c := r.c
764 if c.id == "" {
765 c.branch = branch
766 }
767 a := reviewApproval(r.g, r.stdout, r.stderr, c, r.approveHead, r.approveVersion, r.verbose, r.buildHere, r.carried)
768 r.inForeground(func() {
769 a.watch(os.Interrupt)
770 a.run()
771 a.unwatch()
772 })
773 result := a.result
774 switch {
775 case len(result) == 5 && result[0] == "approved":
776 r.outcome(result...)
777 return true
778 case len(result) == 2 && result[0] == "checks-failed":
779 r.checksFailedAt = result[1]
780 case len(result) == 1 && (result[0] == "refused" || result[0] == "unknown"):
781 default:
782 fmt.Fprintln(r.stderr, "valley: warning: the approval left no outcome; taking it as refused")
783 }
784 r.walkRefused = true
785 return false
786}
787
788// reject deletes the change's branch on origin, once the operator confirms
789// it. For a change with a record, what is rejected is the head its record
790// names, so the branch is deleted only while its tip is that head, and
791// the delete is leased on it. When the tip is another commit, reject
792// refuses and names both, and deletes nothing. A plain branch is deleted
793// as it stands. It reports false when it refused.
794func (r *review) reject(branch string) bool {
795 var lease []string
796 if r.c.head != "" {
797 if !r.recordedTip(branch, "nothing deleted") {
798 r.walkRefused = true
799 return false
800 }
801 lease = []string{"--force-with-lease=refs/heads/" + branch + ":" + r.c.head}
802 }
803 fmt.Fprintf(r.stdout, "really delete origin/%s? [y/N] ", branch)
804 switch choice, _ := answer(); choice {
805 case "y", "Y", "yes":
806 // The change may have moved while the confirmation waited: say so,
807 // and delete nothing.
808 if r.moved(false) {
809 return true
810 }
811 push := exec.Command("git", append(append([]string{"push", "--quiet"}, lease...), "origin", "--delete", branch)...)
812 push.Env, push.Stdout, push.Stderr = r.g.env, r.stdout, r.stderr
813 var err error
814 r.inForeground(func() { err = push.Run() })
815 if err != nil {
816 r.refuse("origin did not delete " + branch + ", which may have moved since the fetch; nothing deleted")
817 r.walkRefused = true
818 return false
819 }
820 fmt.Fprintf(r.stdout, "rejected %s: deleted from origin\n", branch)
821 r.outcome("rejected", branch)
822 default:
823 fmt.Fprintf(r.stdout, "kept %s\n", branch)
824 r.outcome("kept", branch)
825 }
826 return true
827}
828
829// recordedTip reports whether the branch's tip on origin is the head a
830// change's record names, and refuses, naming both, when it is not:
831// [r]eject acts on the branch itself, and deleting it while it is
832// elsewhere would delete a commit no version records. undone is what the
833// refusal leaves undone.
834func (r *review) recordedTip(branch, undone string) bool {
835 tip := r.ref("refs/remotes/origin/" + branch)
836 switch {
837 case tip == "":
838 return r.refuse("no such branch on origin: " + branch + "; " + undone)
839 case tip != r.c.head:
840 return r.refuse(fmt.Sprintf("change %s v%s records the head %s, and origin/%s is at %s; %s. Ready the branch's head as a new version of %s to act on it",
841 r.c.handle, r.c.version, r.c.head, branch, tip, undone, r.c.handle))
842 }
843 return true
844}