gunk-dev/the-valley

changes.go

source9ea588cfdefamain's published tip history
15.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 "context"
31 "fmt"
32 "io"
33 "strings"
34 "unicode/utf8"
35
36 "the-valley/change"
37 "the-valley/rebase"
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 = rebase.Target
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, as
50// the rebase engine reads origin.
51func listOrigin(g git, patterns ...string) (origin, error) {
52 defer phase("fetch")()
53 o, err := rebase.ListOrigin(context.Background(), g.engine(), patterns...)
54 return origin{refs: o.Refs}, err
55}
56
57// engine is the snapshot as the rebase engine holds one.
58func (o origin) engine() rebase.Origin { return rebase.Origin{Refs: o.refs} }
59
60// recordPatterns are the ls-remote patterns that list every record.
61var recordPatterns = rebase.RecordPatterns
62
63// changes is the ID of every change origin holds a record for, in order.
64func (o origin) changes() []string { return o.engine().Changes() }
65
66// handle is the change's handle among the changes origin holds, and this
67// one, which may not be among them yet.
68func (o origin) handle(id string) string { return o.engine().Handle(id) }
69
70// fetch brings the objects named into this checkout's object store, as
71// the rebase engine fetches them: by ID, without moving a ref.
72func fetch(g git, oids ...string) error {
73 defer phase("fetch")()
74 return rebase.Fetch(context.Background(), g.engine(), oids...)
75}
76
77// readRecord reads the record a record commit holds. The commit must have
78// been fetched.
79func readRecord(g git, commit string) (*change.Record, error) {
80 defer phase("records")()
81 return rebase.ReadRecord(context.Background(), g.engine(), commit)
82}
83
84// recorded is a change that a name resolved to: its ID, and its record on
85// origin.
86type recorded struct {
87 id string
88 commit string // the record commit origin's ref points at
89 record *change.Record
90}
91
92// lookup resolves a name to a change origin holds a record for. found is
93// false when the name is a branch name rather than a change's: it is
94// written as origin/<branch>, it has no handle's shape, or it matches no
95// record. A name that matches more than one record is refused.
96func lookup(g git, o origin, name string) (n recorded, found bool, err error) {
97 handle, qualified, err := handlePart(g, name)
98 switch {
99 case err != nil:
100 return recorded{}, false, err
101 case handle == "" || strings.HasPrefix(name, "origin/"):
102 return recorded{}, false, nil
103 }
104 ids := o.changes()
105 matches := change.Matching(handle, ids)
106 switch {
107 case len(matches) == 0 && qualified:
108 return recorded{}, false, failure(fmt.Sprintf("no change on origin has the handle %s", name))
109 case len(matches) == 0:
110 return recorded{}, false, nil
111 case len(matches) > 1:
112 var handles []string
113 for _, id := range matches {
114 handles = append(handles, change.Handle(id, ids))
115 }
116 return recorded{}, false, failure(fmt.Sprintf("%s could name any of the changes %s; give more of its ID",
117 name, strings.Join(handles, ", ")))
118 }
119 n = recorded{id: matches[0], commit: o.refs[change.Ref(recordTarget, matches[0])]}
120 if err := fetch(g, n.commit); err != nil {
121 return recorded{}, false, err
122 }
123 if n.record, err = readRecord(g, n.commit); err != nil {
124 return recorded{}, false, err
125 }
126 if branch := n.record.ActiveVersion().Branch; o.refs["refs/heads/"+name] != "" && branch != name {
127 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",
128 name, n.id, name))
129 }
130 return n, true, nil
131}
132
133// handlePart is the handle a name gives, when it has a handle's shape: the
134// name itself, or what follows the colon in a name written
135// <repo>:<handle>. changes and pending qualify a handle that way when one
136// change ID is recorded in several repositories they list. git refuses a
137// colon in a ref name, so a qualified name is never a branch's. It must
138// name this repository, and qualified reports that it was written so.
139func handlePart(g git, name string) (handle string, qualified bool, err error) {
140 if change.LooksLikeHandle(name) {
141 return name, false, nil
142 }
143 repo, handle, ok := strings.Cut(name, ":")
144 if !ok || !change.LooksLikeHandle(handle) {
145 return "", false, nil
146 }
147 if here := project(g); repo != here {
148 return "", false, failure(fmt.Sprintf("%s names a change in %s, and this repository is %s", name, repo, here))
149 }
150 return handle, true, nil
151}
152
153// resolution is what the name of a change stands for. A name that is a
154// branch's sets branch alone. A name that is a change's sets every field
155// from the change's record on origin: the active version, the head that
156// version names, the branch it names, the change's state, and its owner.
157type resolution struct {
158 id, handle, head, branch, state, owner string
159 version int
160}
161
162// resolveRecorded reads a change's name for the verbs that act on a
163// change: review, approve and rebase, through runResolve. It is
164// lookupRecorded's reading. A change whose active version names no branch
165// resolves with an empty branch: approve files the head alone, and
166// bin/valley refuses it for review and rebase, which act on a branch.
167//
168// A name no record is on is a branch, and is refused unless it is a valid
169// branch name in UTF-8. The name comes from the command line, and
170// runResolve prints it in a line of fields that bin/valley splits, so a
171// name holding a separator could read as some other branch.
172func resolveRecorded(g git, name string) (resolution, error) {
173 o, n, found, err := lookupRecorded(g, name)
174 switch {
175 case err != nil:
176 return resolution{}, err
177 case !found:
178 branch := strings.TrimPrefix(name, "origin/")
179 if !change.ValidBranch(branch) || !utf8.ValidString(branch) {
180 return resolution{}, failure(fmt.Sprintf("%q names no change on origin, and is not a branch name in UTF-8", name))
181 }
182 return resolution{branch: branch}, nil
183 }
184 return o.resolution(n), nil
185}
186
187// lookupRecorded reads a change's name and returns the record it names,
188// if it names one, with the snapshot of origin it was read in. That
189// snapshot lists inventoryPatterns. A name that is a change's ID or handle
190// is that change, as lookup reads it. A branch name, written as <branch>
191// or origin/<branch>, is read against the branch each record's active
192// version names. No record on the branch leaves the name a branch, as it
193// was before changes had records. One record makes the name that record's
194// change, exactly as if its ID had been given. More than one is refused,
195// since acting on the branch would act on any of them.
196func lookupRecorded(g git, name string) (origin, recorded, bool, error) {
197 branch := strings.TrimPrefix(name, "origin/")
198 o, err := listOrigin(g, append([]string{"refs/heads/" + branch}, inventoryPatterns...)...)
199 if err != nil {
200 return origin{}, recorded{}, false, err
201 }
202 if !strings.HasPrefix(name, "origin/") {
203 n, found, err := lookup(g, o, name)
204 switch {
205 case err != nil:
206 return o, recorded{}, false, err
207 case found:
208 return o, n, true, nil
209 }
210 }
211 found, err := unlandedOn(g, o, branch)
212 if err != nil {
213 return o, recorded{}, false, err
214 }
215 switch len(found) {
216 case 0:
217 return o, recorded{}, false, nil
218 case 1:
219 return o, found[0], true, nil
220 }
221 var ids []string
222 for _, n := range found {
223 ids = append(ids, n.id)
224 }
225 return o, recorded{}, false, failure(fmt.Sprintf("the changes %s all have their active version on %s; name one by its change ID",
226 strings.Join(ids, ", "), branch))
227}
228
229// resolution is what a change's record says its name stands for: the
230// active version, the head that version names, the branch it names, the
231// change's state, and its owner.
232func (o origin) resolution(n recorded) resolution {
233 v := n.record.ActiveVersion()
234 return resolution{
235 id: n.id, handle: o.handle(n.id), version: v.N,
236 head: strings.TrimPrefix(v.Head, change.HeadPrefix), branch: v.Branch, state: n.record.State,
237 owner: n.record.Owner,
238 }
239}
240
241// unlandedOn is every change origin holds a record of whose active
242// version names branch, less each whose active version has landed, as
243// the rebase engine reads it (rebase.UnlandedOn). o must list
244// inventoryPatterns.
245func unlandedOn(g git, o origin, branch string) ([]recorded, error) {
246 found, err := rebase.UnlandedOn(context.Background(), g.engine(), o.engine(), branch, newVerifier())
247 return fromEngine(found), err
248}
249
250// runResolve prints what a change's name stands for, for the verbs
251// bin/valley runs itself, as resolveRecorded reads it: one line of fields
252// separated by tabs. For a change it is
253//
254// change <ID> <handle> <version> <head> <branch> <state> <owner>
255//
256// with the head as a full object ID, the state as the record says it:
257// ready, draft or withdrawn, and the owner as the record names it. review
258// names the owner of a draft it shows. For a branch it is
259//
260// branch <branch>
261//
262// A version may name no branch, and then the branch field is empty. A
263// branch name holds no tab, since git refuses control characters in a
264// ref name, and an owner holds none, since the record's validation allows
265// only a principal's name there. The record commit, which has the head as a parent, has been
266// fetched, so the head is in this checkout's objects.
267func runResolve(g git, args []string, w io.Writer) error {
268 if len(args) != 1 {
269 return failure("usage: valley-go resolve <change>")
270 }
271 if !g.succeeds(true, "rev-parse", "--git-dir") {
272 return failure("not a git repository")
273 }
274 r, err := resolveRecorded(g, args[0])
275 if err != nil {
276 return err
277 }
278 if r.id == "" {
279 _, err = fmt.Fprintf(w, "branch\t%s\n", r.branch)
280 return err
281 }
282 _, err = fmt.Fprintf(w, "change\t%s\t%s\t%d\t%s\t%s\t%s\t%s\n", r.id, r.handle, r.version, r.head, r.branch, r.state, r.owner)
283 return err
284}
285
286// runVersions prints every version of a change, for bin/valley's approve,
287// which approves exactly one head of a change and refuses a head no
288// version records. One line each, in order, of fields separated by tabs:
289//
290// <n> <head> <state> <title>
291//
292// with the head as a full object ID and the change's state as its record
293// says it, on every line. The title is last, since it may hold spaces; it
294// holds no tab, which is a control character. It fails when origin holds
295// no record of the change.
296func runVersions(g git, args []string, w io.Writer) error {
297 if len(args) != 1 || !change.ValidID(args[0]) {
298 return failure("usage: valley-go versions <change ID>")
299 }
300 id := args[0]
301 if !g.succeeds(true, "rev-parse", "--git-dir") {
302 return failure("not a git repository")
303 }
304 ref := change.Ref(recordTarget, id)
305 o, err := listOrigin(g, ref)
306 if err != nil {
307 return err
308 }
309 commit := o.refs[ref]
310 if commit == "" {
311 return failure("origin holds no record of change " + id)
312 }
313 if err := fetch(g, commit); err != nil {
314 return err
315 }
316 r, err := readRecord(g, commit)
317 if err != nil {
318 return err
319 }
320 var b strings.Builder
321 for _, v := range r.Versions {
322 fmt.Fprintf(&b, "%d\t%s\t%s\t%s\n", v.N, headOf(v), r.State, v.Title)
323 }
324 _, err = io.WriteString(w, b.String())
325 return err
326}
327
328// readAll reads every record origin holds, in the order of their IDs, as
329// the rebase engine reads them (rebase.ReadAll). A record that does not
330// read is kept apart, in unread, and is no change for any reader.
331func readAll(g git, o origin) (all []recorded, unread []unreadRecord, err error) {
332 defer phase("records")()
333 read, bad, err := rebase.ReadAll(context.Background(), g.engine(), o.engine())
334 for _, u := range bad {
335 unread = append(unread, unreadRecord{ref: u.Ref, commit: u.Commit, why: u.Why})
336 }
337 return fromEngine(read), unread, err
338}
339
340// fromEngine is the engine's records as this program holds them.
341func fromEngine(read []rebase.Recorded) []recorded {
342 var all []recorded
343 for _, n := range read {
344 all = append(all, recorded{id: n.ID, commit: n.Commit, record: n.Record})
345 }
346 return all
347}
348
349// engine is the record as the rebase engine holds one.
350func (n recorded) engine() rebase.Recorded {
351 return rebase.Recorded{ID: n.id, Commit: n.commit, Record: n.record}
352}
353
354// unreadRecord is a record on origin that does not read.
355type unreadRecord struct {
356 ref, commit, why string
357}
358
359// mayName reports whether a record that does not read may name one of
360// the commits from tip to head as a version head. A record names its
361// version heads as parents of its record commits, so it can name only a
362// commit its record commit reaches. That holds for some commit from tip to
363// head exactly when a merge base of the record commit and head is not on
364// tip. A record git cannot compare at all may name anything.
365func mayName(g git, u unreadRecord, head, tip string) bool {
366 out, err := g.output(true, "merge-base", "--all", u.commit, head)
367 if err != nil {
368 return exitCode(err) != 1
369 }
370 for _, base := range strings.Fields(out) {
371 if !g.succeeds(true, "merge-base", "--is-ancestor", base, tip) {
372 return true
373 }
374 }
375 return false
376}
377
378// project is the name a change's handle is printed under: origin's
379// repository, as its URL names it, without .git.
380func project(g git) string {
381 url, err := g.output(true, "remote", "get-url", "origin")
382 if err != nil {
383 return "origin"
384 }
385 url = strings.TrimRight(url, "/")
386 if i := strings.LastIndexAny(url, "/:"); i >= 0 {
387 url = url[i+1:]
388 }
389 if name := strings.TrimSuffix(url, ".git"); name != "" {
390 return name
391 }
392 return "origin"
393}
394
395// writeRecord writes a record commit holding r, with the parents given,
396// and returns its ID, as the rebase engine writes one.
397func writeRecord(g git, r *change.Record, message string, parents ...string) (string, error) {
398 return rebase.WriteRecord(context.Background(), g.engine(), r, message, parents...)
399}
400
401// pushRecord moves the change's record ref on origin from old to commit,
402// leased on old: the push is refused if the ref has moved since it was
403// read, and a record that did not exist must still not exist. The hook's
404// refusal reaches stderr through git.
405func pushRecord(g git, id, old, commit string) error {
406 if w := rebase.PushRecord(context.Background(), g.engine(), id, old, commit); w.Push != rebase.Pushed {
407 return failure("origin did not take the record of " + id)
408 }
409 return nil
410}