gunk-dev/the-valley

compare.go

sourcea0911fc82b8emain's published tip history
20.7 KiB
1// valley-go compare: a version under review, set against the version of
2// its change the operator last approved. review runs it for each change it
3// shows, a stack's layers included, and prints what it says (bin/valley).
4// It is information only: it files no request and skips no check.
5//
6// The approved version is the greatest version below the one shown whose
7// exact head is named by either of these:
8//
9// - an integration request on origin for the change: one filed under
10// c-<change ID>, or under the request name of one of the change's
11// versions' branches, unless that name is c-<ID> for some change ID;
12// - an outcome record on origin under one of those names that says land,
13// stale or reject at that head. The integrator judges only requests
14// that were filed, so each of those is an approval it judged.
15//
16// A branch's request name is lossy, since a/b and a-b are both a-b. So a
17// branch named c/<ID> or c-<ID> maps to c-<ID>, which is reserved for the
18// change with that ID, and is never read as this change's. Another name
19// is ambiguous when anything other than this change maps to it: a branch
20// any version of another change names, or a branch on origin that is no
21// branch of this change. A name is ambiguous too when a record on origin
22// does not read, since that record could name such a branch. A request or
23// outcome under an ambiguous name is no evidence of approval. When the
24// greatest version with any evidence has only ambiguous evidence, which
25// version was approved is not known, and there is no comparison. An older
26// version is never searched for instead. Neither is one whose delta
27// happens to match.
28//
29// The comparison freezes main's tip T, which review passes, and the two
30// heads: H₀, the approved version's, and H₁, the one shown. Each head's
31// base is its merge base with T, which must be one commit: B₀ and B₁. B₀
32// must be B₁ or below it on T's first-parent history. Then the file delta
33// from B₀ to H₀ is set against the one from B₁ to H₁ (valley-delta-v1,
34// ../delta). Equal deltas are a clean restack, and review shows the
35// landings in (B₀, B₁] instead of the diff. Different deltas are a change,
36// and review shows the files whose change differs, git range-diff
37// B₀..H₀ B₁..H₁, and the diff of those files from B₁ to H₁. range-diff's
38// hunks carry no line numbers, so a note review takes beside them has no
39// anchor. The diff is in git's ordinary form, so a note taken beside a
40// line of it keeps its file and line. Either way, the commits' messages
41// and authors, from each base to its head, are compared separately, and a
42// difference is shown whatever the files say.
43//
44// The output is one line naming the kind, none, clean or changed, and then
45// the text review shows. none has text only when an approved version was
46// found or was ambiguous, and says why it is not compared.
47
48package main
49
50import (
51 "bufio"
52 "bytes"
53 "fmt"
54 "io"
55 "os/exec"
56 "sort"
57 "strconv"
58 "strings"
59 "unicode/utf8"
60
61 "the-valley/change"
62 "the-valley/delta"
63)
64
65const compareUsage = "usage: valley-go compare --tip <commit> <change ID> <version> <head>"
66
67// The kinds of comparison.
68const (
69 compareNone = "none"
70 compareClean = "clean"
71 compareChanged = "changed"
72)
73
74// approvalDecisions are the outcomes that judged a request, and so show
75// that a head was approved.
76var approvalDecisions = map[string]bool{"land": true, "stale": true, "reject": true}
77
78type compareArgs struct {
79 tip, id, head string
80 version int
81}
82
83func parseCompareArgs(args []string) (compareArgs, error) {
84 var a compareArgs
85 var rest []string
86 for i := 0; i < len(args); i++ {
87 switch {
88 case args[i] == "--tip" && i+1 < len(args):
89 a.tip = args[i+1]
90 i++
91 case strings.HasPrefix(args[i], "--tip="):
92 a.tip = strings.TrimPrefix(args[i], "--tip=")
93 default:
94 rest = append(rest, args[i])
95 }
96 }
97 if len(rest) != 3 || !isObjectID(a.tip) || !change.ValidID(rest[0]) || !isObjectID(rest[2]) {
98 return compareArgs{}, failure(compareUsage)
99 }
100 n, err := strconv.Atoi(rest[1])
101 if err != nil || n < 1 || strconv.Itoa(n) != rest[1] {
102 return compareArgs{}, failure(compareUsage)
103 }
104 a.id, a.version, a.head = rest[0], n, rest[2]
105 return a, nil
106}
107
108func runCompare(g git, args []string, w io.Writer) error {
109 a, err := parseCompareArgs(args)
110 if err != nil {
111 return err
112 }
113 if !g.succeeds(true, "rev-parse", "--git-dir") {
114 return failure("not a git repository")
115 }
116 if !g.succeeds(true, "cat-file", "-e", a.tip+"^{commit}") {
117 return failure("the tip " + a.tip + " is no commit here")
118 }
119 h, err := readHistory(g, a.id)
120 if err != nil {
121 return err
122 }
123 kind, text, err := compareVersion(g, h, a)
124 if err != nil {
125 return err
126 }
127 _, err = fmt.Fprintf(w, "%s\n%s", kind, text)
128 return err
129}
130
131// history is what origin holds about one change's approvals, read once.
132type history struct {
133 id, handle string
134 versions []change.Version
135 requests map[string]string // request name → the head its ref names
136 outcomes map[string]outcome // request name → its outcome record
137 others map[string]bool // request names something other than this change maps to
138 unread bool // a record on origin does not read
139}
140
141// outcome is what an outcome record says: the head it judged, and how.
142type outcome struct {
143 head, decision string
144}
145
146// readHistory reads origin once: every branch, record, request and
147// outcome. It is the one place this file uses the inventory's readings of
148// origin (changes.go, inventory.go, status.go), so moving them changes
149// this function and nothing else here.
150func readHistory(g git, id string) (*history, error) {
151 o, err := listOrigin(g, inventoryPatterns...)
152 if err != nil {
153 return nil, err
154 }
155 all, unread, err := readAll(g, o)
156 if err != nil {
157 return nil, err
158 }
159 var want []string
160 for ref, oid := range o.refs {
161 if strings.HasPrefix(ref, outcomePrefix) {
162 want = append(want, oid)
163 }
164 }
165 if err := fetch(g, want...); err != nil {
166 return nil, err
167 }
168 h := &history{
169 id: id, handle: o.handle(id), unread: len(unread) > 0,
170 requests: map[string]string{}, outcomes: map[string]outcome{}, others: map[string]bool{},
171 }
172 ours := map[string]bool{}
173 for _, n := range all {
174 if n.id == id {
175 h.versions = n.record.Versions
176 }
177 }
178 if h.versions == nil {
179 return nil, failure("origin holds no record of change " + id)
180 }
181 for _, v := range h.versions {
182 if v.Branch != "" {
183 ours[v.Branch] = true
184 }
185 }
186 for _, n := range all {
187 if n.id == id {
188 continue
189 }
190 for _, v := range n.record.Versions {
191 if v.Branch != "" {
192 h.others[changeName(v.Branch)] = true
193 }
194 }
195 }
196 for ref, oid := range o.refs {
197 if branch, ok := strings.CutPrefix(ref, "refs/heads/"); ok && !ours[branch] {
198 h.others[changeName(branch)] = true
199 }
200 if name, ok := strings.CutPrefix(ref, requestPrefix); ok {
201 h.requests[name] = oid
202 }
203 if name, ok := strings.CutPrefix(ref, outcomePrefix); ok {
204 record, err := g.output(true, "cat-file", "blob", oid)
205 if err != nil {
206 record = ""
207 }
208 m := parseMemo(record)
209 h.outcomes[name] = outcome{head: m.head, decision: m.decision}
210 }
211 }
212 return h, nil
213}
214
215// head is version n's head, as an object ID.
216func (h *history) head(n int) string {
217 return strings.TrimPrefix(h.versions[n-1].Head, change.HeadPrefix)
218}
219
220// names are the request names a request for this change may be filed
221// under: c-<change ID> first, then each version's branch's, each once. A
222// branch whose name maps to c-<ID> adds nothing. That name is reserved
223// for the change with that ID, which may be another change, and this
224// change's own is already first.
225func (h *history) names() []string {
226 names := []string{change.RequestName(h.id)}
227 seen := map[string]bool{names[0]: true}
228 for _, v := range h.versions {
229 if v.Branch == "" {
230 continue
231 }
232 name := changeName(v.Branch)
233 if _, reserved := change.RequestID(name); reserved {
234 continue
235 }
236 if !seen[name] {
237 seen[name] = true
238 names = append(names, name)
239 }
240 }
241 return names
242}
243
244// ambiguous reports whether a request name may stand for something other
245// than this change. c-<change ID> is this change's alone: no branch is
246// filed under it.
247func (h *history) ambiguous(name string) bool {
248 return name != change.RequestName(h.id) && (h.unread || h.others[name])
249}
250
251// reference is the approved version a version is compared with.
252type reference struct {
253 version int // the approved version; 0 for none
254 by string // the ref that names its head as approved
255 unclear string // when there is none: why the approved version is not known, if it may exist
256}
257
258// reference finds the approved version below the version shown, as the
259// file's comment describes.
260func (h *history) reference(shown int) reference {
261 for m := shown - 1; m >= 1; m-- {
262 head := h.head(m)
263 var ambiguousRef string
264 for _, name := range h.names() {
265 var refs []string
266 if h.requests[name] == head {
267 refs = append(refs, requestPrefix+name)
268 }
269 if o, ok := h.outcomes[name]; ok && o.head == head && approvalDecisions[o.decision] {
270 refs = append(refs, outcomePrefix+name)
271 }
272 if len(refs) == 0 {
273 continue
274 }
275 if !h.ambiguous(name) {
276 return reference{version: m, by: refs[0]}
277 }
278 if ambiguousRef == "" {
279 ambiguousRef = refs[0]
280 }
281 }
282 if ambiguousRef != "" {
283 return reference{unclear: fmt.Sprintf(
284 "v%d at %s is named by %s, and another change or branch maps to that name too, so whether v%d was approved is not known",
285 m, short(head), ambiguousRef, m)}
286 }
287 }
288 return reference{}
289}
290
291// compareVersion compares the version a names with its approved version,
292// and returns the kind and the text review shows.
293func compareVersion(g git, h *history, a compareArgs) (kind, text string, err error) {
294 if a.version > len(h.versions) {
295 return "", "", failure(fmt.Sprintf("change %s has no v%d", h.handle, a.version))
296 }
297 if got := h.head(a.version); got != a.head {
298 return "", "", failure(fmt.Sprintf("v%d of change %s records the head %s, not %s", a.version, h.handle, got, a.head))
299 }
300 shown := fmt.Sprintf("%s v%d at %s", h.handle, a.version, short(a.head))
301 ref := h.reference(a.version)
302 if ref.version == 0 {
303 if ref.unclear == "" {
304 return compareNone, "", nil
305 }
306 return compareNone, fmt.Sprintf("%s: %s; reviewing it in full.\n", shown, ref.unclear), nil
307 }
308 old := ref.version
309 h0 := h.head(old)
310 approved := fmt.Sprintf("approved v%d at %s", old, short(h0))
311 withheld := func(why string) (string, string, error) {
312 return compareNone, fmt.Sprintf("%s: %s (%s) is not compared, since %s; reviewing it in full.\n",
313 shown, approved, ref.by, why), nil
314 }
315
316 b0, ok := uniqueBase(g, a.tip, h0)
317 if !ok {
318 return withheld(fmt.Sprintf("v%d's merge base with main is not one commit", old))
319 }
320 b1, ok := uniqueBase(g, a.tip, a.head)
321 if !ok {
322 return withheld(fmt.Sprintf("v%d's merge base with main is not one commit", a.version))
323 }
324 line, err := g.output(true, "rev-list", "--first-parent", a.tip)
325 if err != nil {
326 return "", "", failure("could not read main's history")
327 }
328 firstParent := strings.Fields(line)
329 i0, i1 := indexOf(firstParent, b0), indexOf(firstParent, b1)
330 switch {
331 case i0 < 0:
332 return withheld(fmt.Sprintf("v%d's base %s is not on main's first-parent history", old, short(b0)))
333 case i1 < 0:
334 return withheld(fmt.Sprintf("v%d's base %s is not on main's first-parent history", a.version, short(b1)))
335 case i0 < i1:
336 return withheld(fmt.Sprintf("v%d's base %s is above v%d's base %s on main", old, short(b0), a.version, short(b1)))
337 }
338 repo := delta.Repo{Dir: g.dir, Env: g.env}
339 d0, err := delta.Between(repo, b0, h0)
340 if err != nil {
341 return withheld(fmt.Sprintf("v%d's files do not read as valley-delta-v1: %v", old, err))
342 }
343 d1, err := delta.Between(repo, b1, a.head)
344 if err != nil {
345 return withheld(fmt.Sprintf("v%d's files do not read as valley-delta-v1: %v", a.version, err))
346 }
347 c0, err := rangeCommits(g, b0, h0)
348 if err != nil {
349 return "", "", err
350 }
351 c1, err := rangeCommits(g, b1, a.head)
352 if err != nil {
353 return "", "", err
354 }
355 meta := metadataChanges(c0, c1, old, a.version)
356
357 var b strings.Builder
358 if d0.Digest() == d1.Digest() {
359 kind = compareClean
360 fmt.Fprintf(&b, "%s: clean restack of %s.\n", shown, approved)
361 fmt.Fprintf(&b, "File delta unchanged. Base %s -> %s.\n", short(b0), short(b1))
362 b.WriteString(meta)
363 landings := firstParent[i1:i0]
364 if len(landings) == 0 {
365 b.WriteString("Landings between bases: none.\n")
366 return kind, b.String(), nil
367 }
368 b.WriteString("Landings between bases:\n")
369 commits, err := readCommits(g, landings)
370 if err != nil {
371 return "", "", err
372 }
373 for i := len(commits) - 1; i >= 0; i-- {
374 fmt.Fprintf(&b, " %s %s\n", short(commits[i].oid), visible(commits[i].subject()))
375 }
376 return kind, b.String(), nil
377 }
378 kind = compareChanged
379 fmt.Fprintf(&b, "%s: changed since %s.\n", shown, approved)
380 b.WriteString("Review the range-diff before approving.\n")
381 b.WriteString(meta)
382 fmt.Fprintf(&b, "Base %s -> %s.\n", short(b0), short(b1))
383 fmt.Fprintf(&b, "Files whose change differs from v%d's, as mode and SHA-256 of the content:\n", old)
384 listing, paths := deltaDifferences(d0, d1, old, a.version)
385 b.WriteString(listing)
386 fmt.Fprintf(&b, "\ngit range-diff %s..%s %s..%s:\n", short(b0), short(h0), short(b1), short(a.head))
387 out, err := g.output(true, "range-diff", "--no-color", b0+".."+h0, b1+".."+a.head)
388 if err != nil {
389 b.WriteString(" (git range-diff failed; view the full diff)\n")
390 } else {
391 b.WriteString(out + "\n")
392 }
393 fmt.Fprintf(&b, "\nv%d's diff of the files whose change differs, from its base %s. A note written beside a line of it keeps its file and line:\n",
394 a.version, short(b1))
395 // The prefixes and the options are fixed, so that the person's
396 // configuration cannot change the form review anchors notes by. The
397 // paths are taken literally, as the delta has them, and a rename is a
398 // deletion and an addition, as it is in the delta.
399 out, err = g.output(true, append([]string{"--literal-pathspecs", "diff", "--no-color", "--no-ext-diff", "--no-textconv",
400 "--no-renames", "--no-relative", "--src-prefix=a/", "--dst-prefix=b/", b1, a.head, "--"}, paths...)...)
401 switch {
402 case err != nil:
403 b.WriteString(" (git diff failed; view the full diff)\n")
404 case out == "":
405 fmt.Fprintf(&b, " none: v%d leaves each of them as its base has it.\n", a.version)
406 default:
407 b.WriteString(out + "\n")
408 }
409 return kind, b.String(), nil
410}
411
412// uniqueBase is head's merge base with tip, when there is exactly one.
413func uniqueBase(g git, tip, head string) (string, bool) {
414 out, err := g.output(true, "merge-base", "--all", tip, head)
415 bases := strings.Fields(out)
416 if err != nil || len(bases) != 1 {
417 return "", false
418 }
419 return bases[0], true
420}
421
422func indexOf(list []string, s string) int {
423 for i, e := range list {
424 if e == s {
425 return i
426 }
427 }
428 return -1
429}
430
431// deltaDifferences lists each path whose change differs between two
432// deltas: its change in the approved version's, then in the shown one's.
433// Each image is its mode and the first twelve hex digits of its hash, so a
434// binary file or a mode that changed is listed like any other. It returns
435// the listing and the paths, sorted.
436func deltaDifferences(d0, d1 delta.Delta, old, shown int) (string, []string) {
437 byPath := map[string][2]*delta.Change{}
438 for side, d := range []delta.Delta{d0, d1} {
439 for i := range d {
440 pair := byPath[d[i].Path]
441 pair[side] = &d[i]
442 byPath[d[i].Path] = pair
443 }
444 }
445 paths := make([]string, 0, len(byPath))
446 for p, pair := range byPath {
447 if pair[0] != nil && pair[1] != nil && *pair[0] == *pair[1] {
448 continue
449 }
450 paths = append(paths, p)
451 }
452 sort.Strings(paths)
453 var b strings.Builder
454 for _, p := range paths {
455 pair := byPath[p]
456 fmt.Fprintf(&b, " %s\n v%d: %s\n v%d: %s\n", quotedPath(p), old, described(pair[0]), shown, described(pair[1]))
457 }
458 return b.String(), paths
459}
460
461// described is a path's change in one delta, or unchanged for none.
462func described(c *delta.Change) string {
463 if c == nil {
464 return "unchanged"
465 }
466 image := func(i delta.Image) string {
467 if i.Absent() {
468 return "absent"
469 }
470 return i.Mode + " " + fmt.Sprintf("%x", i.Sum[:6])
471 }
472 return image(c.Pre) + " -> " + image(c.Post)
473}
474
475// quotedPath is a path as it is printed: as it is when every character is
476// printable, and otherwise in Go's quoting, which escapes the rest.
477func quotedPath(p string) string {
478 if utf8.ValidString(p) && strings.IndexFunc(p, func(r rune) bool { return !strconv.IsPrint(r) }) < 0 {
479 return p
480 }
481 return strconv.Quote(p)
482}
483
484// commitText is one commit object's author and message, as stored.
485type commitText struct {
486 oid, author, message string
487 encoding string // the encoding header, when the commit has one
488}
489
490func (c commitText) subject() string {
491 line, _, _ := strings.Cut(c.message, "\n")
492 return line
493}
494
495// rangeCommits are the commits from base to head, oldest first, read
496// whole.
497func rangeCommits(g git, base, head string) ([]commitText, error) {
498 out, err := g.output(true, "rev-list", "--reverse", base+".."+head)
499 if err != nil {
500 return nil, failure("could not list the commits from " + short(base) + " to " + short(head))
501 }
502 return readCommits(g, strings.Fields(out))
503}
504
505// readCommits reads commit objects with one git cat-file --batch, whose
506// output is read as git wrote it: a message's own trailing newlines are
507// part of the object.
508func readCommits(g git, oids []string) ([]commitText, error) {
509 if len(oids) == 0 {
510 return nil, nil
511 }
512 cmd := exec.Command("git", "cat-file", "--batch")
513 cmd.Env, cmd.Dir = g.env, g.dir
514 cmd.Stdin = strings.NewReader(strings.Join(oids, "\n") + "\n")
515 out, err := cmd.Output()
516 if err != nil {
517 return nil, failure("could not read the commits")
518 }
519 r := bufio.NewReader(bytes.NewReader(out))
520 var commits []commitText
521 for _, oid := range oids {
522 header, err := r.ReadString('\n')
523 fields := strings.Fields(header)
524 if err != nil || len(fields) != 3 || fields[0] != oid || fields[1] != "commit" {
525 return nil, failure("could not read the commit " + oid)
526 }
527 size, err := strconv.Atoi(fields[2])
528 if err != nil || size < 0 {
529 return nil, failure("could not read the commit " + oid)
530 }
531 data := make([]byte, size+1)
532 if _, err := io.ReadFull(r, data); err != nil || data[size] != '\n' {
533 return nil, failure("could not read the commit " + oid)
534 }
535 commits = append(commits, parseCommit(oid, data[:size]))
536 }
537 return commits, nil
538}
539
540// parseCommit reads the author and the message of a commit object: the
541// headers up to the first blank line, and everything after it.
542func parseCommit(oid string, data []byte) commitText {
543 c := commitText{oid: oid}
544 headers, message, _ := bytes.Cut(data, []byte("\n\n"))
545 c.message = string(message)
546 for _, line := range strings.Split(string(headers), "\n") {
547 if v, ok := strings.CutPrefix(line, "author "); ok {
548 c.author = v
549 }
550 if v, ok := strings.CutPrefix(line, "encoding "); ok {
551 c.encoding = v
552 }
553 }
554 return c
555}
556
557// metadataChanges says how the shown version's commits' messages and
558// authors differ from the approved version's, from each base to its head:
559// nothing when they are the same. With as many commits on each side, each
560// commit is set against the one in its place, and only those whose
561// message or author differs are shown. Otherwise every commit on each
562// side is, with its author and its message.
563func metadataChanges(c0, c1 []commitText, old, shown int) string {
564 var b strings.Builder
565 author := func(c commitText) string { return " " + visible(c.author) }
566 message := func(c commitText) string {
567 lines := []string{""}
568 if c.encoding != "" {
569 lines = append(lines, " (encoding "+visible(c.encoding)+")")
570 }
571 for _, l := range strings.Split(strings.TrimRight(c.message, "\n"), "\n") {
572 lines = append(lines, " "+visible(l))
573 }
574 return strings.Join(lines, "\n")
575 }
576 entry := func(v int, list []commitText, i int, show func(commitText) string) {
577 fmt.Fprintf(&b, " v%d, commit %d of %d, %s:%s\n", v, i+1, len(list), short(list[i].oid), show(list[i]))
578 }
579 if len(c0) != len(c1) {
580 fmt.Fprintf(&b, "Commits changed since approved v%d: v%d has %s, and v%d has %s. Read their authors and messages before approving:\n",
581 old, old, counted(len(c0), "commit"), shown, counted(len(c1), "commit"))
582 both := func(c commitText) string { return author(c) + message(c) }
583 for i := range c0 {
584 entry(old, c0, i, both)
585 }
586 for i := range c1 {
587 entry(shown, c1, i, both)
588 }
589 return b.String()
590 }
591 for _, field := range []struct {
592 heading string
593 of func(commitText) string
594 show func(commitText) string
595 }{
596 {"Commit messages changed since approved v%d. Read them before approving:\n",
597 func(c commitText) string { return c.encoding + "\x00" + c.message }, message},
598 {"Commit authors changed since approved v%d:\n",
599 func(c commitText) string { return c.author }, author},
600 } {
601 headed := false
602 for i := range c0 {
603 if field.of(c0[i]) == field.of(c1[i]) {
604 continue
605 }
606 if !headed {
607 fmt.Fprintf(&b, field.heading, old)
608 headed = true
609 }
610 entry(old, c0, i, field.show)
611 entry(shown, c1, i, field.show)
612 }
613 }
614 return b.String()
615}