| 1 | // Changes and their records on origin. |
| 2 | // |
| 3 | // A change is named in one of three ways, and every verb that takes a |
| 4 | // change takes all three: |
| 5 | // |
| 6 | // - its full change ID, 32 letters from k to z; |
| 7 | // - its handle: the shortest prefix of its ID, four letters at least, |
| 8 | // that no other change recorded on origin shares; |
| 9 | // - its handle qualified by this repository's name, <repo>/<handle>, |
| 10 | // the way changes and pending write the handle of a change ID that |
| 11 | // several repositories record; |
| 12 | // - its branch, the way changes were named before they had records. |
| 13 | // |
| 14 | // A name shaped like a handle is looked up among origin's records first. |
| 15 | // When it matches no record, it is a branch name. A name written as |
| 16 | // origin/<branch> is always a branch name. A handle that is also the name |
| 17 | // of a branch on origin is refused unless the change is on that branch, |
| 18 | // because the two could be different changes. |
| 19 | // |
| 20 | // The verbs that act on a change read a branch name further: the branch is |
| 21 | // the change whose active version is on it, when exactly one is |
| 22 | // (resolveRecorded). So how a change is named never decides whether its |
| 23 | // record is read. A change whose active version has landed, by the first |
| 24 | // two landing rules (inventory.go), is not on its branch for this while |
| 25 | // the branch is still at that version's head, so a branch name can be |
| 26 | // used again once its change has landed. A branch that has moved since |
| 27 | // names the change as before. |
| 28 | |
| 29 | package main |
| 30 | |
| 31 | import ( |
| 32 | "bytes" |
| 33 | "fmt" |
| 34 | "io" |
| 35 | "sort" |
| 36 | "strings" |
| 37 | |
| 38 | "the-valley/change" |
| 39 | ) |
| 40 | |
| 41 | // recordTarget is the one target a change may name for now. The hook |
| 42 | // refuses a record for any other. |
| 43 | const recordTarget = "main" |
| 44 | |
| 45 | // origin is one ls-remote snapshot of the refs a verb reads. |
| 46 | type origin struct { |
| 47 | refs map[string]string // ref → object ID |
| 48 | } |
| 49 | |
| 50 | // listOrigin takes one snapshot of origin's refs matching the patterns. |
| 51 | // ls-remote matches a pattern against the tail of a ref name, so every ref |
| 52 | // is compared whole afterwards. |
| 53 | func listOrigin(g git, patterns ...string) (origin, error) { |
| 54 | out, err := g.output(false, append([]string{"ls-remote", "--refs", "origin"}, patterns...)...) |
| 55 | if err != nil { |
| 56 | return origin{}, failure("could not read origin") |
| 57 | } |
| 58 | o := origin{refs: map[string]string{}} |
| 59 | for _, line := range strings.Split(out, "\n") { |
| 60 | oid, ref, ok := strings.Cut(line, "\t") |
| 61 | if ok && ref != "" { |
| 62 | o.refs[ref] = oid |
| 63 | } |
| 64 | } |
| 65 | return o, nil |
| 66 | } |
| 67 | |
| 68 | // recordPatterns are the ls-remote patterns that list every record. |
| 69 | var recordPatterns = []string{change.RefPrefix + recordTarget + "/*"} |
| 70 | |
| 71 | // changes is the ID of every change origin holds a record for, in order. |
| 72 | func (o origin) changes() []string { |
| 73 | var ids []string |
| 74 | for ref := range o.refs { |
| 75 | if target, id, ok := change.ParseRef(ref); ok && target == recordTarget { |
| 76 | ids = append(ids, id) |
| 77 | } |
| 78 | } |
| 79 | sort.Strings(ids) |
| 80 | return ids |
| 81 | } |
| 82 | |
| 83 | // handle is the change's handle among the changes origin holds, and this |
| 84 | // one, which may not be among them yet. |
| 85 | func (o origin) handle(id string) string { |
| 86 | return change.Handle(id, append(o.changes(), id)) |
| 87 | } |
| 88 | |
| 89 | // fetch brings the objects named into this checkout's object store, |
| 90 | // without writing FETCH_HEAD, moving a ref or fetching tags. An object |
| 91 | // already here is not asked for: a fetch brings an object with everything |
| 92 | // it reaches, so one that is here has what it reaches here too. |
| 93 | func fetch(g git, oids ...string) error { |
| 94 | var query bytes.Buffer |
| 95 | for _, oid := range oids { |
| 96 | if oid != "" { |
| 97 | fmt.Fprintln(&query, oid) |
| 98 | } |
| 99 | } |
| 100 | if query.Len() == 0 { |
| 101 | return nil |
| 102 | } |
| 103 | present, _ := g.input(true, &query, "cat-file", "--batch-check=%(objectname)") |
| 104 | here := map[string]bool{} |
| 105 | for _, line := range strings.Split(present, "\n") { |
| 106 | here[line] = true |
| 107 | } |
| 108 | var stdin bytes.Buffer |
| 109 | for _, oid := range oids { |
| 110 | if oid != "" && !here[oid] { |
| 111 | fmt.Fprintln(&stdin, oid) |
| 112 | } |
| 113 | } |
| 114 | if stdin.Len() == 0 { |
| 115 | return nil |
| 116 | } |
| 117 | _, err := g.input(false, &stdin, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--stdin", "origin") |
| 118 | if err != nil { |
| 119 | return failure("could not fetch from origin") |
| 120 | } |
| 121 | return nil |
| 122 | } |
| 123 | |
| 124 | // readRecord reads the record a record commit holds. The commit must have |
| 125 | // been fetched. |
| 126 | func readRecord(g git, commit string) (*change.Record, error) { |
| 127 | data, err := g.output(true, "cat-file", "blob", commit+":record.json") |
| 128 | if err != nil { |
| 129 | return nil, failure(fmt.Sprintf("the change record %s holds no record.json", short(commit))) |
| 130 | } |
| 131 | r, err := change.Parse([]byte(data + "\n")) |
| 132 | if err != nil { |
| 133 | return nil, failure(fmt.Sprintf("the change record %s does not read: %v", short(commit), err)) |
| 134 | } |
| 135 | return r, nil |
| 136 | } |
| 137 | |
| 138 | // recorded is a change that a name resolved to: its ID, and its record on |
| 139 | // origin. |
| 140 | type recorded struct { |
| 141 | id string |
| 142 | commit string // the record commit origin's ref points at |
| 143 | record *change.Record |
| 144 | } |
| 145 | |
| 146 | // lookup resolves a name to a change origin holds a record for. found is |
| 147 | // false when the name is a branch name rather than a change's: it is |
| 148 | // written as origin/<branch>, it has no handle's shape, or it matches no |
| 149 | // record. A name that matches more than one record is refused. |
| 150 | func lookup(g git, o origin, name string) (n recorded, found bool, err error) { |
| 151 | handle, ok := handlePart(g, name) |
| 152 | if strings.HasPrefix(name, "origin/") || !ok { |
| 153 | return recorded{}, false, nil |
| 154 | } |
| 155 | ids := o.changes() |
| 156 | matches := change.Matching(handle, ids) |
| 157 | switch { |
| 158 | case len(matches) == 0: |
| 159 | return recorded{}, false, nil |
| 160 | case len(matches) > 1: |
| 161 | var handles []string |
| 162 | for _, id := range matches { |
| 163 | handles = append(handles, change.Handle(id, ids)) |
| 164 | } |
| 165 | return recorded{}, false, failure(fmt.Sprintf("%s could name any of the changes %s; give more of its ID", |
| 166 | name, strings.Join(handles, ", "))) |
| 167 | } |
| 168 | n = recorded{id: matches[0], commit: o.refs[change.Ref(recordTarget, matches[0])]} |
| 169 | if err := fetch(g, n.commit); err != nil { |
| 170 | return recorded{}, false, err |
| 171 | } |
| 172 | if n.record, err = readRecord(g, n.commit); err != nil { |
| 173 | return recorded{}, false, err |
| 174 | } |
| 175 | if branch := n.record.ActiveVersion().Branch; o.refs["refs/heads/"+name] != "" && branch != name { |
| 176 | return recorded{}, false, failure(fmt.Sprintf("%s is a branch on origin and the handle of the change %s; name the branch as origin/%s, or the change by its full ID", |
| 177 | name, n.id, name)) |
| 178 | } |
| 179 | return n, true, nil |
| 180 | } |
| 181 | |
| 182 | // handlePart is the handle a name gives, when it has a handle's shape: the |
| 183 | // name itself, or what follows the slash in a name written |
| 184 | // <repo>/<handle>, when <repo> is this repository's name. changes and |
| 185 | // pending qualify a handle that way when one change ID is recorded in |
| 186 | // several repositories they list. A qualified name that matches no record |
| 187 | // is a branch name, like any other handle. |
| 188 | func handlePart(g git, name string) (string, bool) { |
| 189 | if change.LooksLikeHandle(name) { |
| 190 | return name, true |
| 191 | } |
| 192 | repo, handle, ok := strings.Cut(name, "/") |
| 193 | if ok && repo != "origin" && change.LooksLikeHandle(handle) && repo == project(g) { |
| 194 | return handle, true |
| 195 | } |
| 196 | return "", false |
| 197 | } |
| 198 | |
| 199 | // resolution is what the name of a change stands for. A name that is a |
| 200 | // branch's sets branch alone. A name that is a change's sets every field |
| 201 | // from the change's record on origin: the active version, the head that |
| 202 | // version names, the branch it names, and the change's state. |
| 203 | type resolution struct { |
| 204 | id, handle, head, branch, state string |
| 205 | version int |
| 206 | } |
| 207 | |
| 208 | // resolve reads a change's name, as status does. A name with no handle's |
| 209 | // shape is a branch name without origin being read. A change whose active |
| 210 | // version names no branch is refused, since every verb that resolves a |
| 211 | // name acts on a branch too. |
| 212 | func resolve(g git, name string) (resolution, error) { |
| 213 | if _, ok := handlePart(g, name); strings.HasPrefix(name, "origin/") || !ok { |
| 214 | return resolution{branch: strings.TrimPrefix(name, "origin/")}, nil |
| 215 | } |
| 216 | o, err := listOrigin(g, append([]string{"refs/heads/" + name}, recordPatterns...)...) |
| 217 | if err != nil { |
| 218 | return resolution{}, err |
| 219 | } |
| 220 | n, found, err := lookup(g, o, name) |
| 221 | switch { |
| 222 | case err != nil: |
| 223 | return resolution{}, err |
| 224 | case !found: |
| 225 | return resolution{branch: name}, nil |
| 226 | } |
| 227 | return o.resolution(n) |
| 228 | } |
| 229 | |
| 230 | // resolveRecorded reads a change's name for the verbs that act on a |
| 231 | // change: review, approve and rebase, through runResolve. A name that is a |
| 232 | // change's ID or handle is that change, as resolve reads it. A branch name, |
| 233 | // written as <branch> or origin/<branch>, is read against the branch each |
| 234 | // record's active version names. No record on the branch leaves the name a |
| 235 | // branch, as it was before changes had records. One record makes the name |
| 236 | // that record's change, exactly as if its ID had been given. More than one |
| 237 | // is refused, since acting on the branch would act on any of them. |
| 238 | func resolveRecorded(g git, name string) (resolution, error) { |
| 239 | branch := strings.TrimPrefix(name, "origin/") |
| 240 | o, err := listOrigin(g, append([]string{"refs/heads/" + branch}, inventoryPatterns...)...) |
| 241 | if err != nil { |
| 242 | return resolution{}, err |
| 243 | } |
| 244 | if !strings.HasPrefix(name, "origin/") { |
| 245 | n, found, err := lookup(g, o, name) |
| 246 | switch { |
| 247 | case err != nil: |
| 248 | return resolution{}, err |
| 249 | case found: |
| 250 | return o.resolution(n) |
| 251 | } |
| 252 | } |
| 253 | found, err := unlandedOn(g, o, branch) |
| 254 | if err != nil { |
| 255 | return resolution{}, err |
| 256 | } |
| 257 | switch len(found) { |
| 258 | case 0: |
| 259 | return resolution{branch: branch}, nil |
| 260 | case 1: |
| 261 | return o.resolution(found[0]) |
| 262 | } |
| 263 | var ids []string |
| 264 | for _, n := range found { |
| 265 | ids = append(ids, n.id) |
| 266 | } |
| 267 | return resolution{}, failure(fmt.Sprintf("the changes %s all have their active version on %s; name one by its change ID", |
| 268 | strings.Join(ids, ", "), branch)) |
| 269 | } |
| 270 | |
| 271 | // resolution is what a change's record says its name stands for: the |
| 272 | // active version, the head that version names, the branch it names, and |
| 273 | // the change's state. |
| 274 | func (o origin) resolution(n recorded) (resolution, error) { |
| 275 | v := n.record.ActiveVersion() |
| 276 | r := resolution{ |
| 277 | id: n.id, handle: o.handle(n.id), version: v.N, |
| 278 | head: strings.TrimPrefix(v.Head, change.HeadPrefix), branch: v.Branch, state: n.record.State, |
| 279 | } |
| 280 | if r.branch == "" { |
| 281 | return resolution{}, failure(fmt.Sprintf("the change %s names no branch at v%d, so there is no branch to act on", r.handle, v.N)) |
| 282 | } |
| 283 | return r, nil |
| 284 | } |
| 285 | |
| 286 | // unlandedOn is every change origin holds a record of whose active |
| 287 | // version names branch, less each whose active version has landed while |
| 288 | // the branch's tip on origin is still that version's head. o must list |
| 289 | // inventoryPatterns. |
| 290 | // Landing is read only for a change on the branch, so a name no record is |
| 291 | // on costs no more than reading the records. |
| 292 | func unlandedOn(g git, o origin, branch string) ([]recorded, error) { |
| 293 | all, err := readAll(g, o) |
| 294 | if err != nil { |
| 295 | return nil, err |
| 296 | } |
| 297 | var on []recorded |
| 298 | for _, n := range all { |
| 299 | if n.record.ActiveVersion().Branch == branch { |
| 300 | on = append(on, n) |
| 301 | } |
| 302 | } |
| 303 | if len(on) == 0 { |
| 304 | return nil, nil |
| 305 | } |
| 306 | var want []string |
| 307 | for ref, oid := range o.refs { |
| 308 | if ref == "refs/heads/"+recordTarget || strings.HasPrefix(ref, outcomePrefix) { |
| 309 | want = append(want, oid) |
| 310 | } |
| 311 | } |
| 312 | if err := fetch(g, want...); err != nil { |
| 313 | return nil, err |
| 314 | } |
| 315 | s := newSnapshot(g, o, all, verifierFromEnv()) |
| 316 | var found []recorded |
| 317 | tip := o.refs["refs/heads/"+branch] |
| 318 | for _, n := range on { |
| 319 | v := n.record.ActiveVersion() |
| 320 | if tip != headOf(v) || !s.isLanded(n.id, v) { |
| 321 | found = append(found, n) |
| 322 | } |
| 323 | } |
| 324 | return found, nil |
| 325 | } |
| 326 | |
| 327 | // resolveBranch is the branch a change is on: the branch its active |
| 328 | // version names, when the name is a change's, and otherwise the name |
| 329 | // itself, as a branch name. |
| 330 | func resolveBranch(g git, name string) (string, error) { |
| 331 | r, err := resolve(g, name) |
| 332 | return r.branch, err |
| 333 | } |
| 334 | |
| 335 | // runResolve prints what a change's name stands for, for the verbs |
| 336 | // bin/valley runs itself, as resolveRecorded reads it: one line of fields |
| 337 | // separated by tabs. For a change it is |
| 338 | // |
| 339 | // change <ID> <handle> <version> <head> <branch> <state> |
| 340 | // |
| 341 | // with the head as a full object ID, and the state as the record says it: |
| 342 | // ready, draft or withdrawn. For a branch it is |
| 343 | // |
| 344 | // branch <branch> |
| 345 | // |
| 346 | // A branch name holds no tab, since git refuses control characters in a |
| 347 | // ref name. The record commit, which has the head as a parent, has been |
| 348 | // fetched, so the head is in this checkout's objects. |
| 349 | func runResolve(g git, args []string, w io.Writer) error { |
| 350 | if len(args) != 1 { |
| 351 | return failure("usage: valley-go resolve <change>") |
| 352 | } |
| 353 | if !g.succeeds(true, "rev-parse", "--git-dir") { |
| 354 | return failure("not a git repository") |
| 355 | } |
| 356 | r, err := resolveRecorded(g, args[0]) |
| 357 | if err != nil { |
| 358 | return err |
| 359 | } |
| 360 | if r.id == "" { |
| 361 | _, err = fmt.Fprintf(w, "branch\t%s\n", r.branch) |
| 362 | return err |
| 363 | } |
| 364 | _, err = fmt.Fprintf(w, "change\t%s\t%s\t%d\t%s\t%s\t%s\n", r.id, r.handle, r.version, r.head, r.branch, r.state) |
| 365 | return err |
| 366 | } |
| 367 | |
| 368 | // readAll reads every record origin holds, in the order of their IDs. |
| 369 | func readAll(g git, o origin) ([]recorded, error) { |
| 370 | ids := o.changes() |
| 371 | var commits []string |
| 372 | for _, id := range ids { |
| 373 | commits = append(commits, o.refs[change.Ref(recordTarget, id)]) |
| 374 | } |
| 375 | if err := fetch(g, commits...); err != nil { |
| 376 | return nil, err |
| 377 | } |
| 378 | var all []recorded |
| 379 | for i, id := range ids { |
| 380 | r, err := readRecord(g, commits[i]) |
| 381 | if err != nil { |
| 382 | return nil, err |
| 383 | } |
| 384 | all = append(all, recorded{id: id, commit: commits[i], record: r}) |
| 385 | } |
| 386 | return all, nil |
| 387 | } |
| 388 | |
| 389 | // project is the name a change's handle is printed under: origin's |
| 390 | // repository, as its URL names it, without .git. |
| 391 | func project(g git) string { |
| 392 | url, err := g.output(true, "remote", "get-url", "origin") |
| 393 | if err != nil { |
| 394 | return "origin" |
| 395 | } |
| 396 | url = strings.TrimRight(url, "/") |
| 397 | if i := strings.LastIndexAny(url, "/:"); i >= 0 { |
| 398 | url = url[i+1:] |
| 399 | } |
| 400 | if name := strings.TrimSuffix(url, ".git"); name != "" { |
| 401 | return name |
| 402 | } |
| 403 | return "origin" |
| 404 | } |
| 405 | |
| 406 | // writeRecord writes a record commit holding r, with the parents given, |
| 407 | // and returns its ID. Its tree holds record.json alone, as a plain file, |
| 408 | // which is the only shape the hook accepts. |
| 409 | func writeRecord(g git, r *change.Record, message string, parents ...string) (string, error) { |
| 410 | data, err := change.Encode(r) |
| 411 | if err != nil { |
| 412 | return "", err |
| 413 | } |
| 414 | if len(data) > maxRecordBlob { |
| 415 | return "", failure(fmt.Sprintf("the change's record would be %d bytes, more than the %d a record may be", len(data), maxRecordBlob)) |
| 416 | } |
| 417 | blob, err := g.input(false, bytes.NewReader(data), "hash-object", "-w", "--stdin") |
| 418 | if err != nil { |
| 419 | return "", failure("could not write the record") |
| 420 | } |
| 421 | tree, err := g.input(false, strings.NewReader("100644 blob "+blob+"\trecord.json\n"), "mktree") |
| 422 | if err != nil { |
| 423 | return "", failure("could not write the record's tree") |
| 424 | } |
| 425 | args := []string{"commit-tree", tree} |
| 426 | for _, p := range parents { |
| 427 | args = append(args, "-p", p) |
| 428 | } |
| 429 | commit, err := g.input(false, strings.NewReader(message+"\n"), append(args, "-F", "-")...) |
| 430 | if err != nil { |
| 431 | return "", failure("could not write the record commit") |
| 432 | } |
| 433 | return commit, nil |
| 434 | } |
| 435 | |
| 436 | // maxRecordBlob is the most bytes a record.json may hold, as the hook |
| 437 | // bounds it. |
| 438 | const maxRecordBlob = 64 << 10 |
| 439 | |
| 440 | // pushRecord moves the change's record ref on origin from old to commit, |
| 441 | // leased on old: the push is refused if the ref has moved since it was |
| 442 | // read, and a record that did not exist must still not exist. The hook's |
| 443 | // refusal reaches stderr through git. |
| 444 | func pushRecord(g git, id, old, commit string) error { |
| 445 | ref := change.Ref(recordTarget, id) |
| 446 | _, err := g.output(false, "push", "--quiet", "--force-with-lease="+ref+":"+old, "origin", commit+":"+ref) |
| 447 | if err != nil { |
| 448 | return failure("origin did not take the record of " + id) |
| 449 | } |
| 450 | return nil |
| 451 | } |