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