| 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. A rebased version then |
| 44 | // shows the diff of those files from B₁ to H₁. |
| 45 | // |
| 46 | // An edited version is set against the approved version carried onto B₁: |
| 47 | // the tree git merge-tree --write-tree -z --merge-base=B₀ B₁ H₀ writes, |
| 48 | // the merge the integrator makes, or H₀'s tree when B₀ is B₁. The page |
| 49 | // holds back what that carry explains, so the carry and every diff read |
| 50 | // from it run in a scratch git directory that shares the clone's object |
| 51 | // store and nothing else (carryGit): no system or global configuration, |
| 52 | // no attributes file and replacement refs off. The person's configuration |
| 53 | // or attributes, a merge=union attribute say, could otherwise resolve a |
| 54 | // conflict silently or change what a diff shows. Each file whose change |
| 55 | // differs is carried unchanged when no conflict names it and the carried |
| 56 | // tree's entry is H₁'s, changed since the approved version when the |
| 57 | // entries differ, and in conflict with main when a message in merge-tree's |
| 58 | // conflict report names it. Then comes git diff from the carried tree to |
| 59 | // H₁ of every path no conflict names: everything the shown version holds |
| 60 | // that the approved version carried mechanically does not. Each |
| 61 | // conflicted path follows: for a lone content conflict whose carried file |
| 62 | // holds conflict markers, its diff from the carried tree to H₁, where the |
| 63 | // removed lines are the two sides and the added lines the resolution; |
| 64 | // otherwise its diff from B₀ to H₀ and from B₁ to H₁, so an approved edit |
| 65 | // the shown version drops is in view. -v adds git range-diff |
| 66 | // B₀..H₀ B₁..H₁, whose hunks carry no line numbers, so a note review takes |
| 67 | // beside them has no anchor. Every other diff is in git's ordinary form, |
| 68 | // so a note taken beside a line of it keeps its file and line. When the |
| 69 | // carry cannot be computed, the page says so and shows every differing |
| 70 | // file's landings, the range-diff and the diff from B₁ to H₁ of those |
| 71 | // files. Either way, a message or an author that differs is shown whatever |
| 72 | // the files say, a message as a line diff of the two. |
| 73 | // |
| 74 | // The output is one line naming the kind, none, clean or changed, and then |
| 75 | // the text review shows, in plain text: style (style.go) styles it for a |
| 76 | // terminal. none has text only when an approved version was found or was |
| 77 | // ambiguous, and says why it is not compared. |
| 78 | |
| 79 | package main |
| 80 | |
| 81 | import ( |
| 82 | "bufio" |
| 83 | "bytes" |
| 84 | "errors" |
| 85 | "fmt" |
| 86 | "io" |
| 87 | "os/exec" |
| 88 | "sort" |
| 89 | "strconv" |
| 90 | "strings" |
| 91 | "unicode/utf8" |
| 92 | |
| 93 | "the-valley/change" |
| 94 | "the-valley/delta" |
| 95 | ) |
| 96 | |
| 97 | // compareUsage is what runCompare, which review calls, takes. |
| 98 | const compareUsage = "compare takes [-v] --tip <commit> <change ID> <version> <head>" |
| 99 | |
| 100 | // The kinds of comparison. |
| 101 | const ( |
| 102 | compareNone = "none" |
| 103 | compareClean = "clean" |
| 104 | compareChanged = "changed" |
| 105 | ) |
| 106 | |
| 107 | // approvalDecisions are the outcomes that judged a request, and so show |
| 108 | // that a head was approved. |
| 109 | var approvalDecisions = map[string]bool{"land": true, "stale": true, "reject": true} |
| 110 | |
| 111 | type compareArgs struct { |
| 112 | tip, id, head string |
| 113 | version int |
| 114 | verbose bool // list each differing file's change as modes and hashes, and the range-diff |
| 115 | } |
| 116 | |
| 117 | func parseCompareArgs(args []string) (compareArgs, error) { |
| 118 | var a compareArgs |
| 119 | var rest []string |
| 120 | for i := 0; i < len(args); i++ { |
| 121 | switch { |
| 122 | case args[i] == "--tip" && i+1 < len(args): |
| 123 | a.tip = args[i+1] |
| 124 | i++ |
| 125 | case strings.HasPrefix(args[i], "--tip="): |
| 126 | a.tip = strings.TrimPrefix(args[i], "--tip=") |
| 127 | case args[i] == "-v": |
| 128 | a.verbose = true |
| 129 | default: |
| 130 | rest = append(rest, args[i]) |
| 131 | } |
| 132 | } |
| 133 | if len(rest) != 3 || !isObjectID(a.tip) || !change.ValidID(rest[0]) || !isObjectID(rest[2]) { |
| 134 | return compareArgs{}, failure(compareUsage) |
| 135 | } |
| 136 | n, err := strconv.Atoi(rest[1]) |
| 137 | if err != nil || n < 1 || strconv.Itoa(n) != rest[1] { |
| 138 | return compareArgs{}, failure(compareUsage) |
| 139 | } |
| 140 | a.id, a.version, a.head = rest[0], n, rest[2] |
| 141 | return a, nil |
| 142 | } |
| 143 | |
| 144 | func runCompare(g git, args []string, w io.Writer) error { |
| 145 | a, err := parseCompareArgs(args) |
| 146 | if err != nil { |
| 147 | return err |
| 148 | } |
| 149 | if !g.succeeds(true, "rev-parse", "--git-dir") { |
| 150 | return failure("not a git repository") |
| 151 | } |
| 152 | if !g.succeeds(true, "cat-file", "-e", a.tip+"^{commit}") { |
| 153 | return failure("the tip " + a.tip + " is no commit here") |
| 154 | } |
| 155 | h, err := readHistory(g, a.id) |
| 156 | if err != nil { |
| 157 | return err |
| 158 | } |
| 159 | kind, text, err := compareVersion(g, h, a) |
| 160 | if err != nil { |
| 161 | return err |
| 162 | } |
| 163 | _, err = fmt.Fprintf(w, "%s\n%s", kind, text) |
| 164 | return err |
| 165 | } |
| 166 | |
| 167 | // history is what origin holds about one change's approvals, read once. |
| 168 | type history struct { |
| 169 | id, handle string |
| 170 | tip string // main on origin; "" when origin has none |
| 171 | versions []change.Version |
| 172 | requests map[string]string // request name → the head its ref names |
| 173 | outcomes map[string]outcome // request name → its outcome record |
| 174 | others map[string]bool // request names something other than this change maps to |
| 175 | unread bool // a record on origin does not read |
| 176 | } |
| 177 | |
| 178 | // outcome is what an outcome record says: the head it judged, and how. |
| 179 | type outcome struct { |
| 180 | head, decision string |
| 181 | } |
| 182 | |
| 183 | // readHistory reads origin once: every branch, record, request and |
| 184 | // outcome. It is the one place this file uses the inventory's readings of |
| 185 | // origin (changes.go, inventory.go, status.go), so moving them changes |
| 186 | // this function and nothing else here. |
| 187 | func readHistory(g git, id string) (*history, error) { |
| 188 | o, err := listOrigin(g, inventoryPatterns...) |
| 189 | if err != nil { |
| 190 | return nil, err |
| 191 | } |
| 192 | all, unread, err := readAll(g, o) |
| 193 | if err != nil { |
| 194 | return nil, err |
| 195 | } |
| 196 | return historyOf(g, o, all, len(unread) > 0, id) |
| 197 | } |
| 198 | |
| 199 | // historyOf is the change's history in what one read of origin listed, o, |
| 200 | // and the records it read, all; unread says a record did not read. |
| 201 | func historyOf(g git, o origin, all []recorded, unread bool, id string) (*history, error) { |
| 202 | var want []string |
| 203 | for ref, oid := range o.refs { |
| 204 | if strings.HasPrefix(ref, outcomePrefix) { |
| 205 | want = append(want, oid) |
| 206 | } |
| 207 | } |
| 208 | if err := fetch(g, want...); err != nil { |
| 209 | return nil, err |
| 210 | } |
| 211 | h := &history{ |
| 212 | id: id, handle: o.handle(id), unread: unread, |
| 213 | requests: map[string]string{}, outcomes: map[string]outcome{}, others: map[string]bool{}, |
| 214 | } |
| 215 | ours := map[string]bool{} |
| 216 | for _, n := range all { |
| 217 | if n.id == id { |
| 218 | h.versions = n.record.Versions |
| 219 | } |
| 220 | } |
| 221 | if h.versions == nil { |
| 222 | return nil, failure("origin holds no record of change " + id) |
| 223 | } |
| 224 | for _, v := range h.versions { |
| 225 | if v.Branch != "" { |
| 226 | ours[v.Branch] = true |
| 227 | } |
| 228 | } |
| 229 | for _, n := range all { |
| 230 | if n.id == id { |
| 231 | continue |
| 232 | } |
| 233 | for _, v := range n.record.Versions { |
| 234 | if v.Branch != "" { |
| 235 | h.others[changeName(v.Branch)] = true |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | for ref, oid := range o.refs { |
| 240 | if ref == "refs/heads/"+recordTarget { |
| 241 | h.tip = oid |
| 242 | } |
| 243 | if branch, ok := strings.CutPrefix(ref, "refs/heads/"); ok && !ours[branch] { |
| 244 | h.others[changeName(branch)] = true |
| 245 | } |
| 246 | if name, ok := strings.CutPrefix(ref, requestPrefix); ok { |
| 247 | h.requests[name] = oid |
| 248 | } |
| 249 | if name, ok := strings.CutPrefix(ref, outcomePrefix); ok { |
| 250 | record, err := g.output(true, "cat-file", "blob", oid) |
| 251 | if err != nil { |
| 252 | record = "" |
| 253 | } |
| 254 | m := parseMemo(record) |
| 255 | h.outcomes[name] = outcome{head: m.head, decision: m.decision} |
| 256 | } |
| 257 | } |
| 258 | return h, nil |
| 259 | } |
| 260 | |
| 261 | // head is version n's head, as an object ID. |
| 262 | func (h *history) head(n int) string { |
| 263 | return strings.TrimPrefix(h.versions[n-1].Head, change.HeadPrefix) |
| 264 | } |
| 265 | |
| 266 | // names are the request names a request for this change may be filed |
| 267 | // under: c-<change ID> first, then each version's branch's, each once. A |
| 268 | // branch whose name maps to c-<ID> adds nothing. That name is reserved |
| 269 | // for the change with that ID, which may be another change, and this |
| 270 | // change's own is already first. |
| 271 | func (h *history) names() []string { |
| 272 | names := []string{change.RequestName(h.id)} |
| 273 | seen := map[string]bool{names[0]: true} |
| 274 | for _, v := range h.versions { |
| 275 | if v.Branch == "" { |
| 276 | continue |
| 277 | } |
| 278 | name := changeName(v.Branch) |
| 279 | if _, reserved := change.RequestID(name); reserved { |
| 280 | continue |
| 281 | } |
| 282 | if !seen[name] { |
| 283 | seen[name] = true |
| 284 | names = append(names, name) |
| 285 | } |
| 286 | } |
| 287 | return names |
| 288 | } |
| 289 | |
| 290 | // ambiguous reports whether a request name may stand for something other |
| 291 | // than this change. c-<change ID> is this change's alone: no branch is |
| 292 | // filed under it. |
| 293 | func (h *history) ambiguous(name string) bool { |
| 294 | return name != change.RequestName(h.id) && (h.unread || h.others[name]) |
| 295 | } |
| 296 | |
| 297 | // reference is the earlier version a version is compared with: the |
| 298 | // approved one, or for carry the one review showed. |
| 299 | type reference struct { |
| 300 | version int // the approved version; 0 for none |
| 301 | by string // the ref that names its head as approved; "" when it is not an approval |
| 302 | unclear string // when there is none: why the approved version is not known, if it may exist |
| 303 | } |
| 304 | |
| 305 | // comparison is what comparing a version with its reference found. |
| 306 | type comparison struct { |
| 307 | kind, text string // text is the opening lines when rest is set |
| 308 | verb string // rebased, edited or recommitted, as the text opens |
| 309 | edited int // the shown version's commits that differ from the earlier version's |
| 310 | had, has int // the earlier and the shown version's commit counts |
| 311 | mainEdited []string // the files whose change differs that a landing in between edited |
| 312 | meta bool // the commits' messages or authors differ |
| 313 | base, head string // the shown version's base and head |
| 314 | landings []string // main's first-parent history from the shown version's base down to the reference's, both included |
| 315 | rest func() (string, error) // the rest of the text, built only when page reads it |
| 316 | } |
| 317 | |
| 318 | // reference finds the approved version below the version shown, as the |
| 319 | // file's comment describes. |
| 320 | func (h *history) reference(shown int) reference { |
| 321 | for m := shown - 1; m >= 1; m-- { |
| 322 | head := h.head(m) |
| 323 | var ambiguousRef string |
| 324 | for _, name := range h.names() { |
| 325 | var refs []string |
| 326 | if h.requests[name] == head { |
| 327 | refs = append(refs, requestPrefix+name) |
| 328 | } |
| 329 | if o, ok := h.outcomes[name]; ok && o.head == head && approvalDecisions[o.decision] { |
| 330 | refs = append(refs, outcomePrefix+name) |
| 331 | } |
| 332 | if len(refs) == 0 { |
| 333 | continue |
| 334 | } |
| 335 | if !h.ambiguous(name) { |
| 336 | return reference{version: m, by: refs[0]} |
| 337 | } |
| 338 | if ambiguousRef == "" { |
| 339 | ambiguousRef = refs[0] |
| 340 | } |
| 341 | } |
| 342 | if ambiguousRef != "" { |
| 343 | return reference{unclear: fmt.Sprintf( |
| 344 | "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", |
| 345 | m, short(head), ambiguousRef, m)} |
| 346 | } |
| 347 | } |
| 348 | return reference{} |
| 349 | } |
| 350 | |
| 351 | // compareVersion compares the version a names with its approved version, |
| 352 | // and returns the kind and the text review shows. |
| 353 | func compareVersion(g git, h *history, a compareArgs) (kind, text string, err error) { |
| 354 | if a.version > len(h.versions) { |
| 355 | return "", "", failure(fmt.Sprintf("change %s has no v%d", h.handle, a.version)) |
| 356 | } |
| 357 | if got := h.head(a.version); got != a.head { |
| 358 | return "", "", failure(fmt.Sprintf("v%d of change %s records the head %s, not %s", a.version, h.handle, got, a.head)) |
| 359 | } |
| 360 | ref := h.reference(a.version) |
| 361 | if ref.version == 0 { |
| 362 | if ref.unclear == "" { |
| 363 | return compareNone, "", nil |
| 364 | } |
| 365 | shown := fmt.Sprintf("%s v%d at %s", h.handle, a.version, short(a.head)) |
| 366 | return compareNone, fmt.Sprintf("%s: %s; reviewing it in full.\n", shown, ref.unclear), nil |
| 367 | } |
| 368 | c, err := compareWith(g, h, a.tip, ref, a.version, a.verbose) |
| 369 | if err != nil { |
| 370 | return "", "", err |
| 371 | } |
| 372 | text, err = c.page() |
| 373 | return c.kind, text, err |
| 374 | } |
| 375 | |
| 376 | // compareWith compares version n with the reference, against main's tip, |
| 377 | // as the file's comment describes. |
| 378 | func compareWith(g git, h *history, tip string, ref reference, n int, verbose bool) (comparison, error) { |
| 379 | a := compareArgs{tip: tip, id: h.id, version: n, head: h.head(n), verbose: verbose} |
| 380 | shown := fmt.Sprintf("%s v%d at %s", h.handle, a.version, short(a.head)) |
| 381 | old := ref.version |
| 382 | h0 := h.head(old) |
| 383 | approved, by := fmt.Sprintf("v%d at %s", old, short(h0)), "" |
| 384 | if ref.by != "" { |
| 385 | approved, by = "approved "+approved, " ("+ref.by+")" |
| 386 | } |
| 387 | withheld := func(why string) (comparison, error) { |
| 388 | return comparison{kind: compareNone, text: fmt.Sprintf("%s: %s%s is not compared, since %s; reviewing it in full.\n", |
| 389 | shown, approved, by, why)}, nil |
| 390 | } |
| 391 | |
| 392 | b0, ok := uniqueBase(g, a.tip, h0) |
| 393 | if !ok { |
| 394 | return withheld(fmt.Sprintf("v%d's merge base with main is not one commit", old)) |
| 395 | } |
| 396 | b1, ok := uniqueBase(g, a.tip, a.head) |
| 397 | if !ok { |
| 398 | return withheld(fmt.Sprintf("v%d's merge base with main is not one commit", a.version)) |
| 399 | } |
| 400 | line, err := g.output(true, "rev-list", "--first-parent", a.tip) |
| 401 | if err != nil { |
| 402 | return comparison{}, failure("could not read main's history") |
| 403 | } |
| 404 | firstParent := strings.Fields(line) |
| 405 | i0, i1 := indexOf(firstParent, b0), indexOf(firstParent, b1) |
| 406 | switch { |
| 407 | case i0 < 0: |
| 408 | return withheld(fmt.Sprintf("v%d's base %s is not on main's first-parent history", old, short(b0))) |
| 409 | case i1 < 0: |
| 410 | return withheld(fmt.Sprintf("v%d's base %s is not on main's first-parent history", a.version, short(b1))) |
| 411 | case i0 < i1: |
| 412 | 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))) |
| 413 | } |
| 414 | repo := delta.Repo{Dir: g.at(), Env: g.env} |
| 415 | d0, err := delta.Between(repo, b0, h0) |
| 416 | if err != nil { |
| 417 | return withheld(fmt.Sprintf("v%d's files do not read as valley-delta-v1: %v", old, err)) |
| 418 | } |
| 419 | d1, err := delta.Between(repo, b1, a.head) |
| 420 | if err != nil { |
| 421 | return withheld(fmt.Sprintf("v%d's files do not read as valley-delta-v1: %v", a.version, err)) |
| 422 | } |
| 423 | c0, err := rangeCommits(g, b0, h0) |
| 424 | if err != nil { |
| 425 | return comparison{}, err |
| 426 | } |
| 427 | c1, err := rangeCommits(g, b1, a.head) |
| 428 | if err != nil { |
| 429 | return comparison{}, err |
| 430 | } |
| 431 | ids, err := patchIDs(g, append(oidsOf(c0), oidsOf(c1)...)) |
| 432 | if err != nil { |
| 433 | return comparison{}, err |
| 434 | } |
| 435 | edited := editedCommits(c0, c1, ids) |
| 436 | moved, sameDelta := b0 != b1, d0.Digest() == d1.Digest() |
| 437 | verb := "edited" |
| 438 | if edited == 0 && len(c0) == len(c1) { |
| 439 | switch { |
| 440 | case moved: |
| 441 | verb = "rebased" |
| 442 | case sameDelta: |
| 443 | verb = "recommitted" |
| 444 | } |
| 445 | } |
| 446 | // since names the earlier version: the one the operator approved, or |
| 447 | // for carry the one review showed. |
| 448 | since := fmt.Sprintf("v%d", old) |
| 449 | if ref.by != "" { |
| 450 | since = "you approved " + since |
| 451 | } |
| 452 | meta := metadataChanges(c0, c1, since, old, a.version) |
| 453 | c := comparison{verb: verb, edited: edited, had: len(c0), has: len(c1), meta: meta != "", |
| 454 | base: b1, head: a.head, landings: firstParent[i1 : i0+1]} |
| 455 | |
| 456 | var b strings.Builder |
| 457 | if sameDelta { |
| 458 | c.kind = compareClean |
| 459 | fmt.Fprintf(&b, "%s: %s since %s at %s, with the same file changes.\n", shown, verb, since, short(h0)) |
| 460 | b.WriteString(meta) |
| 461 | landings := firstParent[i1:i0] |
| 462 | if !moved { |
| 463 | fmt.Fprintf(&b, "Its base is still %s.\n", short(b1)) |
| 464 | c.text = b.String() |
| 465 | return c, nil |
| 466 | } |
| 467 | fmt.Fprintf(&b, "Main moved %s → %s, landing %s:\n", short(b0), short(b1), counted(len(landings), "commit")) |
| 468 | commits, err := readCommits(g, landings) |
| 469 | if err != nil { |
| 470 | return comparison{}, err |
| 471 | } |
| 472 | for i := len(commits) - 1; i >= 0; i-- { |
| 473 | fmt.Fprintf(&b, " %s %s\n", short(commits[i].oid), visible(commits[i].subject())) |
| 474 | } |
| 475 | c.text = b.String() |
| 476 | return c, nil |
| 477 | } |
| 478 | c.kind = compareChanged |
| 479 | fmt.Fprintf(&b, "%s: %s since %s at %s.\n", shown, verb, since, short(h0)) |
| 480 | b.WriteString(meta) |
| 481 | files := deltaDifferences(d0, d1) |
| 482 | paths := make([]string, len(files)) |
| 483 | for i, f := range files { |
| 484 | paths[i] = f.path |
| 485 | } |
| 486 | chain := firstParent[i1 : i0+1] |
| 487 | edits, err := landingEdits(g, chain, paths) |
| 488 | if err != nil { |
| 489 | return comparison{}, err |
| 490 | } |
| 491 | if verb == "rebased" { |
| 492 | if len(c1) == 1 { |
| 493 | b.WriteString("Its commit is unchanged: same patch, same message.\n") |
| 494 | } else { |
| 495 | fmt.Fprintf(&b, "Its %d commits are unchanged: same patches, same messages.\n", len(c1)) |
| 496 | } |
| 497 | for _, f := range files { |
| 498 | if len(edits[f.path]) > 0 { |
| 499 | c.mainEdited = append(c.mainEdited, f.path) |
| 500 | } |
| 501 | } |
| 502 | touched := len(c.mainEdited) |
| 503 | of := fmt.Sprintf("%d of its files", touched) |
| 504 | if touched < len(files) { |
| 505 | of = fmt.Sprintf("%d of the %d files whose change differs", touched, len(files)) |
| 506 | } |
| 507 | fmt.Fprintf(&b, "Main moved %s → %s and also edited %s:\n", short(b0), short(b1), of) |
| 508 | listing, err := fileListing(g, files, edits, moved, a.verbose, old, a.version) |
| 509 | if err != nil { |
| 510 | return comparison{}, err |
| 511 | } |
| 512 | b.WriteString(listing + shownDiff(g, paths, b1, a.head, a.version)) |
| 513 | c.text = b.String() |
| 514 | return c, nil |
| 515 | } |
| 516 | if moved { |
| 517 | fmt.Fprintf(&b, "Main moved %s → %s.\n", short(b0), short(b1)) |
| 518 | } else { |
| 519 | fmt.Fprintf(&b, "Its base is still %s.\n", short(b1)) |
| 520 | } |
| 521 | had := "" |
| 522 | if len(c0) != len(c1) { |
| 523 | had = fmt.Sprintf(" (v%d had %d)", old, len(c0)) |
| 524 | } |
| 525 | differ := fmt.Sprintf("%d files differ", len(files)) |
| 526 | if len(files) == 1 { |
| 527 | differ = "1 file differs" |
| 528 | } |
| 529 | c.text = b.String() |
| 530 | p := editedPage{g: g, d0: d0, d1: d1, b0: b0, b1: b1, h0: h0, h1: a.head, old: old, shown: a.version, |
| 531 | counts: fmt.Sprintf("%d of %s changed%s, and %s from v%d", edited, counted(len(c1), "commit"), had, differ, old), |
| 532 | files: files, edits: edits, chain: chain, moved: moved, verbose: a.verbose} |
| 533 | c.rest = p.text |
| 534 | return c, nil |
| 535 | } |
| 536 | |
| 537 | // page is the comparison's whole text. For an edited version whose files |
| 538 | // differ, the part after the opening lines is built here, so that carry, |
| 539 | // which reads the comparison's other fields alone, makes no merge. |
| 540 | func (c comparison) page() (string, error) { |
| 541 | if c.rest == nil { |
| 542 | return c.text, nil |
| 543 | } |
| 544 | rest, err := c.rest() |
| 545 | return c.text + rest, err |
| 546 | } |
| 547 | |
| 548 | // editedPage is what the page of an edited version whose files differ is |
| 549 | // built from. |
| 550 | type editedPage struct { |
| 551 | g git |
| 552 | d0, d1 delta.Delta |
| 553 | b0, b1, h0, h1 string |
| 554 | old, shown int |
| 555 | counts string // how many commits changed and files differ |
| 556 | files []fileDifference |
| 557 | edits map[string][]string |
| 558 | chain []string |
| 559 | moved, verbose bool |
| 560 | } |
| 561 | |
| 562 | // text is the page after its opening lines, as the file's comment |
| 563 | // describes: the files whose change differs, grouped by how they compare |
| 564 | // with the approved version carried onto main, then what the shown |
| 565 | // version changes beyond that carry, then each conflicted path. |
| 566 | func (p editedPage) text() (string, error) { |
| 567 | cg, done, err := carryGit(p.g) |
| 568 | defer done() |
| 569 | var k carried |
| 570 | if err == nil { |
| 571 | k, err = carry(cg, p.b0, p.b1, p.h0) |
| 572 | } |
| 573 | if err != nil { |
| 574 | return p.fallback(err) |
| 575 | } |
| 576 | out, err := cg.output(true, "diff", "--name-only", "-z", "--no-renames", "--no-relative", "--no-ext-diff", k.tree, p.h1) |
| 577 | if err != nil { |
| 578 | return p.fallback(errors.New("the carried tree does not diff")) |
| 579 | } |
| 580 | changed := map[string]bool{} |
| 581 | var beyond []string |
| 582 | for _, path := range strings.Split(out, "\x00") { |
| 583 | if _, conflicted := k.conflicts[path]; path != "" && !conflicted { |
| 584 | changed[path] = true |
| 585 | beyond = append(beyond, path) |
| 586 | } |
| 587 | } |
| 588 | var same, differ, conflicts []fileDifference |
| 589 | listed := map[string]bool{} |
| 590 | for _, f := range p.files { |
| 591 | listed[f.path] = true |
| 592 | switch _, conflicted := k.conflicts[f.path]; { |
| 593 | case conflicted: |
| 594 | case changed[f.path]: |
| 595 | differ = append(differ, f) |
| 596 | default: |
| 597 | same = append(same, f) |
| 598 | } |
| 599 | } |
| 600 | var unlisted []string |
| 601 | for _, path := range k.paths() { |
| 602 | conflicts = append(conflicts, fileDifference{path: path, old: changeOf(p.d0, path), new: changeOf(p.d1, path)}) |
| 603 | if !listed[path] { |
| 604 | unlisted = append(unlisted, path) |
| 605 | } |
| 606 | } |
| 607 | more, err := landingEdits(p.g, p.chain, unlisted) |
| 608 | if err != nil { |
| 609 | return "", err |
| 610 | } |
| 611 | edits := map[string][]string{} |
| 612 | for _, m := range []map[string][]string{p.edits, more} { |
| 613 | for path, oids := range m { |
| 614 | edits[path] = oids |
| 615 | } |
| 616 | } |
| 617 | |
| 618 | var b strings.Builder |
| 619 | b.WriteString(p.counts + ".\n") |
| 620 | for _, group := range []struct { |
| 621 | files []fileDifference |
| 622 | heading string |
| 623 | landings bool |
| 624 | }{ |
| 625 | {same, "carried unchanged onto main", p.verbose}, |
| 626 | {differ, fmt.Sprintf("changed since v%d", p.old), p.verbose}, |
| 627 | {conflicts, "in conflict with main", true}, |
| 628 | } { |
| 629 | if len(group.files) == 0 { |
| 630 | continue |
| 631 | } |
| 632 | named := edits |
| 633 | if !group.landings { |
| 634 | named = nil |
| 635 | } |
| 636 | listing, err := fileListing(p.g, group.files, named, p.moved && group.landings, p.verbose, p.old, p.shown) |
| 637 | if err != nil { |
| 638 | return "", err |
| 639 | } |
| 640 | fmt.Fprintf(&b, "%s %s:\n%s", counted(len(group.files), "file"), group.heading, listing) |
| 641 | } |
| 642 | if p.verbose { |
| 643 | b.WriteString(p.rangeDiff()) |
| 644 | } |
| 645 | |
| 646 | fmt.Fprintf(&b, "\n── what v%d changes beyond v%d carried onto main %s ──\n", p.shown, p.old, short(p.b1)) |
| 647 | switch { |
| 648 | case len(beyond) > 0: |
| 649 | b.WriteString(diffOf(cg, k.tree, p.h1, beyond)) |
| 650 | case len(conflicts) > 0: |
| 651 | fmt.Fprintf(&b, " none: outside its conflicts with main, v%d is v%d carried onto main and nothing else.\n", p.shown, p.old) |
| 652 | default: |
| 653 | fmt.Fprintf(&b, " none: v%d is v%d carried onto main and nothing else.\n", p.shown, p.old) |
| 654 | } |
| 655 | |
| 656 | for _, f := range conflicts { |
| 657 | types := k.conflicts[f.path] |
| 658 | fmt.Fprintf(&b, "\n── %s: %s ──\n", quotedPath(f.path), strings.Join(types, ", ")) |
| 659 | if len(types) == 1 && types[0] == "CONFLICT (contents)" && holdsMarkers(cg, k.tree, f.path) { |
| 660 | fmt.Fprintf(&b, "Removed: the conflict, main's side and v%d's. Added: v%d's resolution.\n", p.old, p.shown) |
| 661 | if diff := diffOf(cg, k.tree, p.h1, []string{f.path}); diff != "" { |
| 662 | b.WriteString(diff) |
| 663 | } else { |
| 664 | fmt.Fprintf(&b, " none: v%d keeps the conflict as the carry wrote it.\n", p.shown) |
| 665 | } |
| 666 | continue |
| 667 | } |
| 668 | // The approved version's diff is indented: its new side is H₀, |
| 669 | // not the shown head, so review anchors no note to it. |
| 670 | fmt.Fprintf(&b, "v%d's diff against main %s, indented:\n", p.old, short(p.b0)) |
| 671 | if diff := diffOf(cg, p.b0, p.h0, []string{f.path}); diff != "" { |
| 672 | b.WriteString(" " + strings.ReplaceAll(strings.TrimSuffix(diff, "\n"), "\n", "\n ") + "\n") |
| 673 | } else { |
| 674 | fmt.Fprintf(&b, " none: v%d leaves it as main has it.\n", p.old) |
| 675 | } |
| 676 | fmt.Fprintf(&b, "── v%d's diff of %s against main %s ──\n", p.shown, quotedPath(f.path), short(p.b1)) |
| 677 | if diff := diffOf(cg, p.b1, p.h1, []string{f.path}); diff != "" { |
| 678 | b.WriteString(diff) |
| 679 | } else { |
| 680 | fmt.Fprintf(&b, " none: v%d leaves it as main has it.\n", p.shown) |
| 681 | } |
| 682 | } |
| 683 | return b.String(), nil |
| 684 | } |
| 685 | |
| 686 | // fallback is the page when the carry could not be computed: every file |
| 687 | // whose change differs, the range-diff and the shown version's diff of |
| 688 | // those files. |
| 689 | func (p editedPage) fallback(why error) (string, error) { |
| 690 | listing, err := fileListing(p.g, p.files, p.edits, p.moved, p.verbose, p.old, p.shown) |
| 691 | if err != nil { |
| 692 | return "", err |
| 693 | } |
| 694 | paths := make([]string, len(p.files)) |
| 695 | for i, f := range p.files { |
| 696 | paths[i] = f.path |
| 697 | } |
| 698 | return fmt.Sprintf("%s:\n%s\nThe carry of v%d onto main %s could not be computed: %v.\n", p.counts, listing, p.old, short(p.b1), why) + |
| 699 | p.rangeDiff() + shownDiff(p.g, paths, p.b1, p.h1, p.shown), nil |
| 700 | } |
| 701 | |
| 702 | // rangeDiff is git range-diff B₀..H₀ B₁..H₁ under its heading. |
| 703 | func (p editedPage) rangeDiff() string { |
| 704 | s := fmt.Sprintf("\n── git range-diff %s..%s %s..%s ──\n", short(p.b0), short(p.h0), short(p.b1), short(p.h1)) |
| 705 | out, err := p.g.output(true, "range-diff", "--no-color", p.b0+".."+p.h0, p.b1+".."+p.h1) |
| 706 | if err != nil { |
| 707 | return s + " (git range-diff failed; view the full diff)\n" |
| 708 | } |
| 709 | return s + out + "\n" |
| 710 | } |
| 711 | |
| 712 | // shownDiff is the shown version's diff of the paths from its base, under |
| 713 | // its heading. |
| 714 | func shownDiff(g git, paths []string, base, head string, shown int) string { |
| 715 | these := fmt.Sprintf("these %d files", len(paths)) |
| 716 | if len(paths) == 1 { |
| 717 | these = "this file" |
| 718 | } |
| 719 | s := fmt.Sprintf("\n── v%d's diff of %s against main %s ──\n", shown, these, short(base)) |
| 720 | switch diff := diffOf(g, base, head, paths); diff { |
| 721 | case "": |
| 722 | return s + fmt.Sprintf(" none: v%d leaves each of them as its base has it.\n", shown) |
| 723 | default: |
| 724 | return s + diff |
| 725 | } |
| 726 | } |
| 727 | |
| 728 | // diffOf is git diff from one commit or tree to another of the paths, each |
| 729 | // line ending in a newline, or "" when they do not differ. The prefixes |
| 730 | // and the options are fixed, so that the person's configuration cannot |
| 731 | // change the form review anchors notes by. The paths are taken literally, |
| 732 | // as the delta has them, and a rename is a deletion and an addition, as it |
| 733 | // is in the delta. |
| 734 | func diffOf(g git, from, to string, paths []string) string { |
| 735 | out, err := g.output(true, append([]string{"--literal-pathspecs", "diff", "--no-color", "--no-ext-diff", "--no-textconv", |
| 736 | "--no-renames", "--no-relative", "--src-prefix=a/", "--dst-prefix=b/", from, to, "--"}, paths...)...) |
| 737 | switch { |
| 738 | case err != nil: |
| 739 | return " (git diff failed; view the full diff)\n" |
| 740 | case out == "": |
| 741 | return "" |
| 742 | } |
| 743 | return out + "\n" |
| 744 | } |
| 745 | |
| 746 | // holdsMarkers reports whether the tree holds path as text with a |
| 747 | // conflict marker line. |
| 748 | func holdsMarkers(g git, tree, path string) bool { |
| 749 | out, err := g.output(true, "cat-file", "blob", tree+":"+path) |
| 750 | return err == nil && !strings.Contains(out, "\x00") && strings.Contains("\n"+out, "\n<<<<<<< ") |
| 751 | } |
| 752 | |
| 753 | // changeOf is path's change in d, or nil when d leaves it alone. |
| 754 | func changeOf(d delta.Delta, path string) *delta.Change { |
| 755 | for i := range d { |
| 756 | if d[i].Path == path { |
| 757 | return &d[i] |
| 758 | } |
| 759 | } |
| 760 | return nil |
| 761 | } |
| 762 | |
| 763 | // uniqueBase is head's merge base with tip, when there is exactly one. |
| 764 | func uniqueBase(g git, tip, head string) (string, bool) { |
| 765 | out, err := g.output(true, "merge-base", "--all", tip, head) |
| 766 | bases := strings.Fields(out) |
| 767 | if err != nil || len(bases) != 1 { |
| 768 | return "", false |
| 769 | } |
| 770 | return bases[0], true |
| 771 | } |
| 772 | |
| 773 | func indexOf(list []string, s string) int { |
| 774 | for i, e := range list { |
| 775 | if e == s { |
| 776 | return i |
| 777 | } |
| 778 | } |
| 779 | return -1 |
| 780 | } |
| 781 | |
| 782 | // fileDifference is a path whose change differs between two deltas, and |
| 783 | // its change in each: nil where a delta leaves it alone. |
| 784 | type fileDifference struct { |
| 785 | path string |
| 786 | old, new *delta.Change |
| 787 | } |
| 788 | |
| 789 | // deltaDifferences are the paths whose change differs between two |
| 790 | // deltas, sorted. A binary file or a mode that changed is one like any |
| 791 | // other. |
| 792 | func deltaDifferences(d0, d1 delta.Delta) []fileDifference { |
| 793 | byPath := map[string][2]*delta.Change{} |
| 794 | for side, d := range []delta.Delta{d0, d1} { |
| 795 | for i := range d { |
| 796 | pair := byPath[d[i].Path] |
| 797 | pair[side] = &d[i] |
| 798 | byPath[d[i].Path] = pair |
| 799 | } |
| 800 | } |
| 801 | var files []fileDifference |
| 802 | for p, pair := range byPath { |
| 803 | if pair[0] != nil && pair[1] != nil && *pair[0] == *pair[1] { |
| 804 | continue |
| 805 | } |
| 806 | files = append(files, fileDifference{path: p, old: pair[0], new: pair[1]}) |
| 807 | } |
| 808 | sort.Slice(files, func(i, j int) bool { return files[i].path < files[j].path }) |
| 809 | return files |
| 810 | } |
| 811 | |
| 812 | // fileListing lists the files whose change differs. When main moved, |
| 813 | // each names the landings that edited it, oldest first, with their |
| 814 | // subjects cut to fit 100 columns. verbose adds each file's change in |
| 815 | // each version, as the mode and the first twelve hex digits of the |
| 816 | // SHA-256 of each image. |
| 817 | func fileListing(g git, files []fileDifference, edits map[string][]string, moved, verbose bool, old, shown int) (string, error) { |
| 818 | var oids []string |
| 819 | for _, f := range files { |
| 820 | oids = append(oids, edits[f.path]...) |
| 821 | } |
| 822 | subjects := map[string]string{} |
| 823 | commits, err := readCommits(g, oids) |
| 824 | if err != nil { |
| 825 | return "", err |
| 826 | } |
| 827 | for _, c := range commits { |
| 828 | subjects[c.oid] = visible(c.subject()) |
| 829 | } |
| 830 | width := 0 |
| 831 | for _, f := range files { |
| 832 | width = max(width, columns(quotedPath(f.path))) |
| 833 | } |
| 834 | var b strings.Builder |
| 835 | for _, f := range files { |
| 836 | name := quotedPath(f.path) |
| 837 | lead := " " + name + strings.Repeat(" ", width-columns(name)) + " " |
| 838 | switch { |
| 839 | case !moved: |
| 840 | b.WriteString(" " + name + "\n") |
| 841 | case len(edits[f.path]) == 0: |
| 842 | b.WriteString(lead + "not edited on main\n") |
| 843 | } |
| 844 | for i, oid := range edits[f.path] { |
| 845 | if i > 0 { |
| 846 | lead = strings.Repeat(" ", columns(lead)) |
| 847 | } |
| 848 | line := short(oid) + " " + subjects[oid] |
| 849 | b.WriteString(lead + fit(line, 100-columns(lead)) + "\n") |
| 850 | } |
| 851 | if verbose { |
| 852 | fmt.Fprintf(&b, " v%d: %s\n v%d: %s\n", old, described(f.old), shown, described(f.new)) |
| 853 | } |
| 854 | } |
| 855 | return b.String(), nil |
| 856 | } |
| 857 | |
| 858 | // landingEdits maps each path to the landings in chain that edited it, |
| 859 | // oldest first. chain is main's first-parent history from B₁ down to B₀, |
| 860 | // so each landing is diffed against the commit after it, its first |
| 861 | // parent, and B₀ is no landing. |
| 862 | func landingEdits(g git, chain, paths []string) (map[string][]string, error) { |
| 863 | edits := map[string][]string{} |
| 864 | if len(chain) < 2 || len(paths) == 0 { |
| 865 | return edits, nil |
| 866 | } |
| 867 | var in strings.Builder |
| 868 | landing := map[string]bool{} |
| 869 | for k := len(chain) - 2; k >= 0; k-- { |
| 870 | fmt.Fprintf(&in, "%s %s\n", chain[k], chain[k+1]) |
| 871 | landing[chain[k]] = true |
| 872 | } |
| 873 | out, err := g.input(true, strings.NewReader(in.String()), append([]string{"--literal-pathspecs", "diff-tree", "--stdin", |
| 874 | "-r", "--name-only", "-z", "--no-renames", "--no-ext-diff", "--"}, paths...)...) |
| 875 | if err != nil { |
| 876 | return nil, failure("could not read which landings edited the files") |
| 877 | } |
| 878 | current := "" |
| 879 | for _, field := range strings.Split(out, "\x00") { |
| 880 | switch { |
| 881 | case landing[field]: |
| 882 | current = field |
| 883 | case field != "" && current != "": |
| 884 | edits[field] = append(edits[field], current) |
| 885 | } |
| 886 | } |
| 887 | return edits, nil |
| 888 | } |
| 889 | |
| 890 | // patchIDs maps each commit to git patch-id --verbatim of its diff from |
| 891 | // its first parent. The diff is in a fixed form, with binary content, |
| 892 | // modes and whole object names, so that the person's configuration |
| 893 | // cannot change it and two commits share an ID only when they make the |
| 894 | // same edit. A commit whose diff is empty has none. |
| 895 | func patchIDs(g git, oids []string) (map[string]string, error) { |
| 896 | ids := map[string]string{} |
| 897 | if len(oids) == 0 { |
| 898 | return ids, nil |
| 899 | } |
| 900 | patches, err := g.input(true, strings.NewReader(strings.Join(oids, "\n")+"\n"), "log", "--stdin", "--no-walk=unsorted", |
| 901 | "--no-color", "--no-ext-diff", "--no-textconv", "--no-renames", "--no-relative", "--src-prefix=a/", "--dst-prefix=b/", |
| 902 | "--binary", "--full-index", "--diff-merges=first-parent", "--patch", "--format=commit %H") |
| 903 | if err != nil { |
| 904 | return nil, failure("could not read the commits' patches") |
| 905 | } |
| 906 | out, err := g.input(true, strings.NewReader(patches+"\n"), "patch-id", "--verbatim") |
| 907 | if err != nil { |
| 908 | return nil, failure("could not read the commits' patch IDs") |
| 909 | } |
| 910 | for _, line := range strings.Split(out, "\n") { |
| 911 | if id, oid, ok := strings.Cut(line, " "); ok { |
| 912 | ids[oid] = id |
| 913 | } |
| 914 | } |
| 915 | return ids, nil |
| 916 | } |
| 917 | |
| 918 | // editedCommits counts the shown version's commits that are not the |
| 919 | // earlier version's, by patch, message and author. With as many commits |
| 920 | // on each side, each is set against the one in its place, so commits |
| 921 | // reordered are edited. Otherwise a commit is edited when no commit of |
| 922 | // the earlier version is the same. |
| 923 | func editedCommits(c0, c1 []commitText, ids map[string]string) int { |
| 924 | key := func(c commitText) string { |
| 925 | return ids[c.oid] + "\x00" + c.encoding + "\x00" + c.author + "\x00" + c.message |
| 926 | } |
| 927 | n := 0 |
| 928 | if len(c0) == len(c1) { |
| 929 | for i := range c0 { |
| 930 | if key(c0[i]) != key(c1[i]) { |
| 931 | n++ |
| 932 | } |
| 933 | } |
| 934 | return n |
| 935 | } |
| 936 | left := map[string]int{} |
| 937 | for _, c := range c0 { |
| 938 | left[key(c)]++ |
| 939 | } |
| 940 | for _, c := range c1 { |
| 941 | if left[key(c)] > 0 { |
| 942 | left[key(c)]-- |
| 943 | } else { |
| 944 | n++ |
| 945 | } |
| 946 | } |
| 947 | return n |
| 948 | } |
| 949 | |
| 950 | func oidsOf(commits []commitText) []string { |
| 951 | oids := make([]string, len(commits)) |
| 952 | for i, c := range commits { |
| 953 | oids[i] = c.oid |
| 954 | } |
| 955 | return oids |
| 956 | } |
| 957 | |
| 958 | // described is a path's change in one delta, or unchanged for none. |
| 959 | func described(c *delta.Change) string { |
| 960 | if c == nil { |
| 961 | return "unchanged" |
| 962 | } |
| 963 | image := func(i delta.Image) string { |
| 964 | if i.Absent() { |
| 965 | return "absent" |
| 966 | } |
| 967 | return i.Mode + " " + fmt.Sprintf("%x", i.Sum[:6]) |
| 968 | } |
| 969 | return image(c.Pre) + " -> " + image(c.Post) |
| 970 | } |
| 971 | |
| 972 | // quotedPath is a path as it is printed: as it is when every character is |
| 973 | // printable, and otherwise in Go's quoting, which escapes the rest. |
| 974 | func quotedPath(p string) string { |
| 975 | if utf8.ValidString(p) && strings.IndexFunc(p, func(r rune) bool { return !strconv.IsPrint(r) }) < 0 { |
| 976 | return p |
| 977 | } |
| 978 | return strconv.Quote(p) |
| 979 | } |
| 980 | |
| 981 | // commitText is one commit object's author and message, as stored. |
| 982 | type commitText struct { |
| 983 | oid, author, message string |
| 984 | encoding string // the encoding header, when the commit has one |
| 985 | } |
| 986 | |
| 987 | func (c commitText) subject() string { |
| 988 | line, _, _ := strings.Cut(c.message, "\n") |
| 989 | return line |
| 990 | } |
| 991 | |
| 992 | // rangeCommits are the commits from base to head, oldest first, read |
| 993 | // whole. |
| 994 | func rangeCommits(g git, base, head string) ([]commitText, error) { |
| 995 | out, err := g.output(true, "rev-list", "--reverse", base+".."+head) |
| 996 | if err != nil { |
| 997 | return nil, failure("could not list the commits from " + short(base) + " to " + short(head)) |
| 998 | } |
| 999 | return readCommits(g, strings.Fields(out)) |
| 1000 | } |
| 1001 | |
| 1002 | // readCommits reads commit objects with one git cat-file --batch, whose |
| 1003 | // output is read as git wrote it: a message's own trailing newlines are |
| 1004 | // part of the object. |
| 1005 | func readCommits(g git, oids []string) ([]commitText, error) { |
| 1006 | if len(oids) == 0 { |
| 1007 | return nil, nil |
| 1008 | } |
| 1009 | cmd := exec.Command("git", "cat-file", "--batch") |
| 1010 | cmd.Env, cmd.Dir = g.env, g.at() |
| 1011 | cmd.Stdin = strings.NewReader(strings.Join(oids, "\n") + "\n") |
| 1012 | out, err := cmd.Output() |
| 1013 | if err != nil { |
| 1014 | return nil, failure("could not read the commits") |
| 1015 | } |
| 1016 | r := bufio.NewReader(bytes.NewReader(out)) |
| 1017 | var commits []commitText |
| 1018 | for _, oid := range oids { |
| 1019 | header, err := r.ReadString('\n') |
| 1020 | fields := strings.Fields(header) |
| 1021 | if err != nil || len(fields) != 3 || fields[0] != oid || fields[1] != "commit" { |
| 1022 | return nil, failure("could not read the commit " + oid) |
| 1023 | } |
| 1024 | size, err := strconv.Atoi(fields[2]) |
| 1025 | if err != nil || size < 0 { |
| 1026 | return nil, failure("could not read the commit " + oid) |
| 1027 | } |
| 1028 | data := make([]byte, size+1) |
| 1029 | if _, err := io.ReadFull(r, data); err != nil || data[size] != '\n' { |
| 1030 | return nil, failure("could not read the commit " + oid) |
| 1031 | } |
| 1032 | commits = append(commits, parseCommit(oid, data[:size])) |
| 1033 | } |
| 1034 | return commits, nil |
| 1035 | } |
| 1036 | |
| 1037 | // parseCommit reads the author and the message of a commit object: the |
| 1038 | // headers up to the first blank line, and everything after it. |
| 1039 | func parseCommit(oid string, data []byte) commitText { |
| 1040 | c := commitText{oid: oid} |
| 1041 | headers, message, _ := bytes.Cut(data, []byte("\n\n")) |
| 1042 | c.message = string(message) |
| 1043 | for _, line := range strings.Split(string(headers), "\n") { |
| 1044 | if v, ok := strings.CutPrefix(line, "author "); ok { |
| 1045 | c.author = v |
| 1046 | } |
| 1047 | if v, ok := strings.CutPrefix(line, "encoding "); ok { |
| 1048 | c.encoding = v |
| 1049 | } |
| 1050 | } |
| 1051 | return c |
| 1052 | } |
| 1053 | |
| 1054 | // metadataChanges says how the shown version's commits' messages and |
| 1055 | // authors differ from the earlier version's, from each base to its head: |
| 1056 | // nothing when they are the same. since names the earlier version, as |
| 1057 | // "you approved v<n>" or "v<n>". With as many commits on each side, each |
| 1058 | // commit is set against the one in its place, and only those whose |
| 1059 | // message or author differs are shown. Otherwise every commit on each |
| 1060 | // side is, with its author and its message. A message that differs, in |
| 1061 | // the same encoding on each side, shows as a line diff of the two. |
| 1062 | func metadataChanges(c0, c1 []commitText, since string, old, shown int) string { |
| 1063 | var b strings.Builder |
| 1064 | author := func(c commitText) string { return " " + visible(c.author) } |
| 1065 | message := func(c commitText) string { |
| 1066 | lines := []string{""} |
| 1067 | if c.encoding != "" { |
| 1068 | lines = append(lines, " (encoding "+visible(c.encoding)+")") |
| 1069 | } |
| 1070 | for _, l := range strings.Split(strings.TrimRight(c.message, "\n"), "\n") { |
| 1071 | lines = append(lines, " "+visible(l)) |
| 1072 | } |
| 1073 | return strings.Join(lines, "\n") |
| 1074 | } |
| 1075 | entry := func(v int, list []commitText, i int, show func(commitText) string) { |
| 1076 | fmt.Fprintf(&b, " v%d, commit %d of %d, %s:%s\n", v, i+1, len(list), short(list[i].oid), show(list[i])) |
| 1077 | } |
| 1078 | if len(c0) != len(c1) { |
| 1079 | fmt.Fprintf(&b, "Commits edited since %s: v%d has %s, and v%d had %s. Read their authors and messages before approving:\n", |
| 1080 | since, shown, counted(len(c1), "commit"), old, counted(len(c0), "commit")) |
| 1081 | both := func(c commitText) string { return author(c) + message(c) } |
| 1082 | for i := range c0 { |
| 1083 | entry(old, c0, i, both) |
| 1084 | } |
| 1085 | for i := range c1 { |
| 1086 | entry(shown, c1, i, both) |
| 1087 | } |
| 1088 | return b.String() |
| 1089 | } |
| 1090 | for _, field := range []struct { |
| 1091 | heading string |
| 1092 | of func(commitText) string |
| 1093 | show func(commitText) string |
| 1094 | diff bool // a message in one encoding on each side shows as a line diff |
| 1095 | }{ |
| 1096 | {"Commit messages edited since %s. Read them before approving:\n", |
| 1097 | func(c commitText) string { return c.encoding + "\x00" + c.message }, message, true}, |
| 1098 | {"Commit authors edited since %s:\n", |
| 1099 | func(c commitText) string { return c.author }, author, false}, |
| 1100 | } { |
| 1101 | headed := false |
| 1102 | for i := range c0 { |
| 1103 | if field.of(c0[i]) == field.of(c1[i]) { |
| 1104 | continue |
| 1105 | } |
| 1106 | if !headed { |
| 1107 | fmt.Fprintf(&b, field.heading, since) |
| 1108 | headed = true |
| 1109 | } |
| 1110 | if diff, ok := messageDiff(c0[i].message, c1[i].message); field.diff && ok && c0[i].encoding == c1[i].encoding { |
| 1111 | fmt.Fprintf(&b, " commit %d of %d, v%d %s → v%d %s:\n%s", i+1, len(c0), old, short(c0[i].oid), shown, short(c1[i].oid), diff) |
| 1112 | continue |
| 1113 | } |
| 1114 | entry(old, c0, i, field.show) |
| 1115 | entry(shown, c1, i, field.show) |
| 1116 | } |
| 1117 | } |
| 1118 | return b.String() |
| 1119 | } |
| 1120 | |
| 1121 | // messageContext is how many unchanged lines a message's line diff shows |
| 1122 | // on each side of a changed one. |
| 1123 | const messageContext = 3 |
| 1124 | |
| 1125 | // messageDiffCells bounds the table lineDiff fills for the lines two |
| 1126 | // messages do not share at either end: a million cells, eight megabytes. |
| 1127 | // Past it a message prints in full. |
| 1128 | const messageDiffCells = 1 << 20 |
| 1129 | |
| 1130 | // messageDiff is a line diff of two messages: each line indented four |
| 1131 | // spaces and marked -, + or, for an unchanged line, a space. Unchanged |
| 1132 | // lines further than messageContext from a change are counted, not shown. |
| 1133 | // ok is false when the diff is past messageDiffCells, or when the |
| 1134 | // messages differ only in trailing newlines, which a line diff would not |
| 1135 | // show. |
| 1136 | func messageDiff(a, b string) (diff string, ok bool) { |
| 1137 | if strings.TrimRight(a, "\n") == strings.TrimRight(b, "\n") { |
| 1138 | return "", false |
| 1139 | } |
| 1140 | x, y := strings.Split(strings.TrimRight(a, "\n"), "\n"), strings.Split(strings.TrimRight(b, "\n"), "\n") |
| 1141 | head := 0 |
| 1142 | for head < min(len(x), len(y)) && x[head] == y[head] { |
| 1143 | head++ |
| 1144 | } |
| 1145 | tail := 0 |
| 1146 | for tail < min(len(x), len(y))-head && x[len(x)-1-tail] == y[len(y)-1-tail] { |
| 1147 | tail++ |
| 1148 | } |
| 1149 | if (len(x)-head-tail+1)*(len(y)-head-tail+1) > messageDiffCells { |
| 1150 | return "", false |
| 1151 | } |
| 1152 | var ops []string |
| 1153 | for _, l := range x[:head] { |
| 1154 | ops = append(ops, " "+l) |
| 1155 | } |
| 1156 | ops = append(ops, lineDiff(x[head:len(x)-tail], y[head:len(y)-tail])...) |
| 1157 | for _, l := range x[len(x)-tail:] { |
| 1158 | ops = append(ops, " "+l) |
| 1159 | } |
| 1160 | near := make([]bool, len(ops)) |
| 1161 | for i, op := range ops { |
| 1162 | if op[0] != ' ' { |
| 1163 | for j := max(0, i-messageContext); j <= min(len(ops)-1, i+messageContext); j++ { |
| 1164 | near[j] = true |
| 1165 | } |
| 1166 | } |
| 1167 | } |
| 1168 | var s strings.Builder |
| 1169 | for i := 0; i < len(ops); { |
| 1170 | if near[i] { |
| 1171 | s.WriteString(" " + ops[i][:1] + visible(ops[i][1:]) + "\n") |
| 1172 | i++ |
| 1173 | continue |
| 1174 | } |
| 1175 | j := i |
| 1176 | for j < len(ops) && !near[j] { |
| 1177 | j++ |
| 1178 | } |
| 1179 | fmt.Fprintf(&s, " (%s)\n", counted(j-i, "unchanged line")) |
| 1180 | i = j |
| 1181 | } |
| 1182 | return s.String(), true |
| 1183 | } |
| 1184 | |
| 1185 | // lineDiff is a shortest edit from lines a to lines b, each line marked |
| 1186 | // "-" for a's alone, "+" for b's alone or " " for both, a's before b's |
| 1187 | // within a change. |
| 1188 | func lineDiff(a, b []string) []string { |
| 1189 | // common[i][j] is the length of the longest common subsequence of |
| 1190 | // a[i:] and b[j:]. |
| 1191 | common := make([][]int, len(a)+1) |
| 1192 | for i := range common { |
| 1193 | common[i] = make([]int, len(b)+1) |
| 1194 | } |
| 1195 | for i := len(a) - 1; i >= 0; i-- { |
| 1196 | for j := len(b) - 1; j >= 0; j-- { |
| 1197 | if a[i] == b[j] { |
| 1198 | common[i][j] = common[i+1][j+1] + 1 |
| 1199 | } else { |
| 1200 | common[i][j] = max(common[i+1][j], common[i][j+1]) |
| 1201 | } |
| 1202 | } |
| 1203 | } |
| 1204 | var ops []string |
| 1205 | i, j := 0, 0 |
| 1206 | for i < len(a) || j < len(b) { |
| 1207 | switch { |
| 1208 | case i < len(a) && j < len(b) && a[i] == b[j]: |
| 1209 | ops = append(ops, " "+a[i]) |
| 1210 | i, j = i+1, j+1 |
| 1211 | case j == len(b) || i < len(a) && common[i+1][j] >= common[i][j+1]: |
| 1212 | ops = append(ops, "-"+a[i]) |
| 1213 | i++ |
| 1214 | default: |
| 1215 | ops = append(ops, "+"+b[j]) |
| 1216 | j++ |
| 1217 | } |
| 1218 | } |
| 1219 | return ops |
| 1220 | } |