gunk-dev/the-valley

changes.go

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