gunk-dev/the-valley

changes.go

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