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