gunk-dev/the-valley

compare.go

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