gunk-dev/the-valley

compare.go

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