gunk-dev/the-valley

compare.go

source721fe5203156main'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 s := newSnapshot(g, o, all, verifier{})
169 h := &history{
170 id: id, handle: o.handle(id), unread: len(unread) > 0,
171 requests: map[string]string{}, outcomes: map[string]outcome{}, others: map[string]bool{},
172 }
173 ours := map[string]bool{}
174 for _, n := range all {
175 if n.id == id {
176 h.versions = n.record.Versions
177 }
178 }
179 if h.versions == nil {
180 return nil, failure("origin holds no record of change " + id)
181 }
182 for _, v := range h.versions {
183 if v.Branch != "" {
184 ours[v.Branch] = true
185 }
186 }
187 for _, n := range all {
188 if n.id == id {
189 continue
190 }
191 for _, v := range n.record.Versions {
192 if v.Branch != "" {
193 h.others[changeName(v.Branch)] = true
194 }
195 }
196 }
197 for ref, oid := range o.refs {
198 if branch, ok := strings.CutPrefix(ref, "refs/heads/"); ok && !ours[branch] {
199 h.others[changeName(branch)] = true
200 }
201 if name, ok := strings.CutPrefix(ref, requestPrefix); ok {
202 h.requests[name] = oid
203 }
204 }
205 for ref, m := range s.outcomes {
206 h.outcomes[strings.TrimPrefix(ref, outcomePrefix)] = outcome{head: m.head, decision: m.decision}
207 }
208 return h, nil
209}
210
211// head is version n's head, as an object ID.
212func (h *history) head(n int) string {
213 return strings.TrimPrefix(h.versions[n-1].Head, change.HeadPrefix)
214}
215
216// names are the request names a request for this change may be filed
217// under: c-<change ID> first, then each version's branch's, each once. A
218// branch whose name maps to c-<ID> adds nothing. That name is reserved
219// for the change with that ID, which may be another change, and this
220// change's own is already first.
221func (h *history) names() []string {
222 names := []string{change.RequestName(h.id)}
223 seen := map[string]bool{names[0]: true}
224 for _, v := range h.versions {
225 if v.Branch == "" {
226 continue
227 }
228 name := changeName(v.Branch)
229 if _, reserved := change.RequestID(name); reserved {
230 continue
231 }
232 if !seen[name] {
233 seen[name] = true
234 names = append(names, name)
235 }
236 }
237 return names
238}
239
240// ambiguous reports whether a request name may stand for something other
241// than this change. c-<change ID> is this change's alone: no branch is
242// filed under it.
243func (h *history) ambiguous(name string) bool {
244 return name != change.RequestName(h.id) && (h.unread || h.others[name])
245}
246
247// reference is the approved version a version is compared with.
248type reference struct {
249 version int // the approved version; 0 for none
250 by string // the ref that names its head as approved
251 unclear string // when there is none: why the approved version is not known, if it may exist
252}
253
254// reference finds the approved version below the version shown, as the
255// file's comment describes.
256func (h *history) reference(shown int) reference {
257 for m := shown - 1; m >= 1; m-- {
258 head := h.head(m)
259 var ambiguousRef string
260 for _, name := range h.names() {
261 var refs []string
262 if h.requests[name] == head {
263 refs = append(refs, requestPrefix+name)
264 }
265 if o, ok := h.outcomes[name]; ok && o.head == head && approvalDecisions[o.decision] {
266 refs = append(refs, outcomePrefix+name)
267 }
268 if len(refs) == 0 {
269 continue
270 }
271 if !h.ambiguous(name) {
272 return reference{version: m, by: refs[0]}
273 }
274 if ambiguousRef == "" {
275 ambiguousRef = refs[0]
276 }
277 }
278 if ambiguousRef != "" {
279 return reference{unclear: fmt.Sprintf(
280 "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",
281 m, short(head), ambiguousRef, m)}
282 }
283 }
284 return reference{}
285}
286
287// compareVersion compares the version a names with its approved version,
288// and returns the kind and the text review shows.
289func compareVersion(g git, h *history, a compareArgs) (kind, text string, err error) {
290 if a.version > len(h.versions) {
291 return "", "", failure(fmt.Sprintf("change %s has no v%d", h.handle, a.version))
292 }
293 if got := h.head(a.version); got != a.head {
294 return "", "", failure(fmt.Sprintf("v%d of change %s records the head %s, not %s", a.version, h.handle, got, a.head))
295 }
296 shown := fmt.Sprintf("%s v%d at %s", h.handle, a.version, short(a.head))
297 ref := h.reference(a.version)
298 if ref.version == 0 {
299 if ref.unclear == "" {
300 return compareNone, "", nil
301 }
302 return compareNone, fmt.Sprintf("%s: %s; reviewing it in full.\n", shown, ref.unclear), nil
303 }
304 old := ref.version
305 h0 := h.head(old)
306 approved := fmt.Sprintf("approved v%d at %s", old, short(h0))
307 withheld := func(why string) (string, string, error) {
308 return compareNone, fmt.Sprintf("%s: %s (%s) is not compared, since %s; reviewing it in full.\n",
309 shown, approved, ref.by, why), nil
310 }
311
312 b0, ok := uniqueBase(g, a.tip, h0)
313 if !ok {
314 return withheld(fmt.Sprintf("v%d's merge base with main is not one commit", old))
315 }
316 b1, ok := uniqueBase(g, a.tip, a.head)
317 if !ok {
318 return withheld(fmt.Sprintf("v%d's merge base with main is not one commit", a.version))
319 }
320 line, err := g.output(true, "rev-list", "--first-parent", a.tip)
321 if err != nil {
322 return "", "", failure("could not read main's history")
323 }
324 firstParent := strings.Fields(line)
325 i0, i1 := indexOf(firstParent, b0), indexOf(firstParent, b1)
326 switch {
327 case i0 < 0:
328 return withheld(fmt.Sprintf("v%d's base %s is not on main's first-parent history", old, short(b0)))
329 case i1 < 0:
330 return withheld(fmt.Sprintf("v%d's base %s is not on main's first-parent history", a.version, short(b1)))
331 case i0 < i1:
332 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)))
333 }
334 repo := delta.Repo{Dir: g.dir, Env: g.env}
335 d0, err := delta.Between(repo, b0, h0)
336 if err != nil {
337 return withheld(fmt.Sprintf("v%d's files do not read as valley-delta-v1: %v", old, err))
338 }
339 d1, err := delta.Between(repo, b1, a.head)
340 if err != nil {
341 return withheld(fmt.Sprintf("v%d's files do not read as valley-delta-v1: %v", a.version, err))
342 }
343 c0, err := rangeCommits(g, b0, h0)
344 if err != nil {
345 return "", "", err
346 }
347 c1, err := rangeCommits(g, b1, a.head)
348 if err != nil {
349 return "", "", err
350 }
351 meta := metadataChanges(c0, c1, old, a.version)
352
353 var b strings.Builder
354 if d0.Digest() == d1.Digest() {
355 kind = compareClean
356 fmt.Fprintf(&b, "%s: clean restack of %s.\n", shown, approved)
357 fmt.Fprintf(&b, "File delta unchanged. Base %s -> %s.\n", short(b0), short(b1))
358 b.WriteString(meta)
359 landings := firstParent[i1:i0]
360 if len(landings) == 0 {
361 b.WriteString("Landings between bases: none.\n")
362 return kind, b.String(), nil
363 }
364 b.WriteString("Landings between bases:\n")
365 commits, err := readCommits(g, landings)
366 if err != nil {
367 return "", "", err
368 }
369 for i := len(commits) - 1; i >= 0; i-- {
370 fmt.Fprintf(&b, " %s %s\n", short(commits[i].oid), visible(commits[i].subject()))
371 }
372 return kind, b.String(), nil
373 }
374 kind = compareChanged
375 fmt.Fprintf(&b, "%s: changed since %s.\n", shown, approved)
376 b.WriteString("Review the range-diff before approving.\n")
377 b.WriteString(meta)
378 fmt.Fprintf(&b, "Base %s -> %s.\n", short(b0), short(b1))
379 fmt.Fprintf(&b, "Files whose change differs from v%d's, as mode and SHA-256 of the content:\n", old)
380 listing, paths := deltaDifferences(d0, d1, old, a.version)
381 b.WriteString(listing)
382 fmt.Fprintf(&b, "\ngit range-diff %s..%s %s..%s:\n", short(b0), short(h0), short(b1), short(a.head))
383 out, err := g.output(true, "range-diff", "--no-color", b0+".."+h0, b1+".."+a.head)
384 if err != nil {
385 b.WriteString(" (git range-diff failed; view the full diff)\n")
386 } else {
387 b.WriteString(out + "\n")
388 }
389 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",
390 a.version, short(b1))
391 // The prefixes and the options are fixed, so that the person's
392 // configuration cannot change the form review anchors notes by. The
393 // paths are taken literally, as the delta has them, and a rename is a
394 // deletion and an addition, as it is in the delta.
395 out, err = g.output(true, append([]string{"--literal-pathspecs", "diff", "--no-color", "--no-ext-diff", "--no-textconv",
396 "--no-renames", "--no-relative", "--src-prefix=a/", "--dst-prefix=b/", b1, a.head, "--"}, paths...)...)
397 switch {
398 case err != nil:
399 b.WriteString(" (git diff failed; view the full diff)\n")
400 case out == "":
401 fmt.Fprintf(&b, " none: v%d leaves each of them as its base has it.\n", a.version)
402 default:
403 b.WriteString(out + "\n")
404 }
405 return kind, b.String(), nil
406}
407
408// uniqueBase is head's merge base with tip, when there is exactly one.
409func uniqueBase(g git, tip, head string) (string, bool) {
410 out, err := g.output(true, "merge-base", "--all", tip, head)
411 bases := strings.Fields(out)
412 if err != nil || len(bases) != 1 {
413 return "", false
414 }
415 return bases[0], true
416}
417
418func indexOf(list []string, s string) int {
419 for i, e := range list {
420 if e == s {
421 return i
422 }
423 }
424 return -1
425}
426
427// deltaDifferences lists each path whose change differs between two
428// deltas: its change in the approved version's, then in the shown one's.
429// Each image is its mode and the first twelve hex digits of its hash, so a
430// binary file or a mode that changed is listed like any other. It returns
431// the listing and the paths, sorted.
432func deltaDifferences(d0, d1 delta.Delta, old, shown int) (string, []string) {
433 byPath := map[string][2]*delta.Change{}
434 for side, d := range []delta.Delta{d0, d1} {
435 for i := range d {
436 pair := byPath[d[i].Path]
437 pair[side] = &d[i]
438 byPath[d[i].Path] = pair
439 }
440 }
441 paths := make([]string, 0, len(byPath))
442 for p, pair := range byPath {
443 if pair[0] != nil && pair[1] != nil && *pair[0] == *pair[1] {
444 continue
445 }
446 paths = append(paths, p)
447 }
448 sort.Strings(paths)
449 var b strings.Builder
450 for _, p := range paths {
451 pair := byPath[p]
452 fmt.Fprintf(&b, " %s\n v%d: %s\n v%d: %s\n", quotedPath(p), old, described(pair[0]), shown, described(pair[1]))
453 }
454 return b.String(), paths
455}
456
457// described is a path's change in one delta, or unchanged for none.
458func described(c *delta.Change) string {
459 if c == nil {
460 return "unchanged"
461 }
462 image := func(i delta.Image) string {
463 if i.Absent() {
464 return "absent"
465 }
466 return i.Mode + " " + fmt.Sprintf("%x", i.Sum[:6])
467 }
468 return image(c.Pre) + " -> " + image(c.Post)
469}
470
471// quotedPath is a path as it is printed: as it is when every character is
472// printable, and otherwise in Go's quoting, which escapes the rest.
473func quotedPath(p string) string {
474 if utf8.ValidString(p) && strings.IndexFunc(p, func(r rune) bool { return !strconv.IsPrint(r) }) < 0 {
475 return p
476 }
477 return strconv.Quote(p)
478}
479
480// commitText is one commit object's author and message, as stored.
481type commitText struct {
482 oid, author, message string
483 encoding string // the encoding header, when the commit has one
484}
485
486func (c commitText) subject() string {
487 line, _, _ := strings.Cut(c.message, "\n")
488 return line
489}
490
491// rangeCommits are the commits from base to head, oldest first, read
492// whole.
493func rangeCommits(g git, base, head string) ([]commitText, error) {
494 out, err := g.output(true, "rev-list", "--reverse", base+".."+head)
495 if err != nil {
496 return nil, failure("could not list the commits from " + short(base) + " to " + short(head))
497 }
498 return readCommits(g, strings.Fields(out))
499}
500
501// readCommits reads commit objects with one git cat-file --batch, whose
502// output is read as git wrote it: a message's own trailing newlines are
503// part of the object.
504func readCommits(g git, oids []string) ([]commitText, error) {
505 if len(oids) == 0 {
506 return nil, nil
507 }
508 cmd := exec.Command("git", "cat-file", "--batch")
509 cmd.Env, cmd.Dir = g.env, g.dir
510 cmd.Stdin = strings.NewReader(strings.Join(oids, "\n") + "\n")
511 out, err := cmd.Output()
512 if err != nil {
513 return nil, failure("could not read the commits")
514 }
515 r := bufio.NewReader(bytes.NewReader(out))
516 var commits []commitText
517 for _, oid := range oids {
518 header, err := r.ReadString('\n')
519 fields := strings.Fields(header)
520 if err != nil || len(fields) != 3 || fields[0] != oid || fields[1] != "commit" {
521 return nil, failure("could not read the commit " + oid)
522 }
523 size, err := strconv.Atoi(fields[2])
524 if err != nil || size < 0 {
525 return nil, failure("could not read the commit " + oid)
526 }
527 data := make([]byte, size+1)
528 if _, err := io.ReadFull(r, data); err != nil || data[size] != '\n' {
529 return nil, failure("could not read the commit " + oid)
530 }
531 commits = append(commits, parseCommit(oid, data[:size]))
532 }
533 return commits, nil
534}
535
536// parseCommit reads the author and the message of a commit object: the
537// headers up to the first blank line, and everything after it.
538func parseCommit(oid string, data []byte) commitText {
539 c := commitText{oid: oid}
540 headers, message, _ := bytes.Cut(data, []byte("\n\n"))
541 c.message = string(message)
542 for _, line := range strings.Split(string(headers), "\n") {
543 if v, ok := strings.CutPrefix(line, "author "); ok {
544 c.author = v
545 }
546 if v, ok := strings.CutPrefix(line, "encoding "); ok {
547 c.encoding = v
548 }
549 }
550 return c
551}
552
553// metadataChanges says how the shown version's commits' messages and
554// authors differ from the approved version's, from each base to its head:
555// nothing when they are the same. With as many commits on each side, each
556// commit is set against the one in its place, and only those whose
557// message or author differs are shown. Otherwise every commit on each
558// side is, with its author and its message.
559func metadataChanges(c0, c1 []commitText, old, shown int) string {
560 var b strings.Builder
561 author := func(c commitText) string { return " " + visible(c.author) }
562 message := func(c commitText) string {
563 lines := []string{""}
564 if c.encoding != "" {
565 lines = append(lines, " (encoding "+visible(c.encoding)+")")
566 }
567 for _, l := range strings.Split(strings.TrimRight(c.message, "\n"), "\n") {
568 lines = append(lines, " "+visible(l))
569 }
570 return strings.Join(lines, "\n")
571 }
572 entry := func(v int, list []commitText, i int, show func(commitText) string) {
573 fmt.Fprintf(&b, " v%d, commit %d of %d, %s:%s\n", v, i+1, len(list), short(list[i].oid), show(list[i]))
574 }
575 if len(c0) != len(c1) {
576 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",
577 old, old, counted(len(c0), "commit"), shown, counted(len(c1), "commit"))
578 both := func(c commitText) string { return author(c) + message(c) }
579 for i := range c0 {
580 entry(old, c0, i, both)
581 }
582 for i := range c1 {
583 entry(shown, c1, i, both)
584 }
585 return b.String()
586 }
587 for _, field := range []struct {
588 heading string
589 of func(commitText) string
590 show func(commitText) string
591 }{
592 {"Commit messages changed since approved v%d. Read them before approving:\n",
593 func(c commitText) string { return c.encoding + "\x00" + c.message }, message},
594 {"Commit authors changed since approved v%d:\n",
595 func(c commitText) string { return c.author }, author},
596 } {
597 headed := false
598 for i := range c0 {
599 if field.of(c0[i]) == field.of(c1[i]) {
600 continue
601 }
602 if !headed {
603 fmt.Fprintf(&b, field.heading, old)
604 headed = true
605 }
606 entry(old, c0, i, field.show)
607 entry(shown, c1, i, field.show)
608 }
609 }
610 return b.String()
611}