gunk-dev/the-valley

changes.go

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