gunk-dev/the-valley

compare.go

sourceddfdc45c1aa2main's published tip history
29.6 KiB
1// 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 (review.go).
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), and each commit from B₁ to H₁ against the one in its place
35// from B₀ to H₀, by patch (git patch-id), message and author.
36//
37// The text opens with the answer: the shown version is rebased, when its
38// commits are the same and B₀ is not B₁; edited, when a commit is not the
39// same; and otherwise recommitted. Equal deltas are a clean restack, and
40// review shows the landings in (B₀, B₁] instead of the diff. Different
41// deltas list each file whose change differs, with the landings in
42// (B₀, B₁] that edited it, since a rebase onto a file main also edited
43// changes the file's delta and not the commit. Then, when a commit is
44// edited, comes git range-diff B₀..H₀ B₁..H₁, and last the diff of those
45// files from B₁ to H₁. range-diff's hunks carry no line numbers, so a
46// note review takes beside them has no anchor. The diff is in git's
47// ordinary form, so a note taken beside a line of it keeps its file and
48// line. Either way, a message or an author that differs is shown whatever
49// the files say.
50//
51// The output is one line naming the kind, none, clean or changed, and then
52// the text review shows, in plain text: style (style.go) styles it for a
53// terminal. none has text only when an approved version was found or was
54// ambiguous, and says why it is not compared.
55
56package main
57
58import (
59 "bufio"
60 "bytes"
61 "fmt"
62 "io"
63 "os/exec"
64 "sort"
65 "strconv"
66 "strings"
67 "unicode/utf8"
68
69 "the-valley/change"
70 "the-valley/delta"
71)
72
73// compareUsage is what runCompare, which review calls, takes.
74const compareUsage = "compare takes [-v] --tip <commit> <change ID> <version> <head>"
75
76// The kinds of comparison.
77const (
78 compareNone = "none"
79 compareClean = "clean"
80 compareChanged = "changed"
81)
82
83// approvalDecisions are the outcomes that judged a request, and so show
84// that a head was approved.
85var approvalDecisions = map[string]bool{"land": true, "stale": true, "reject": true}
86
87type compareArgs struct {
88 tip, id, head string
89 version int
90 verbose bool // list each differing file's change as modes and hashes
91}
92
93func parseCompareArgs(args []string) (compareArgs, error) {
94 var a compareArgs
95 var rest []string
96 for i := 0; i < len(args); i++ {
97 switch {
98 case args[i] == "--tip" && i+1 < len(args):
99 a.tip = args[i+1]
100 i++
101 case strings.HasPrefix(args[i], "--tip="):
102 a.tip = strings.TrimPrefix(args[i], "--tip=")
103 case args[i] == "-v":
104 a.verbose = true
105 default:
106 rest = append(rest, args[i])
107 }
108 }
109 if len(rest) != 3 || !isObjectID(a.tip) || !change.ValidID(rest[0]) || !isObjectID(rest[2]) {
110 return compareArgs{}, failure(compareUsage)
111 }
112 n, err := strconv.Atoi(rest[1])
113 if err != nil || n < 1 || strconv.Itoa(n) != rest[1] {
114 return compareArgs{}, failure(compareUsage)
115 }
116 a.id, a.version, a.head = rest[0], n, rest[2]
117 return a, nil
118}
119
120func runCompare(g git, args []string, w io.Writer) error {
121 a, err := parseCompareArgs(args)
122 if err != nil {
123 return err
124 }
125 if !g.succeeds(true, "rev-parse", "--git-dir") {
126 return failure("not a git repository")
127 }
128 if !g.succeeds(true, "cat-file", "-e", a.tip+"^{commit}") {
129 return failure("the tip " + a.tip + " is no commit here")
130 }
131 h, err := readHistory(g, a.id)
132 if err != nil {
133 return err
134 }
135 kind, text, err := compareVersion(g, h, a)
136 if err != nil {
137 return err
138 }
139 _, err = fmt.Fprintf(w, "%s\n%s", kind, text)
140 return err
141}
142
143// history is what origin holds about one change's approvals, read once.
144type history struct {
145 id, handle string
146 tip string // main on origin; "" when origin has none
147 versions []change.Version
148 requests map[string]string // request name → the head its ref names
149 outcomes map[string]outcome // request name → its outcome record
150 others map[string]bool // request names something other than this change maps to
151 unread bool // a record on origin does not read
152}
153
154// outcome is what an outcome record says: the head it judged, and how.
155type outcome struct {
156 head, decision string
157}
158
159// readHistory reads origin once: every branch, record, request and
160// outcome. It is the one place this file uses the inventory's readings of
161// origin (changes.go, inventory.go, status.go), so moving them changes
162// this function and nothing else here.
163func readHistory(g git, id string) (*history, error) {
164 o, err := listOrigin(g, inventoryPatterns...)
165 if err != nil {
166 return nil, err
167 }
168 all, unread, err := readAll(g, o)
169 if err != nil {
170 return nil, err
171 }
172 return historyOf(g, o, all, len(unread) > 0, id)
173}
174
175// historyOf is the change's history in what one read of origin listed, o,
176// and the records it read, all; unread says a record did not read.
177func historyOf(g git, o origin, all []recorded, unread bool, id string) (*history, error) {
178 var want []string
179 for ref, oid := range o.refs {
180 if strings.HasPrefix(ref, outcomePrefix) {
181 want = append(want, oid)
182 }
183 }
184 if err := fetch(g, want...); err != nil {
185 return nil, err
186 }
187 h := &history{
188 id: id, handle: o.handle(id), unread: unread,
189 requests: map[string]string{}, outcomes: map[string]outcome{}, others: map[string]bool{},
190 }
191 ours := map[string]bool{}
192 for _, n := range all {
193 if n.id == id {
194 h.versions = n.record.Versions
195 }
196 }
197 if h.versions == nil {
198 return nil, failure("origin holds no record of change " + id)
199 }
200 for _, v := range h.versions {
201 if v.Branch != "" {
202 ours[v.Branch] = true
203 }
204 }
205 for _, n := range all {
206 if n.id == id {
207 continue
208 }
209 for _, v := range n.record.Versions {
210 if v.Branch != "" {
211 h.others[changeName(v.Branch)] = true
212 }
213 }
214 }
215 for ref, oid := range o.refs {
216 if ref == "refs/heads/"+recordTarget {
217 h.tip = oid
218 }
219 if branch, ok := strings.CutPrefix(ref, "refs/heads/"); ok && !ours[branch] {
220 h.others[changeName(branch)] = true
221 }
222 if name, ok := strings.CutPrefix(ref, requestPrefix); ok {
223 h.requests[name] = oid
224 }
225 if name, ok := strings.CutPrefix(ref, outcomePrefix); ok {
226 record, err := g.output(true, "cat-file", "blob", oid)
227 if err != nil {
228 record = ""
229 }
230 m := parseMemo(record)
231 h.outcomes[name] = outcome{head: m.head, decision: m.decision}
232 }
233 }
234 return h, nil
235}
236
237// head is version n's head, as an object ID.
238func (h *history) head(n int) string {
239 return strings.TrimPrefix(h.versions[n-1].Head, change.HeadPrefix)
240}
241
242// names are the request names a request for this change may be filed
243// under: c-<change ID> first, then each version's branch's, each once. A
244// branch whose name maps to c-<ID> adds nothing. That name is reserved
245// for the change with that ID, which may be another change, and this
246// change's own is already first.
247func (h *history) names() []string {
248 names := []string{change.RequestName(h.id)}
249 seen := map[string]bool{names[0]: true}
250 for _, v := range h.versions {
251 if v.Branch == "" {
252 continue
253 }
254 name := changeName(v.Branch)
255 if _, reserved := change.RequestID(name); reserved {
256 continue
257 }
258 if !seen[name] {
259 seen[name] = true
260 names = append(names, name)
261 }
262 }
263 return names
264}
265
266// ambiguous reports whether a request name may stand for something other
267// than this change. c-<change ID> is this change's alone: no branch is
268// filed under it.
269func (h *history) ambiguous(name string) bool {
270 return name != change.RequestName(h.id) && (h.unread || h.others[name])
271}
272
273// reference is the earlier version a version is compared with: the
274// approved one, or for carry the one review showed.
275type reference struct {
276 version int // the approved version; 0 for none
277 by string // the ref that names its head as approved; "" when it is not an approval
278 unclear string // when there is none: why the approved version is not known, if it may exist
279}
280
281// comparison is what comparing a version with its reference found.
282type comparison struct {
283 kind, text string
284 verb string // rebased, edited or recommitted, as the text opens
285 edited int // the shown version's commits that differ from the earlier version's
286 had, has int // the earlier and the shown version's commit counts
287 mainEdited []string // the files whose change differs that a landing in between edited
288 meta bool // the commits' messages or authors differ
289 base, head string // the shown version's base and head
290 landings []string // main's first-parent history from the shown version's base down to the reference's, both included
291}
292
293// reference finds the approved version below the version shown, as the
294// file's comment describes.
295func (h *history) reference(shown int) reference {
296 for m := shown - 1; m >= 1; m-- {
297 head := h.head(m)
298 var ambiguousRef string
299 for _, name := range h.names() {
300 var refs []string
301 if h.requests[name] == head {
302 refs = append(refs, requestPrefix+name)
303 }
304 if o, ok := h.outcomes[name]; ok && o.head == head && approvalDecisions[o.decision] {
305 refs = append(refs, outcomePrefix+name)
306 }
307 if len(refs) == 0 {
308 continue
309 }
310 if !h.ambiguous(name) {
311 return reference{version: m, by: refs[0]}
312 }
313 if ambiguousRef == "" {
314 ambiguousRef = refs[0]
315 }
316 }
317 if ambiguousRef != "" {
318 return reference{unclear: fmt.Sprintf(
319 "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",
320 m, short(head), ambiguousRef, m)}
321 }
322 }
323 return reference{}
324}
325
326// compareVersion compares the version a names with its approved version,
327// and returns the kind and the text review shows.
328func compareVersion(g git, h *history, a compareArgs) (kind, text string, err error) {
329 if a.version > len(h.versions) {
330 return "", "", failure(fmt.Sprintf("change %s has no v%d", h.handle, a.version))
331 }
332 if got := h.head(a.version); got != a.head {
333 return "", "", failure(fmt.Sprintf("v%d of change %s records the head %s, not %s", a.version, h.handle, got, a.head))
334 }
335 ref := h.reference(a.version)
336 if ref.version == 0 {
337 if ref.unclear == "" {
338 return compareNone, "", nil
339 }
340 shown := fmt.Sprintf("%s v%d at %s", h.handle, a.version, short(a.head))
341 return compareNone, fmt.Sprintf("%s: %s; reviewing it in full.\n", shown, ref.unclear), nil
342 }
343 c, err := compareWith(g, h, a.tip, ref, a.version, a.verbose)
344 return c.kind, c.text, err
345}
346
347// compareWith compares version n with the reference, against main's tip,
348// as the file's comment describes.
349func compareWith(g git, h *history, tip string, ref reference, n int, verbose bool) (comparison, error) {
350 a := compareArgs{tip: tip, id: h.id, version: n, head: h.head(n), verbose: verbose}
351 shown := fmt.Sprintf("%s v%d at %s", h.handle, a.version, short(a.head))
352 old := ref.version
353 h0 := h.head(old)
354 approved, by := fmt.Sprintf("v%d at %s", old, short(h0)), ""
355 if ref.by != "" {
356 approved, by = "approved "+approved, " ("+ref.by+")"
357 }
358 withheld := func(why string) (comparison, error) {
359 return comparison{kind: compareNone, text: fmt.Sprintf("%s: %s%s is not compared, since %s; reviewing it in full.\n",
360 shown, approved, by, why)}, nil
361 }
362
363 b0, ok := uniqueBase(g, a.tip, h0)
364 if !ok {
365 return withheld(fmt.Sprintf("v%d's merge base with main is not one commit", old))
366 }
367 b1, ok := uniqueBase(g, a.tip, a.head)
368 if !ok {
369 return withheld(fmt.Sprintf("v%d's merge base with main is not one commit", a.version))
370 }
371 line, err := g.output(true, "rev-list", "--first-parent", a.tip)
372 if err != nil {
373 return comparison{}, failure("could not read main's history")
374 }
375 firstParent := strings.Fields(line)
376 i0, i1 := indexOf(firstParent, b0), indexOf(firstParent, b1)
377 switch {
378 case i0 < 0:
379 return withheld(fmt.Sprintf("v%d's base %s is not on main's first-parent history", old, short(b0)))
380 case i1 < 0:
381 return withheld(fmt.Sprintf("v%d's base %s is not on main's first-parent history", a.version, short(b1)))
382 case i0 < i1:
383 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)))
384 }
385 repo := delta.Repo{Dir: g.dir, Env: g.env}
386 d0, err := delta.Between(repo, b0, h0)
387 if err != nil {
388 return withheld(fmt.Sprintf("v%d's files do not read as valley-delta-v1: %v", old, err))
389 }
390 d1, err := delta.Between(repo, b1, a.head)
391 if err != nil {
392 return withheld(fmt.Sprintf("v%d's files do not read as valley-delta-v1: %v", a.version, err))
393 }
394 c0, err := rangeCommits(g, b0, h0)
395 if err != nil {
396 return comparison{}, err
397 }
398 c1, err := rangeCommits(g, b1, a.head)
399 if err != nil {
400 return comparison{}, err
401 }
402 ids, err := patchIDs(g, append(oidsOf(c0), oidsOf(c1)...))
403 if err != nil {
404 return comparison{}, err
405 }
406 edited := editedCommits(c0, c1, ids)
407 moved, sameDelta := b0 != b1, d0.Digest() == d1.Digest()
408 verb := "edited"
409 if edited == 0 && len(c0) == len(c1) {
410 switch {
411 case moved:
412 verb = "rebased"
413 case sameDelta:
414 verb = "recommitted"
415 }
416 }
417 // since names the earlier version: the one the operator approved, or
418 // for carry the one review showed.
419 since := fmt.Sprintf("v%d", old)
420 if ref.by != "" {
421 since = "you approved " + since
422 }
423 meta := metadataChanges(c0, c1, since, old, a.version)
424 c := comparison{verb: verb, edited: edited, had: len(c0), has: len(c1), meta: meta != "",
425 base: b1, head: a.head, landings: firstParent[i1 : i0+1]}
426
427 var b strings.Builder
428 if sameDelta {
429 c.kind = compareClean
430 fmt.Fprintf(&b, "%s: %s since %s at %s, with the same file changes.\n", shown, verb, since, short(h0))
431 b.WriteString(meta)
432 landings := firstParent[i1:i0]
433 if !moved {
434 fmt.Fprintf(&b, "Its base is still %s.\n", short(b1))
435 c.text = b.String()
436 return c, nil
437 }
438 fmt.Fprintf(&b, "Main moved %s → %s, landing %s:\n", short(b0), short(b1), counted(len(landings), "commit"))
439 commits, err := readCommits(g, landings)
440 if err != nil {
441 return comparison{}, err
442 }
443 for i := len(commits) - 1; i >= 0; i-- {
444 fmt.Fprintf(&b, " %s %s\n", short(commits[i].oid), visible(commits[i].subject()))
445 }
446 c.text = b.String()
447 return c, nil
448 }
449 c.kind = compareChanged
450 fmt.Fprintf(&b, "%s: %s since %s at %s.\n", shown, verb, since, short(h0))
451 b.WriteString(meta)
452 files := deltaDifferences(d0, d1)
453 paths := make([]string, len(files))
454 for i, f := range files {
455 paths[i] = f.path
456 }
457 edits, err := landingEdits(g, firstParent[i1:i0+1], paths)
458 if err != nil {
459 return comparison{}, err
460 }
461 if verb == "rebased" {
462 if len(c1) == 1 {
463 b.WriteString("Its commit is unchanged: same patch, same message.\n")
464 } else {
465 fmt.Fprintf(&b, "Its %d commits are unchanged: same patches, same messages.\n", len(c1))
466 }
467 for _, f := range files {
468 if len(edits[f.path]) > 0 {
469 c.mainEdited = append(c.mainEdited, f.path)
470 }
471 }
472 touched := len(c.mainEdited)
473 of := fmt.Sprintf("%d of its files", touched)
474 if touched < len(files) {
475 of = fmt.Sprintf("%d of the %d files whose change differs", touched, len(files))
476 }
477 fmt.Fprintf(&b, "Main moved %s → %s and also edited %s:\n", short(b0), short(b1), of)
478 } else {
479 if moved {
480 fmt.Fprintf(&b, "Main moved %s → %s.\n", short(b0), short(b1))
481 } else {
482 fmt.Fprintf(&b, "Its base is still %s.\n", short(b1))
483 }
484 had := ""
485 if len(c0) != len(c1) {
486 had = fmt.Sprintf(" (v%d had %d)", old, len(c0))
487 }
488 differ := fmt.Sprintf("%d files differ", len(files))
489 if len(files) == 1 {
490 differ = "1 file differs"
491 }
492 fmt.Fprintf(&b, "%d of %s changed%s, and %s from v%d:\n", edited, counted(len(c1), "commit"), had, differ, old)
493 }
494 listing, err := fileListing(g, files, edits, moved, a.verbose, old, a.version)
495 if err != nil {
496 return comparison{}, err
497 }
498 b.WriteString(listing)
499 if verb != "rebased" {
500 fmt.Fprintf(&b, "\n── git range-diff %s..%s %s..%s ──\n", short(b0), short(h0), short(b1), short(a.head))
501 out, err := g.output(true, "range-diff", "--no-color", b0+".."+h0, b1+".."+a.head)
502 if err != nil {
503 b.WriteString(" (git range-diff failed; view the full diff)\n")
504 } else {
505 b.WriteString(out + "\n")
506 }
507 }
508 these := fmt.Sprintf("these %d files", len(files))
509 if len(files) == 1 {
510 these = "this file"
511 }
512 fmt.Fprintf(&b, "\n── v%d's diff of %s against main %s ──\n", a.version, these, short(b1))
513 // The prefixes and the options are fixed, so that the person's
514 // configuration cannot change the form review anchors notes by. The
515 // paths are taken literally, as the delta has them, and a rename is a
516 // deletion and an addition, as it is in the delta.
517 out, err := g.output(true, append([]string{"--literal-pathspecs", "diff", "--no-color", "--no-ext-diff", "--no-textconv",
518 "--no-renames", "--no-relative", "--src-prefix=a/", "--dst-prefix=b/", b1, a.head, "--"}, paths...)...)
519 switch {
520 case err != nil:
521 b.WriteString(" (git diff failed; view the full diff)\n")
522 case out == "":
523 fmt.Fprintf(&b, " none: v%d leaves each of them as its base has it.\n", a.version)
524 default:
525 b.WriteString(out + "\n")
526 }
527 c.text = b.String()
528 return c, nil
529}
530
531// uniqueBase is head's merge base with tip, when there is exactly one.
532func uniqueBase(g git, tip, head string) (string, bool) {
533 out, err := g.output(true, "merge-base", "--all", tip, head)
534 bases := strings.Fields(out)
535 if err != nil || len(bases) != 1 {
536 return "", false
537 }
538 return bases[0], true
539}
540
541func indexOf(list []string, s string) int {
542 for i, e := range list {
543 if e == s {
544 return i
545 }
546 }
547 return -1
548}
549
550// fileDifference is a path whose change differs between two deltas, and
551// its change in each: nil where a delta leaves it alone.
552type fileDifference struct {
553 path string
554 old, new *delta.Change
555}
556
557// deltaDifferences are the paths whose change differs between two
558// deltas, sorted. A binary file or a mode that changed is one like any
559// other.
560func deltaDifferences(d0, d1 delta.Delta) []fileDifference {
561 byPath := map[string][2]*delta.Change{}
562 for side, d := range []delta.Delta{d0, d1} {
563 for i := range d {
564 pair := byPath[d[i].Path]
565 pair[side] = &d[i]
566 byPath[d[i].Path] = pair
567 }
568 }
569 var files []fileDifference
570 for p, pair := range byPath {
571 if pair[0] != nil && pair[1] != nil && *pair[0] == *pair[1] {
572 continue
573 }
574 files = append(files, fileDifference{path: p, old: pair[0], new: pair[1]})
575 }
576 sort.Slice(files, func(i, j int) bool { return files[i].path < files[j].path })
577 return files
578}
579
580// fileListing lists the files whose change differs. When main moved,
581// each names the landings that edited it, oldest first, with their
582// subjects cut to fit 100 columns. verbose adds each file's change in
583// each version, as the mode and the first twelve hex digits of the
584// SHA-256 of each image.
585func fileListing(g git, files []fileDifference, edits map[string][]string, moved, verbose bool, old, shown int) (string, error) {
586 var oids []string
587 for _, f := range files {
588 oids = append(oids, edits[f.path]...)
589 }
590 subjects := map[string]string{}
591 commits, err := readCommits(g, oids)
592 if err != nil {
593 return "", err
594 }
595 for _, c := range commits {
596 subjects[c.oid] = visible(c.subject())
597 }
598 width := 0
599 for _, f := range files {
600 width = max(width, columns(quotedPath(f.path)))
601 }
602 var b strings.Builder
603 for _, f := range files {
604 name := quotedPath(f.path)
605 lead := " " + name + strings.Repeat(" ", width-columns(name)) + " "
606 switch {
607 case !moved:
608 b.WriteString(" " + name + "\n")
609 case len(edits[f.path]) == 0:
610 b.WriteString(lead + "not edited on main\n")
611 }
612 for i, oid := range edits[f.path] {
613 if i > 0 {
614 lead = strings.Repeat(" ", columns(lead))
615 }
616 line := short(oid) + " " + subjects[oid]
617 b.WriteString(lead + fit(line, 100-columns(lead)) + "\n")
618 }
619 if verbose {
620 fmt.Fprintf(&b, " v%d: %s\n v%d: %s\n", old, described(f.old), shown, described(f.new))
621 }
622 }
623 return b.String(), nil
624}
625
626// landingEdits maps each path to the landings in chain that edited it,
627// oldest first. chain is main's first-parent history from B₁ down to B₀,
628// so each landing is diffed against the commit after it, its first
629// parent, and B₀ is no landing.
630func landingEdits(g git, chain, paths []string) (map[string][]string, error) {
631 edits := map[string][]string{}
632 if len(chain) < 2 || len(paths) == 0 {
633 return edits, nil
634 }
635 var in strings.Builder
636 landing := map[string]bool{}
637 for k := len(chain) - 2; k >= 0; k-- {
638 fmt.Fprintf(&in, "%s %s\n", chain[k], chain[k+1])
639 landing[chain[k]] = true
640 }
641 out, err := g.input(true, strings.NewReader(in.String()), append([]string{"--literal-pathspecs", "diff-tree", "--stdin",
642 "-r", "--name-only", "-z", "--no-renames", "--no-ext-diff", "--"}, paths...)...)
643 if err != nil {
644 return nil, failure("could not read which landings edited the files")
645 }
646 current := ""
647 for _, field := range strings.Split(out, "\x00") {
648 switch {
649 case landing[field]:
650 current = field
651 case field != "" && current != "":
652 edits[field] = append(edits[field], current)
653 }
654 }
655 return edits, nil
656}
657
658// patchIDs maps each commit to git patch-id --verbatim of its diff from
659// its first parent. The diff is in a fixed form, with binary content,
660// modes and whole object names, so that the person's configuration
661// cannot change it and two commits share an ID only when they make the
662// same edit. A commit whose diff is empty has none.
663func patchIDs(g git, oids []string) (map[string]string, error) {
664 ids := map[string]string{}
665 if len(oids) == 0 {
666 return ids, nil
667 }
668 patches, err := g.input(true, strings.NewReader(strings.Join(oids, "\n")+"\n"), "log", "--stdin", "--no-walk=unsorted",
669 "--no-color", "--no-ext-diff", "--no-textconv", "--no-renames", "--no-relative", "--src-prefix=a/", "--dst-prefix=b/",
670 "--binary", "--full-index", "--diff-merges=first-parent", "--patch", "--format=commit %H")
671 if err != nil {
672 return nil, failure("could not read the commits' patches")
673 }
674 out, err := g.input(true, strings.NewReader(patches+"\n"), "patch-id", "--verbatim")
675 if err != nil {
676 return nil, failure("could not read the commits' patch IDs")
677 }
678 for _, line := range strings.Split(out, "\n") {
679 if id, oid, ok := strings.Cut(line, " "); ok {
680 ids[oid] = id
681 }
682 }
683 return ids, nil
684}
685
686// editedCommits counts the shown version's commits that are not the
687// earlier version's, by patch, message and author. With as many commits
688// on each side, each is set against the one in its place, so commits
689// reordered are edited. Otherwise a commit is edited when no commit of
690// the earlier version is the same.
691func editedCommits(c0, c1 []commitText, ids map[string]string) int {
692 key := func(c commitText) string {
693 return ids[c.oid] + "\x00" + c.encoding + "\x00" + c.author + "\x00" + c.message
694 }
695 n := 0
696 if len(c0) == len(c1) {
697 for i := range c0 {
698 if key(c0[i]) != key(c1[i]) {
699 n++
700 }
701 }
702 return n
703 }
704 left := map[string]int{}
705 for _, c := range c0 {
706 left[key(c)]++
707 }
708 for _, c := range c1 {
709 if left[key(c)] > 0 {
710 left[key(c)]--
711 } else {
712 n++
713 }
714 }
715 return n
716}
717
718func oidsOf(commits []commitText) []string {
719 oids := make([]string, len(commits))
720 for i, c := range commits {
721 oids[i] = c.oid
722 }
723 return oids
724}
725
726// described is a path's change in one delta, or unchanged for none.
727func described(c *delta.Change) string {
728 if c == nil {
729 return "unchanged"
730 }
731 image := func(i delta.Image) string {
732 if i.Absent() {
733 return "absent"
734 }
735 return i.Mode + " " + fmt.Sprintf("%x", i.Sum[:6])
736 }
737 return image(c.Pre) + " -> " + image(c.Post)
738}
739
740// quotedPath is a path as it is printed: as it is when every character is
741// printable, and otherwise in Go's quoting, which escapes the rest.
742func quotedPath(p string) string {
743 if utf8.ValidString(p) && strings.IndexFunc(p, func(r rune) bool { return !strconv.IsPrint(r) }) < 0 {
744 return p
745 }
746 return strconv.Quote(p)
747}
748
749// commitText is one commit object's author and message, as stored.
750type commitText struct {
751 oid, author, message string
752 encoding string // the encoding header, when the commit has one
753}
754
755func (c commitText) subject() string {
756 line, _, _ := strings.Cut(c.message, "\n")
757 return line
758}
759
760// rangeCommits are the commits from base to head, oldest first, read
761// whole.
762func rangeCommits(g git, base, head string) ([]commitText, error) {
763 out, err := g.output(true, "rev-list", "--reverse", base+".."+head)
764 if err != nil {
765 return nil, failure("could not list the commits from " + short(base) + " to " + short(head))
766 }
767 return readCommits(g, strings.Fields(out))
768}
769
770// readCommits reads commit objects with one git cat-file --batch, whose
771// output is read as git wrote it: a message's own trailing newlines are
772// part of the object.
773func readCommits(g git, oids []string) ([]commitText, error) {
774 if len(oids) == 0 {
775 return nil, nil
776 }
777 cmd := exec.Command("git", "cat-file", "--batch")
778 cmd.Env, cmd.Dir = g.env, g.dir
779 cmd.Stdin = strings.NewReader(strings.Join(oids, "\n") + "\n")
780 out, err := cmd.Output()
781 if err != nil {
782 return nil, failure("could not read the commits")
783 }
784 r := bufio.NewReader(bytes.NewReader(out))
785 var commits []commitText
786 for _, oid := range oids {
787 header, err := r.ReadString('\n')
788 fields := strings.Fields(header)
789 if err != nil || len(fields) != 3 || fields[0] != oid || fields[1] != "commit" {
790 return nil, failure("could not read the commit " + oid)
791 }
792 size, err := strconv.Atoi(fields[2])
793 if err != nil || size < 0 {
794 return nil, failure("could not read the commit " + oid)
795 }
796 data := make([]byte, size+1)
797 if _, err := io.ReadFull(r, data); err != nil || data[size] != '\n' {
798 return nil, failure("could not read the commit " + oid)
799 }
800 commits = append(commits, parseCommit(oid, data[:size]))
801 }
802 return commits, nil
803}
804
805// parseCommit reads the author and the message of a commit object: the
806// headers up to the first blank line, and everything after it.
807func parseCommit(oid string, data []byte) commitText {
808 c := commitText{oid: oid}
809 headers, message, _ := bytes.Cut(data, []byte("\n\n"))
810 c.message = string(message)
811 for _, line := range strings.Split(string(headers), "\n") {
812 if v, ok := strings.CutPrefix(line, "author "); ok {
813 c.author = v
814 }
815 if v, ok := strings.CutPrefix(line, "encoding "); ok {
816 c.encoding = v
817 }
818 }
819 return c
820}
821
822// metadataChanges says how the shown version's commits' messages and
823// authors differ from the earlier version's, from each base to its head:
824// nothing when they are the same. since names the earlier version, as
825// "you approved v<n>" or "v<n>". With as many commits on each side, each
826// commit is set against the one in its place, and only those whose
827// message or author differs are shown. Otherwise every commit on each
828// side is, with its author and its message.
829func metadataChanges(c0, c1 []commitText, since string, old, shown int) string {
830 var b strings.Builder
831 author := func(c commitText) string { return " " + visible(c.author) }
832 message := func(c commitText) string {
833 lines := []string{""}
834 if c.encoding != "" {
835 lines = append(lines, " (encoding "+visible(c.encoding)+")")
836 }
837 for _, l := range strings.Split(strings.TrimRight(c.message, "\n"), "\n") {
838 lines = append(lines, " "+visible(l))
839 }
840 return strings.Join(lines, "\n")
841 }
842 entry := func(v int, list []commitText, i int, show func(commitText) string) {
843 fmt.Fprintf(&b, " v%d, commit %d of %d, %s:%s\n", v, i+1, len(list), short(list[i].oid), show(list[i]))
844 }
845 if len(c0) != len(c1) {
846 fmt.Fprintf(&b, "Commits edited since %s: v%d has %s, and v%d had %s. Read their authors and messages before approving:\n",
847 since, shown, counted(len(c1), "commit"), old, counted(len(c0), "commit"))
848 both := func(c commitText) string { return author(c) + message(c) }
849 for i := range c0 {
850 entry(old, c0, i, both)
851 }
852 for i := range c1 {
853 entry(shown, c1, i, both)
854 }
855 return b.String()
856 }
857 for _, field := range []struct {
858 heading string
859 of func(commitText) string
860 show func(commitText) string
861 }{
862 {"Commit messages edited since %s. Read them before approving:\n",
863 func(c commitText) string { return c.encoding + "\x00" + c.message }, message},
864 {"Commit authors edited since %s:\n",
865 func(c commitText) string { return c.author }, author},
866 } {
867 headed := false
868 for i := range c0 {
869 if field.of(c0[i]) == field.of(c1[i]) {
870 continue
871 }
872 if !headed {
873 fmt.Fprintf(&b, field.heading, since)
874 headed = true
875 }
876 entry(old, c0, i, field.show)
877 entry(shown, c1, i, field.show)
878 }
879 }
880 return b.String()
881}