gunk-dev/the-valley

compare.go

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