gunk-dev/the-valley

review.go

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