| 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 | package main |
| 18 | |
| 19 | import ( |
| 20 | "bytes" |
| 21 | "fmt" |
| 22 | "io" |
| 23 | "sort" |
| 24 | "strings" |
| 25 | |
| 26 | "the-valley/change" |
| 27 | ) |
| 28 | |
| 29 | // recordTarget is the one target a change may name for now. The hook |
| 30 | // refuses a record for any other. |
| 31 | const recordTarget = "main" |
| 32 | |
| 33 | // origin is one ls-remote snapshot of the refs a verb reads. |
| 34 | type origin struct { |
| 35 | refs map[string]string // ref → object ID |
| 36 | } |
| 37 | |
| 38 | // listOrigin takes one snapshot of origin's refs matching the patterns. |
| 39 | // ls-remote matches a pattern against the tail of a ref name, so every ref |
| 40 | // is compared whole afterwards. |
| 41 | func listOrigin(g git, patterns ...string) (origin, error) { |
| 42 | out, err := g.output(false, append([]string{"ls-remote", "--refs", "origin"}, patterns...)...) |
| 43 | if err != nil { |
| 44 | return origin{}, failure("could not read origin") |
| 45 | } |
| 46 | o := origin{refs: map[string]string{}} |
| 47 | for _, line := range strings.Split(out, "\n") { |
| 48 | oid, ref, ok := strings.Cut(line, "\t") |
| 49 | if ok && ref != "" { |
| 50 | o.refs[ref] = oid |
| 51 | } |
| 52 | } |
| 53 | return o, nil |
| 54 | } |
| 55 | |
| 56 | // recordPatterns are the ls-remote patterns that list every record. |
| 57 | var recordPatterns = []string{change.RefPrefix + recordTarget + "/*"} |
| 58 | |
| 59 | // changes is the ID of every change origin holds a record for, in order. |
| 60 | func (o origin) changes() []string { |
| 61 | var ids []string |
| 62 | for ref := range o.refs { |
| 63 | if target, id, ok := change.ParseRef(ref); ok && target == recordTarget { |
| 64 | ids = append(ids, id) |
| 65 | } |
| 66 | } |
| 67 | sort.Strings(ids) |
| 68 | return ids |
| 69 | } |
| 70 | |
| 71 | // handle is the change's handle among the changes origin holds, and this |
| 72 | // one, which may not be among them yet. |
| 73 | func (o origin) handle(id string) string { |
| 74 | return change.Handle(id, append(o.changes(), id)) |
| 75 | } |
| 76 | |
| 77 | // fetch brings the objects named into this checkout's object store, |
| 78 | // without writing FETCH_HEAD, moving a ref or fetching tags. |
| 79 | func fetch(g git, oids ...string) error { |
| 80 | var stdin bytes.Buffer |
| 81 | for _, oid := range oids { |
| 82 | if oid != "" { |
| 83 | fmt.Fprintln(&stdin, oid) |
| 84 | } |
| 85 | } |
| 86 | if stdin.Len() == 0 { |
| 87 | return nil |
| 88 | } |
| 89 | _, err := g.input(false, &stdin, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--stdin", "origin") |
| 90 | if err != nil { |
| 91 | return failure("could not fetch from origin") |
| 92 | } |
| 93 | return nil |
| 94 | } |
| 95 | |
| 96 | // readRecord reads the record a record commit holds. The commit must have |
| 97 | // been fetched. |
| 98 | func readRecord(g git, commit string) (*change.Record, error) { |
| 99 | data, err := g.output(true, "cat-file", "blob", commit+":record.json") |
| 100 | if err != nil { |
| 101 | return nil, failure(fmt.Sprintf("the change record %s holds no record.json", short(commit))) |
| 102 | } |
| 103 | r, err := change.Parse([]byte(data + "\n")) |
| 104 | if err != nil { |
| 105 | return nil, failure(fmt.Sprintf("the change record %s does not read: %v", short(commit), err)) |
| 106 | } |
| 107 | return r, nil |
| 108 | } |
| 109 | |
| 110 | // recorded is a change that a name resolved to: its ID, and its record on |
| 111 | // origin. |
| 112 | type recorded struct { |
| 113 | id string |
| 114 | commit string // the record commit origin's ref points at |
| 115 | record *change.Record |
| 116 | } |
| 117 | |
| 118 | // lookup resolves a name to a change origin holds a record for. found is |
| 119 | // false when the name is a branch name rather than a change's: it is |
| 120 | // written as origin/<branch>, it has no handle's shape, or it matches no |
| 121 | // record. A name that matches more than one record is refused. |
| 122 | func lookup(g git, o origin, name string) (n recorded, found bool, err error) { |
| 123 | if strings.HasPrefix(name, "origin/") || !change.LooksLikeHandle(name) { |
| 124 | return recorded{}, false, nil |
| 125 | } |
| 126 | ids := o.changes() |
| 127 | matches := change.Matching(name, ids) |
| 128 | switch { |
| 129 | case len(matches) == 0: |
| 130 | return recorded{}, false, nil |
| 131 | case len(matches) > 1: |
| 132 | var handles []string |
| 133 | for _, id := range matches { |
| 134 | handles = append(handles, change.Handle(id, ids)) |
| 135 | } |
| 136 | return recorded{}, false, failure(fmt.Sprintf("%s could name any of the changes %s; give more of its ID", |
| 137 | name, strings.Join(handles, ", "))) |
| 138 | } |
| 139 | n = recorded{id: matches[0], commit: o.refs[change.Ref(recordTarget, matches[0])]} |
| 140 | if err := fetch(g, n.commit); err != nil { |
| 141 | return recorded{}, false, err |
| 142 | } |
| 143 | if n.record, err = readRecord(g, n.commit); err != nil { |
| 144 | return recorded{}, false, err |
| 145 | } |
| 146 | if branch := n.record.ActiveVersion().Branch; o.refs["refs/heads/"+name] != "" && branch != name { |
| 147 | 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", |
| 148 | name, n.id, name)) |
| 149 | } |
| 150 | return n, true, nil |
| 151 | } |
| 152 | |
| 153 | // resolution is what the name of a change stands for. A name that is a |
| 154 | // branch's sets branch alone. A name that is a change's sets every field |
| 155 | // from the change's record on origin: the active version, the head that |
| 156 | // version names, and the branch it names. |
| 157 | type resolution struct { |
| 158 | id, handle, head, branch string |
| 159 | version int |
| 160 | } |
| 161 | |
| 162 | // resolve reads a change's name, as every verb that takes a change does. |
| 163 | // A name with no handle's shape is a branch name without origin being |
| 164 | // read. A change whose active version names no branch is refused, since |
| 165 | // every verb that resolves a name acts on a branch too. |
| 166 | func resolve(g git, name string) (resolution, error) { |
| 167 | if strings.HasPrefix(name, "origin/") || !change.LooksLikeHandle(name) { |
| 168 | return resolution{branch: strings.TrimPrefix(name, "origin/")}, nil |
| 169 | } |
| 170 | o, err := listOrigin(g, append([]string{"refs/heads/" + name}, recordPatterns...)...) |
| 171 | if err != nil { |
| 172 | return resolution{}, err |
| 173 | } |
| 174 | n, found, err := lookup(g, o, name) |
| 175 | switch { |
| 176 | case err != nil: |
| 177 | return resolution{}, err |
| 178 | case !found: |
| 179 | return resolution{branch: name}, nil |
| 180 | } |
| 181 | v := n.record.ActiveVersion() |
| 182 | r := resolution{ |
| 183 | id: n.id, handle: o.handle(n.id), version: v.N, |
| 184 | head: strings.TrimPrefix(v.Head, change.HeadPrefix), branch: v.Branch, |
| 185 | } |
| 186 | if r.branch == "" { |
| 187 | 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)) |
| 188 | } |
| 189 | return r, nil |
| 190 | } |
| 191 | |
| 192 | // resolveBranch is the branch a change is on: the branch its active |
| 193 | // version names, when the name is a change's, and otherwise the name |
| 194 | // itself, as a branch name. |
| 195 | func resolveBranch(g git, name string) (string, error) { |
| 196 | r, err := resolve(g, name) |
| 197 | return r.branch, err |
| 198 | } |
| 199 | |
| 200 | // runResolve prints what a change's name stands for, for the verbs |
| 201 | // bin/valley runs itself, as one line of fields separated by tabs. For a |
| 202 | // change it is |
| 203 | // |
| 204 | // change <ID> <handle> <version> <head> <branch> |
| 205 | // |
| 206 | // with the head as a full object ID. For a branch it is |
| 207 | // |
| 208 | // branch <branch> |
| 209 | // |
| 210 | // A branch name holds no tab, since git refuses control characters in a |
| 211 | // ref name. The record commit, which has the head as a parent, has been |
| 212 | // fetched, so the head is in this checkout's objects. |
| 213 | func runResolve(g git, args []string, w io.Writer) error { |
| 214 | if len(args) != 1 { |
| 215 | return failure("usage: valley-go resolve <change>") |
| 216 | } |
| 217 | if !g.succeeds(true, "rev-parse", "--git-dir") { |
| 218 | return failure("not a git repository") |
| 219 | } |
| 220 | r, err := resolve(g, args[0]) |
| 221 | if err != nil { |
| 222 | return err |
| 223 | } |
| 224 | if r.id == "" { |
| 225 | _, err = fmt.Fprintf(w, "branch\t%s\n", r.branch) |
| 226 | return err |
| 227 | } |
| 228 | _, err = fmt.Fprintf(w, "change\t%s\t%s\t%d\t%s\t%s\n", r.id, r.handle, r.version, r.head, r.branch) |
| 229 | return err |
| 230 | } |
| 231 | |
| 232 | // project is the name a change's handle is printed under: origin's |
| 233 | // repository, as its URL names it, without .git. |
| 234 | func project(g git) string { |
| 235 | url, err := g.output(true, "remote", "get-url", "origin") |
| 236 | if err != nil { |
| 237 | return "origin" |
| 238 | } |
| 239 | url = strings.TrimRight(url, "/") |
| 240 | if i := strings.LastIndexAny(url, "/:"); i >= 0 { |
| 241 | url = url[i+1:] |
| 242 | } |
| 243 | if name := strings.TrimSuffix(url, ".git"); name != "" { |
| 244 | return name |
| 245 | } |
| 246 | return "origin" |
| 247 | } |
| 248 | |
| 249 | // writeRecord writes a record commit holding r, with the parents given, |
| 250 | // and returns its ID. Its tree holds record.json alone, as a plain file, |
| 251 | // which is the only shape the hook accepts. |
| 252 | func writeRecord(g git, r *change.Record, message string, parents ...string) (string, error) { |
| 253 | data, err := change.Encode(r) |
| 254 | if err != nil { |
| 255 | return "", err |
| 256 | } |
| 257 | if len(data) > maxRecordBlob { |
| 258 | return "", failure(fmt.Sprintf("the change's record would be %d bytes, more than the %d a record may be", len(data), maxRecordBlob)) |
| 259 | } |
| 260 | blob, err := g.input(false, bytes.NewReader(data), "hash-object", "-w", "--stdin") |
| 261 | if err != nil { |
| 262 | return "", failure("could not write the record") |
| 263 | } |
| 264 | tree, err := g.input(false, strings.NewReader("100644 blob "+blob+"\trecord.json\n"), "mktree") |
| 265 | if err != nil { |
| 266 | return "", failure("could not write the record's tree") |
| 267 | } |
| 268 | args := []string{"commit-tree", tree} |
| 269 | for _, p := range parents { |
| 270 | args = append(args, "-p", p) |
| 271 | } |
| 272 | commit, err := g.input(false, strings.NewReader(message+"\n"), append(args, "-F", "-")...) |
| 273 | if err != nil { |
| 274 | return "", failure("could not write the record commit") |
| 275 | } |
| 276 | return commit, nil |
| 277 | } |
| 278 | |
| 279 | // maxRecordBlob is the most bytes a record.json may hold, as the hook |
| 280 | // bounds it. |
| 281 | const maxRecordBlob = 64 << 10 |
| 282 | |
| 283 | // pushRecord moves the change's record ref on origin from old to commit, |
| 284 | // leased on old: the push is refused if the ref has moved since it was |
| 285 | // read, and a record that did not exist must still not exist. The hook's |
| 286 | // refusal reaches stderr through git. |
| 287 | func pushRecord(g git, id, old, commit string) error { |
| 288 | ref := change.Ref(recordTarget, id) |
| 289 | _, err := g.output(false, "push", "--quiet", "--force-with-lease="+ref+":"+old, "origin", commit+":"+ref) |
| 290 | if err != nil { |
| 291 | return failure("origin did not take the record of " + id) |
| 292 | } |
| 293 | return nil |
| 294 | } |