gunk-dev/the-valley

changes.go

source8b1b9a095b54main's published tip history
17.8 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. A change whose active version names no branch
217// resolves with an empty branch: approve files the head alone, and
218// bin/valley refuses it for review and rebase, which act on a branch.
219func resolveRecorded(g git, name string) (resolution, error) {
220 o, n, found, err := lookupRecorded(g, name)
221 switch {
222 case err != nil:
223 return resolution{}, err
224 case !found:
225 return resolution{branch: strings.TrimPrefix(name, "origin/")}, nil
226 }
227 return o.resolution(n), nil
228}
229
230// lookupRecorded reads a change's name and returns the record it names,
231// if it names one, with the snapshot of origin it was read in. That
232// snapshot lists inventoryPatterns. A name that is a change's ID or handle
233// is that change, as lookup reads it. A branch name, written as <branch>
234// or origin/<branch>, is read against the branch each record's active
235// version names. No record on the branch leaves the name a branch, as it
236// was before changes had records. One record makes the name that record's
237// change, exactly as if its ID had been given. More than one is refused,
238// since acting on the branch would act on any of them.
239func lookupRecorded(g git, name string) (origin, recorded, bool, error) {
240 branch := strings.TrimPrefix(name, "origin/")
241 o, err := listOrigin(g, append([]string{"refs/heads/" + branch}, inventoryPatterns...)...)
242 if err != nil {
243 return origin{}, recorded{}, false, err
244 }
245 if !strings.HasPrefix(name, "origin/") {
246 n, found, err := lookup(g, o, name)
247 switch {
248 case err != nil:
249 return o, recorded{}, false, err
250 case found:
251 return o, n, true, nil
252 }
253 }
254 found, err := unlandedOn(g, o, branch)
255 if err != nil {
256 return o, recorded{}, false, err
257 }
258 switch len(found) {
259 case 0:
260 return o, recorded{}, false, nil
261 case 1:
262 return o, found[0], true, nil
263 }
264 var ids []string
265 for _, n := range found {
266 ids = append(ids, n.id)
267 }
268 return o, recorded{}, false, failure(fmt.Sprintf("the changes %s all have their active version on %s; name one by its change ID",
269 strings.Join(ids, ", "), branch))
270}
271
272// resolution is what a change's record says its name stands for: the
273// active version, the head that version names, the branch it names, and
274// the change's state.
275func (o origin) resolution(n recorded) resolution {
276 v := n.record.ActiveVersion()
277 return resolution{
278 id: n.id, handle: o.handle(n.id), version: v.N,
279 head: strings.TrimPrefix(v.Head, change.HeadPrefix), branch: v.Branch, state: n.record.State,
280 }
281}
282
283// unlandedOn is every change origin holds a record of whose active
284// version names branch, less each whose active version has landed. o must
285// list inventoryPatterns. Landing is read only for a change on the
286// branch, so a name no record is on costs no more than reading the
287// records.
288//
289// A landed change is left out wherever the branch has moved since. The
290// branch then holds new work, and the name is free for it. A landing read
291// wrongly could make a draft's branch read as a plain branch, but nothing
292// lands from that: the integrator refuses any request whose head is a
293// version of a change that is not ready, whatever the request is named.
294func unlandedOn(g git, o origin, branch string) ([]recorded, error) {
295 all, _, err := readAll(g, o)
296 if err != nil {
297 return nil, err
298 }
299 var on []recorded
300 for _, n := range all {
301 if n.record.ActiveVersion().Branch == branch {
302 on = append(on, n)
303 }
304 }
305 if len(on) == 0 {
306 return nil, nil
307 }
308 var want []string
309 for ref, oid := range o.refs {
310 if ref == "refs/heads/"+recordTarget || strings.HasPrefix(ref, outcomePrefix) {
311 want = append(want, oid)
312 }
313 }
314 if err := fetch(g, want...); err != nil {
315 return nil, err
316 }
317 s := newSnapshot(g, o, all, verifierFromEnv())
318 var found []recorded
319 for _, n := range on {
320 if !s.isLanded(n.id, n.record.ActiveVersion()) {
321 found = append(found, n)
322 }
323 }
324 return found, nil
325}
326
327// runResolve prints what a change's name stands for, for the verbs
328// bin/valley runs itself, as resolveRecorded reads it: one line of fields
329// separated by tabs. For a change it is
330//
331// change <ID> <handle> <version> <head> <branch> <state>
332//
333// with the head as a full object ID, and the state as the record says it:
334// ready, draft or withdrawn. For a branch it is
335//
336// branch <branch>
337//
338// A version may name no branch, and then the branch field is empty. A
339// branch name holds no tab, since git refuses control characters in a
340// ref name. The record commit, which has the head as a parent, has been
341// fetched, so the head is in this checkout's objects.
342func runResolve(g git, args []string, w io.Writer) error {
343 if len(args) != 1 {
344 return failure("usage: valley-go resolve <change>")
345 }
346 if !g.succeeds(true, "rev-parse", "--git-dir") {
347 return failure("not a git repository")
348 }
349 r, err := resolveRecorded(g, args[0])
350 if err != nil {
351 return err
352 }
353 if r.id == "" {
354 _, err = fmt.Fprintf(w, "branch\t%s\n", r.branch)
355 return err
356 }
357 _, 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)
358 return err
359}
360
361// runVersions prints every version of a change, for bin/valley's approve,
362// which approves exactly one head of a change and refuses a head no
363// version records. One line each, in order, of fields separated by tabs:
364//
365// <n> <head> <state> <title>
366//
367// with the head as a full object ID and the change's state as its record
368// says it, on every line. The title is last, since it may hold spaces; it
369// holds no tab, which is a control character. It fails when origin holds
370// no record of the change.
371func runVersions(g git, args []string, w io.Writer) error {
372 if len(args) != 1 || !change.ValidID(args[0]) {
373 return failure("usage: valley-go versions <change ID>")
374 }
375 id := args[0]
376 if !g.succeeds(true, "rev-parse", "--git-dir") {
377 return failure("not a git repository")
378 }
379 ref := change.Ref(recordTarget, id)
380 o, err := listOrigin(g, ref)
381 if err != nil {
382 return err
383 }
384 commit := o.refs[ref]
385 if commit == "" {
386 return failure("origin holds no record of change " + id)
387 }
388 if err := fetch(g, commit); err != nil {
389 return err
390 }
391 r, err := readRecord(g, commit)
392 if err != nil {
393 return err
394 }
395 var b strings.Builder
396 for _, v := range r.Versions {
397 fmt.Fprintf(&b, "%d\t%s\t%s\t%s\n", v.N, headOf(v), r.State, v.Title)
398 }
399 _, err = io.WriteString(w, b.String())
400 return err
401}
402
403// readAll reads every record origin holds, in the order of their IDs. A
404// record that does not read is kept apart, in unread, and is no change for
405// any reader: the integrator treats it the same way. The hook refuses such
406// a record, so only corrupt storage holds one. err is for origin that
407// could not be read.
408func readAll(g git, o origin) (all []recorded, unread []unreadRecord, err error) {
409 ids := o.changes()
410 var commits []string
411 for _, id := range ids {
412 commits = append(commits, o.refs[change.Ref(recordTarget, id)])
413 }
414 if err := fetch(g, commits...); err != nil {
415 return nil, nil, err
416 }
417 for i, id := range ids {
418 r, err := readRecord(g, commits[i])
419 if err != nil {
420 unread = append(unread, unreadRecord{ref: change.Ref(recordTarget, id), commit: commits[i], why: err.Error()})
421 continue
422 }
423 all = append(all, recorded{id: id, commit: commits[i], record: r})
424 }
425 return all, unread, nil
426}
427
428// unreadRecord is a record on origin that does not read.
429type unreadRecord struct {
430 ref, commit, why string
431}
432
433// mayName reports whether a record that does not read may name one of
434// the commits from tip to head as a version head. A record names its
435// version heads as parents of its record commits, so it can name only a
436// commit its record commit reaches. That holds for some commit from tip to
437// head exactly when a merge base of the record commit and head is not on
438// tip. A record git cannot compare at all may name anything.
439func mayName(g git, u unreadRecord, head, tip string) bool {
440 out, err := g.output(true, "merge-base", "--all", u.commit, head)
441 if err != nil {
442 return exitCode(err) != 1
443 }
444 for _, base := range strings.Fields(out) {
445 if !g.succeeds(true, "merge-base", "--is-ancestor", base, tip) {
446 return true
447 }
448 }
449 return false
450}
451
452// project is the name a change's handle is printed under: origin's
453// repository, as its URL names it, without .git.
454func project(g git) string {
455 url, err := g.output(true, "remote", "get-url", "origin")
456 if err != nil {
457 return "origin"
458 }
459 url = strings.TrimRight(url, "/")
460 if i := strings.LastIndexAny(url, "/:"); i >= 0 {
461 url = url[i+1:]
462 }
463 if name := strings.TrimSuffix(url, ".git"); name != "" {
464 return name
465 }
466 return "origin"
467}
468
469// writeRecord writes a record commit holding r, with the parents given,
470// and returns its ID. Its tree holds record.json alone, as a plain file,
471// which is the only shape the hook accepts.
472func writeRecord(g git, r *change.Record, message string, parents ...string) (string, error) {
473 data, err := change.Encode(r)
474 if err != nil {
475 return "", err
476 }
477 if len(data) > maxRecordBlob {
478 return "", failure(fmt.Sprintf("the change's record would be %d bytes, more than the %d a record may be", len(data), maxRecordBlob))
479 }
480 blob, err := g.input(false, bytes.NewReader(data), "hash-object", "-w", "--stdin")
481 if err != nil {
482 return "", failure("could not write the record")
483 }
484 tree, err := g.input(false, strings.NewReader("100644 blob "+blob+"\trecord.json\n"), "mktree")
485 if err != nil {
486 return "", failure("could not write the record's tree")
487 }
488 args := []string{"commit-tree", tree}
489 for _, p := range parents {
490 args = append(args, "-p", p)
491 }
492 commit, err := g.input(false, strings.NewReader(message+"\n"), append(args, "-F", "-")...)
493 if err != nil {
494 return "", failure("could not write the record commit")
495 }
496 return commit, nil
497}
498
499// maxRecordBlob is the most bytes a record.json may hold, as the hook
500// bounds it.
501const maxRecordBlob = change.MaxRecordBlob
502
503// pushRecord moves the change's record ref on origin from old to commit,
504// leased on old: the push is refused if the ref has moved since it was
505// read, and a record that did not exist must still not exist. The hook's
506// refusal reaches stderr through git.
507func pushRecord(g git, id, old, commit string) error {
508 ref := change.Ref(recordTarget, id)
509 _, err := g.output(false, "push", "--quiet", "--force-with-lease="+ref+":"+old, "origin", commit+":"+ref)
510 if err != nil {
511 return failure("origin did not take the record of " + id)
512 }
513 return nil
514}