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