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