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