gunk-dev/the-valley

changes.go

source7f2ba03103bemain's published tip history
15.6 KiB
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
29package main
30
31import (
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.
43const recordTarget = "main"
44
45// origin is one ls-remote snapshot of the refs a verb reads.
46type 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.
53func 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.
69var recordPatterns = []string{change.RefPrefix + recordTarget + "/*"}
70
71// changes is the ID of every change origin holds a record for, in order.
72func (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.
85func (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.
93func 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.
126func 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.
140type 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.
150func lookup(g git, o origin, name string) (n recorded, found bool, err error) {
151 handle, qualified, err := handlePart(g, name)
152 switch {
153 case err != nil:
154 return recorded{}, false, err
155 case handle == "" || strings.HasPrefix(name, "origin/"):
156 return recorded{}, false, nil
157 }
158 ids := o.changes()
159 matches := change.Matching(handle, ids)
160 switch {
161 case len(matches) == 0 && qualified:
162 return recorded{}, false, failure(fmt.Sprintf("no change on origin has the handle %s", name))
163 case len(matches) == 0:
164 return recorded{}, false, nil
165 case len(matches) > 1:
166 var handles []string
167 for _, id := range matches {
168 handles = append(handles, change.Handle(id, ids))
169 }
170 return recorded{}, false, failure(fmt.Sprintf("%s could name any of the changes %s; give more of its ID",
171 name, strings.Join(handles, ", ")))
172 }
173 n = recorded{id: matches[0], commit: o.refs[change.Ref(recordTarget, matches[0])]}
174 if err := fetch(g, n.commit); err != nil {
175 return recorded{}, false, err
176 }
177 if n.record, err = readRecord(g, n.commit); err != nil {
178 return recorded{}, false, err
179 }
180 if branch := n.record.ActiveVersion().Branch; o.refs["refs/heads/"+name] != "" && branch != name {
181 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",
182 name, n.id, name))
183 }
184 return n, true, nil
185}
186
187// handlePart is the handle a name gives, when it has a handle's shape: the
188// name itself, or what follows the colon in a name written
189// <repo>:<handle>. changes and pending qualify a handle that way when one
190// change ID is recorded in several repositories they list. git refuses a
191// colon in a ref name, so a qualified name is never a branch's. It must
192// name this repository, and qualified reports that it was written so.
193func handlePart(g git, name string) (handle string, qualified bool, err error) {
194 if change.LooksLikeHandle(name) {
195 return name, false, nil
196 }
197 repo, handle, ok := strings.Cut(name, ":")
198 if !ok || !change.LooksLikeHandle(handle) {
199 return "", false, nil
200 }
201 if here := project(g); repo != here {
202 return "", false, failure(fmt.Sprintf("%s names a change in %s, and this repository is %s", name, repo, here))
203 }
204 return handle, true, nil
205}
206
207// resolution is what the name of a change stands for. A name that is a
208// branch's sets branch alone. A name that is a change's sets every field
209// from the change's record on origin: the active version, the head that
210// version names, the branch it names, and the change's state.
211type resolution struct {
212 id, handle, head, branch, state string
213 version int
214}
215
216// resolve reads a change's name, as status does. A name with no handle's
217// shape is a branch name without origin being read. A change whose active
218// version names no branch is refused, since every verb that resolves a
219// name acts on a branch too.
220func resolve(g git, name string) (resolution, error) {
221 handle, _, err := handlePart(g, name)
222 if err != nil {
223 return resolution{}, err
224 }
225 if strings.HasPrefix(name, "origin/") || handle == "" {
226 return resolution{branch: strings.TrimPrefix(name, "origin/")}, nil
227 }
228 o, err := listOrigin(g, append([]string{"refs/heads/" + name}, recordPatterns...)...)
229 if err != nil {
230 return resolution{}, err
231 }
232 n, found, err := lookup(g, o, name)
233 switch {
234 case err != nil:
235 return resolution{}, err
236 case !found:
237 return resolution{branch: name}, nil
238 }
239 return o.resolution(n)
240}
241
242// resolveRecorded reads a change's name for the verbs that act on a
243// change: review, approve and rebase, through runResolve. A name that is a
244// change's ID or handle is that change, as resolve reads it. A branch name,
245// written as <branch> or origin/<branch>, is read against the branch each
246// record's active version names. No record on the branch leaves the name a
247// branch, as it was before changes had records. One record makes the name
248// that record's change, exactly as if its ID had been given. More than one
249// is refused, since acting on the branch would act on any of them.
250func resolveRecorded(g git, name string) (resolution, error) {
251 branch := strings.TrimPrefix(name, "origin/")
252 o, err := listOrigin(g, append([]string{"refs/heads/" + branch}, inventoryPatterns...)...)
253 if err != nil {
254 return resolution{}, err
255 }
256 if !strings.HasPrefix(name, "origin/") {
257 n, found, err := lookup(g, o, name)
258 switch {
259 case err != nil:
260 return resolution{}, err
261 case found:
262 return o.resolution(n)
263 }
264 }
265 found, err := unlandedOn(g, o, branch)
266 if err != nil {
267 return resolution{}, err
268 }
269 switch len(found) {
270 case 0:
271 return resolution{branch: branch}, nil
272 case 1:
273 return o.resolution(found[0])
274 }
275 var ids []string
276 for _, n := range found {
277 ids = append(ids, n.id)
278 }
279 return resolution{}, failure(fmt.Sprintf("the changes %s all have their active version on %s; name one by its change ID",
280 strings.Join(ids, ", "), branch))
281}
282
283// resolution is what a change's record says its name stands for: the
284// active version, the head that version names, the branch it names, and
285// the change's state.
286func (o origin) resolution(n recorded) (resolution, error) {
287 v := n.record.ActiveVersion()
288 r := resolution{
289 id: n.id, handle: o.handle(n.id), version: v.N,
290 head: strings.TrimPrefix(v.Head, change.HeadPrefix), branch: v.Branch, state: n.record.State,
291 }
292 if r.branch == "" {
293 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))
294 }
295 return r, nil
296}
297
298// unlandedOn is every change origin holds a record of whose active
299// version names branch, less each whose active version has landed while
300// the branch's tip on origin is still that version's head. o must list
301// inventoryPatterns.
302// Landing is read only for a change on the branch, so a name no record is
303// on costs no more than reading the records.
304func unlandedOn(g git, o origin, branch string) ([]recorded, error) {
305 all, err := readAll(g, o)
306 if err != nil {
307 return nil, err
308 }
309 var on []recorded
310 for _, n := range all {
311 if n.record.ActiveVersion().Branch == branch {
312 on = append(on, n)
313 }
314 }
315 if len(on) == 0 {
316 return nil, nil
317 }
318 var want []string
319 for ref, oid := range o.refs {
320 if ref == "refs/heads/"+recordTarget || strings.HasPrefix(ref, outcomePrefix) {
321 want = append(want, oid)
322 }
323 }
324 if err := fetch(g, want...); err != nil {
325 return nil, err
326 }
327 s := newSnapshot(g, o, all, verifierFromEnv())
328 var found []recorded
329 tip := o.refs["refs/heads/"+branch]
330 for _, n := range on {
331 v := n.record.ActiveVersion()
332 if tip != headOf(v) || !s.isLanded(n.id, v) {
333 found = append(found, n)
334 }
335 }
336 return found, nil
337}
338
339// resolveBranch is the branch a change is on: the branch its active
340// version names, when the name is a change's, and otherwise the name
341// itself, as a branch name.
342func resolveBranch(g git, name string) (string, error) {
343 r, err := resolve(g, name)
344 return r.branch, err
345}
346
347// runResolve prints what a change's name stands for, for the verbs
348// bin/valley runs itself, as resolveRecorded reads it: one line of fields
349// separated by tabs. For a change it is
350//
351// change <ID> <handle> <version> <head> <branch> <state>
352//
353// with the head as a full object ID, and the state as the record says it:
354// ready, draft or withdrawn. For a branch it is
355//
356// branch <branch>
357//
358// A branch name holds no tab, since git refuses control characters in a
359// ref name. The record commit, which has the head as a parent, has been
360// fetched, so the head is in this checkout's objects.
361func runResolve(g git, args []string, w io.Writer) error {
362 if len(args) != 1 {
363 return failure("usage: valley-go resolve <change>")
364 }
365 if !g.succeeds(true, "rev-parse", "--git-dir") {
366 return failure("not a git repository")
367 }
368 r, err := resolveRecorded(g, args[0])
369 if err != nil {
370 return err
371 }
372 if r.id == "" {
373 _, err = fmt.Fprintf(w, "branch\t%s\n", r.branch)
374 return err
375 }
376 _, 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)
377 return err
378}
379
380// readAll reads every record origin holds, in the order of their IDs.
381func readAll(g git, o origin) ([]recorded, error) {
382 ids := o.changes()
383 var commits []string
384 for _, id := range ids {
385 commits = append(commits, o.refs[change.Ref(recordTarget, id)])
386 }
387 if err := fetch(g, commits...); err != nil {
388 return nil, err
389 }
390 var all []recorded
391 for i, id := range ids {
392 r, err := readRecord(g, commits[i])
393 if err != nil {
394 return nil, err
395 }
396 all = append(all, recorded{id: id, commit: commits[i], record: r})
397 }
398 return all, nil
399}
400
401// project is the name a change's handle is printed under: origin's
402// repository, as its URL names it, without .git.
403func project(g git) string {
404 url, err := g.output(true, "remote", "get-url", "origin")
405 if err != nil {
406 return "origin"
407 }
408 url = strings.TrimRight(url, "/")
409 if i := strings.LastIndexAny(url, "/:"); i >= 0 {
410 url = url[i+1:]
411 }
412 if name := strings.TrimSuffix(url, ".git"); name != "" {
413 return name
414 }
415 return "origin"
416}
417
418// writeRecord writes a record commit holding r, with the parents given,
419// and returns its ID. Its tree holds record.json alone, as a plain file,
420// which is the only shape the hook accepts.
421func writeRecord(g git, r *change.Record, message string, parents ...string) (string, error) {
422 data, err := change.Encode(r)
423 if err != nil {
424 return "", err
425 }
426 if len(data) > maxRecordBlob {
427 return "", failure(fmt.Sprintf("the change's record would be %d bytes, more than the %d a record may be", len(data), maxRecordBlob))
428 }
429 blob, err := g.input(false, bytes.NewReader(data), "hash-object", "-w", "--stdin")
430 if err != nil {
431 return "", failure("could not write the record")
432 }
433 tree, err := g.input(false, strings.NewReader("100644 blob "+blob+"\trecord.json\n"), "mktree")
434 if err != nil {
435 return "", failure("could not write the record's tree")
436 }
437 args := []string{"commit-tree", tree}
438 for _, p := range parents {
439 args = append(args, "-p", p)
440 }
441 commit, err := g.input(false, strings.NewReader(message+"\n"), append(args, "-F", "-")...)
442 if err != nil {
443 return "", failure("could not write the record commit")
444 }
445 return commit, nil
446}
447
448// maxRecordBlob is the most bytes a record.json may hold, as the hook
449// bounds it.
450const maxRecordBlob = change.MaxRecordBlob
451
452// pushRecord moves the change's record ref on origin from old to commit,
453// leased on old: the push is refused if the ref has moved since it was
454// read, and a record that did not exist must still not exist. The hook's
455// refusal reaches stderr through git.
456func pushRecord(g git, id, old, commit string) error {
457 ref := change.Ref(recordTarget, id)
458 _, err := g.output(false, "push", "--quiet", "--force-with-lease="+ref+":"+old, "origin", commit+":"+ref)
459 if err != nil {
460 return failure("origin did not take the record of " + id)
461 }
462 return nil
463}