| 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 | // resolveBranch is the branch a change is on: the branch its active |
| 154 | // version names, when the name is a change's, and otherwise the name |
| 155 | // itself, as a branch name. A name with no handle's shape is a branch name |
| 156 | // without origin being read. |
| 157 | func resolveBranch(g git, name string) (string, error) { |
| 158 | if strings.HasPrefix(name, "origin/") || !change.LooksLikeHandle(name) { |
| 159 | return strings.TrimPrefix(name, "origin/"), nil |
| 160 | } |
| 161 | o, err := listOrigin(g, append([]string{"refs/heads/" + name}, recordPatterns...)...) |
| 162 | if err != nil { |
| 163 | return "", err |
| 164 | } |
| 165 | n, found, err := lookup(g, o, name) |
| 166 | switch { |
| 167 | case err != nil: |
| 168 | return "", err |
| 169 | case !found: |
| 170 | return name, nil |
| 171 | } |
| 172 | v := n.record.ActiveVersion() |
| 173 | if v.Branch == "" { |
| 174 | return "", failure(fmt.Sprintf("the change %s names no branch at v%d, so there is no branch to act on", o.handle(n.id), v.N)) |
| 175 | } |
| 176 | return v.Branch, nil |
| 177 | } |
| 178 | |
| 179 | // runResolve prints the branch a change is on, for the verbs bin/valley |
| 180 | // runs itself. |
| 181 | func runResolve(g git, args []string, w io.Writer) error { |
| 182 | if len(args) != 1 { |
| 183 | return failure("usage: valley-go resolve <change>") |
| 184 | } |
| 185 | if !g.succeeds(true, "rev-parse", "--git-dir") { |
| 186 | return failure("not a git repository") |
| 187 | } |
| 188 | branch, err := resolveBranch(g, args[0]) |
| 189 | if err != nil { |
| 190 | return err |
| 191 | } |
| 192 | _, err = fmt.Fprintln(w, branch) |
| 193 | return err |
| 194 | } |
| 195 | |
| 196 | // project is the name a change's handle is printed under: origin's |
| 197 | // repository, as its URL names it, without .git. |
| 198 | func project(g git) string { |
| 199 | url, err := g.output(true, "remote", "get-url", "origin") |
| 200 | if err != nil { |
| 201 | return "origin" |
| 202 | } |
| 203 | url = strings.TrimRight(url, "/") |
| 204 | if i := strings.LastIndexAny(url, "/:"); i >= 0 { |
| 205 | url = url[i+1:] |
| 206 | } |
| 207 | if name := strings.TrimSuffix(url, ".git"); name != "" { |
| 208 | return name |
| 209 | } |
| 210 | return "origin" |
| 211 | } |
| 212 | |
| 213 | // writeRecord writes a record commit holding r, with the parents given, |
| 214 | // and returns its ID. Its tree holds record.json alone, as a plain file, |
| 215 | // which is the only shape the hook accepts. |
| 216 | func writeRecord(g git, r *change.Record, message string, parents ...string) (string, error) { |
| 217 | data, err := change.Encode(r) |
| 218 | if err != nil { |
| 219 | return "", err |
| 220 | } |
| 221 | if len(data) > maxRecordBlob { |
| 222 | return "", failure(fmt.Sprintf("the change's record would be %d bytes, more than the %d a record may be", len(data), maxRecordBlob)) |
| 223 | } |
| 224 | blob, err := g.input(false, bytes.NewReader(data), "hash-object", "-w", "--stdin") |
| 225 | if err != nil { |
| 226 | return "", failure("could not write the record") |
| 227 | } |
| 228 | tree, err := g.input(false, strings.NewReader("100644 blob "+blob+"\trecord.json\n"), "mktree") |
| 229 | if err != nil { |
| 230 | return "", failure("could not write the record's tree") |
| 231 | } |
| 232 | args := []string{"commit-tree", tree} |
| 233 | for _, p := range parents { |
| 234 | args = append(args, "-p", p) |
| 235 | } |
| 236 | commit, err := g.input(false, strings.NewReader(message+"\n"), append(args, "-F", "-")...) |
| 237 | if err != nil { |
| 238 | return "", failure("could not write the record commit") |
| 239 | } |
| 240 | return commit, nil |
| 241 | } |
| 242 | |
| 243 | // maxRecordBlob is the most bytes a record.json may hold, as the hook |
| 244 | // bounds it. |
| 245 | const maxRecordBlob = 64 << 10 |
| 246 | |
| 247 | // pushRecord moves the change's record ref on origin from old to commit, |
| 248 | // leased on old: the push is refused if the ref has moved since it was |
| 249 | // read, and a record that did not exist must still not exist. The hook's |
| 250 | // refusal reaches stderr through git. |
| 251 | func pushRecord(g git, id, old, commit string) error { |
| 252 | ref := change.Ref(recordTarget, id) |
| 253 | _, err := g.output(false, "push", "--quiet", "--force-with-lease="+ref+":"+old, "origin", commit+":"+ref) |
| 254 | if err != nil { |
| 255 | return failure("origin did not take the record of " + id) |
| 256 | } |
| 257 | return nil |
| 258 | } |