gunk-dev/the-valley

changes.go

source2f2d416560bcmain's published tip history
11.5 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 branch, the way changes were named before they had records.
10//
11// A name shaped like a handle is looked up among origin's records first.
12// When it matches no record, it is a branch name. A name written as
13// origin/<branch> is always a branch name. A handle that is also the name
14// of a branch on origin is refused unless the change is on that branch,
15// because the two could be different changes.
16
17package main
18
19import (
20 "bytes"
21 "fmt"
22 "io"
23 "sort"
24 "strings"
25
26 "the-valley/change"
27)
28
29// recordTarget is the one target a change may name for now. The hook
30// refuses a record for any other.
31const recordTarget = "main"
32
33// origin is one ls-remote snapshot of the refs a verb reads.
34type origin struct {
35 refs map[string]string // ref → object ID
36}
37
38// listOrigin takes one snapshot of origin's refs matching the patterns.
39// ls-remote matches a pattern against the tail of a ref name, so every ref
40// is compared whole afterwards.
41func listOrigin(g git, patterns ...string) (origin, error) {
42 out, err := g.output(false, append([]string{"ls-remote", "--refs", "origin"}, patterns...)...)
43 if err != nil {
44 return origin{}, failure("could not read origin")
45 }
46 o := origin{refs: map[string]string{}}
47 for _, line := range strings.Split(out, "\n") {
48 oid, ref, ok := strings.Cut(line, "\t")
49 if ok && ref != "" {
50 o.refs[ref] = oid
51 }
52 }
53 return o, nil
54}
55
56// recordPatterns are the ls-remote patterns that list every record.
57var recordPatterns = []string{change.RefPrefix + recordTarget + "/*"}
58
59// changes is the ID of every change origin holds a record for, in order.
60func (o origin) changes() []string {
61 var ids []string
62 for ref := range o.refs {
63 if target, id, ok := change.ParseRef(ref); ok && target == recordTarget {
64 ids = append(ids, id)
65 }
66 }
67 sort.Strings(ids)
68 return ids
69}
70
71// handle is the change's handle among the changes origin holds, and this
72// one, which may not be among them yet.
73func (o origin) handle(id string) string {
74 return change.Handle(id, append(o.changes(), id))
75}
76
77// fetch brings the objects named into this checkout's object store,
78// without writing FETCH_HEAD, moving a ref or fetching tags.
79func fetch(g git, oids ...string) error {
80 var stdin bytes.Buffer
81 for _, oid := range oids {
82 if oid != "" {
83 fmt.Fprintln(&stdin, oid)
84 }
85 }
86 if stdin.Len() == 0 {
87 return nil
88 }
89 _, err := g.input(false, &stdin, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--stdin", "origin")
90 if err != nil {
91 return failure("could not fetch from origin")
92 }
93 return nil
94}
95
96// readRecord reads the record a record commit holds. The commit must have
97// been fetched.
98func readRecord(g git, commit string) (*change.Record, error) {
99 data, err := g.output(true, "cat-file", "blob", commit+":record.json")
100 if err != nil {
101 return nil, failure(fmt.Sprintf("the change record %s holds no record.json", short(commit)))
102 }
103 r, err := change.Parse([]byte(data + "\n"))
104 if err != nil {
105 return nil, failure(fmt.Sprintf("the change record %s does not read: %v", short(commit), err))
106 }
107 return r, nil
108}
109
110// recorded is a change that a name resolved to: its ID, and its record on
111// origin.
112type recorded struct {
113 id string
114 commit string // the record commit origin's ref points at
115 record *change.Record
116}
117
118// lookup resolves a name to a change origin holds a record for. found is
119// false when the name is a branch name rather than a change's: it is
120// written as origin/<branch>, it has no handle's shape, or it matches no
121// record. A name that matches more than one record is refused.
122func lookup(g git, o origin, name string) (n recorded, found bool, err error) {
123 if strings.HasPrefix(name, "origin/") || !change.LooksLikeHandle(name) {
124 return recorded{}, false, nil
125 }
126 ids := o.changes()
127 matches := change.Matching(name, ids)
128 switch {
129 case len(matches) == 0:
130 return recorded{}, false, nil
131 case len(matches) > 1:
132 var handles []string
133 for _, id := range matches {
134 handles = append(handles, change.Handle(id, ids))
135 }
136 return recorded{}, false, failure(fmt.Sprintf("%s could name any of the changes %s; give more of its ID",
137 name, strings.Join(handles, ", ")))
138 }
139 n = recorded{id: matches[0], commit: o.refs[change.Ref(recordTarget, matches[0])]}
140 if err := fetch(g, n.commit); err != nil {
141 return recorded{}, false, err
142 }
143 if n.record, err = readRecord(g, n.commit); err != nil {
144 return recorded{}, false, err
145 }
146 if branch := n.record.ActiveVersion().Branch; o.refs["refs/heads/"+name] != "" && branch != name {
147 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",
148 name, n.id, name))
149 }
150 return n, 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, and the change's state.
157type resolution struct {
158 id, handle, head, branch, state string
159 version int
160}
161
162// resolve reads a change's name, as every verb that takes a change does.
163// A name with no handle's shape is a branch name without origin being
164// read. A change whose active version names no branch is refused, since
165// every verb that resolves a name acts on a branch too.
166func resolve(g git, name string) (resolution, error) {
167 if strings.HasPrefix(name, "origin/") || !change.LooksLikeHandle(name) {
168 return resolution{branch: strings.TrimPrefix(name, "origin/")}, nil
169 }
170 o, err := listOrigin(g, append([]string{"refs/heads/" + name}, recordPatterns...)...)
171 if err != nil {
172 return resolution{}, err
173 }
174 n, found, err := lookup(g, o, name)
175 switch {
176 case err != nil:
177 return resolution{}, err
178 case !found:
179 return resolution{branch: name}, nil
180 }
181 v := n.record.ActiveVersion()
182 r := resolution{
183 id: n.id, handle: o.handle(n.id), version: v.N,
184 head: strings.TrimPrefix(v.Head, change.HeadPrefix), branch: v.Branch, state: n.record.State,
185 }
186 if r.branch == "" {
187 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))
188 }
189 return r, nil
190}
191
192// resolveBranch is the branch a change is on: the branch its active
193// version names, when the name is a change's, and otherwise the name
194// itself, as a branch name.
195func resolveBranch(g git, name string) (string, error) {
196 r, err := resolve(g, name)
197 return r.branch, err
198}
199
200// runResolve prints what a change's name stands for, for the verbs
201// bin/valley runs itself, as one line of fields separated by tabs. For a
202// change it is
203//
204// change <ID> <handle> <version> <head> <branch> <state>
205//
206// with the head as a full object ID, and the state as the record says it:
207// ready, draft or withdrawn. For a branch it is
208//
209// branch <branch>
210//
211// A branch name holds no tab, since git refuses control characters in a
212// ref name. The record commit, which has the head as a parent, has been
213// fetched, so the head is in this checkout's objects.
214func runResolve(g git, args []string, w io.Writer) error {
215 if len(args) != 1 {
216 return failure("usage: valley-go resolve <change>")
217 }
218 if !g.succeeds(true, "rev-parse", "--git-dir") {
219 return failure("not a git repository")
220 }
221 r, err := resolve(g, args[0])
222 if err != nil {
223 return err
224 }
225 if r.id == "" {
226 _, err = fmt.Fprintf(w, "branch\t%s\n", r.branch)
227 return err
228 }
229 _, 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)
230 return err
231}
232
233// runDrafts lists every change origin holds a record of that is a draft,
234// for pending, which shows drafts apart. Each is one line of fields
235// separated by tabs:
236//
237// <handle> <version> <head> <branch>
238//
239// for the active version, with the head as a full object ID. The branch
240// is last, since it may be empty. Every record commit is fetched, and has
241// its heads as parents, so each head is in this checkout's objects.
242func runDrafts(g git, args []string, w io.Writer) error {
243 if len(args) != 0 {
244 return failure("usage: valley-go drafts")
245 }
246 if !g.succeeds(true, "rev-parse", "--git-dir") {
247 return failure("not a git repository")
248 }
249 o, err := listOrigin(g, recordPatterns...)
250 if err != nil {
251 return err
252 }
253 all, err := readAll(g, o)
254 if err != nil {
255 return err
256 }
257 for _, n := range all {
258 if n.record.State != change.Draft {
259 continue
260 }
261 v := n.record.ActiveVersion()
262 if _, err := fmt.Fprintf(w, "%s\t%d\t%s\t%s\n", o.handle(n.id), v.N,
263 strings.TrimPrefix(v.Head, change.HeadPrefix), v.Branch); err != nil {
264 return err
265 }
266 }
267 return nil
268}
269
270// readAll reads every record origin holds, in the order of their IDs.
271func readAll(g git, o origin) ([]recorded, error) {
272 ids := o.changes()
273 var commits []string
274 for _, id := range ids {
275 commits = append(commits, o.refs[change.Ref(recordTarget, id)])
276 }
277 if err := fetch(g, commits...); err != nil {
278 return nil, err
279 }
280 var all []recorded
281 for i, id := range ids {
282 r, err := readRecord(g, commits[i])
283 if err != nil {
284 return nil, err
285 }
286 all = append(all, recorded{id: id, commit: commits[i], record: r})
287 }
288 return all, nil
289}
290
291// project is the name a change's handle is printed under: origin's
292// repository, as its URL names it, without .git.
293func project(g git) string {
294 url, err := g.output(true, "remote", "get-url", "origin")
295 if err != nil {
296 return "origin"
297 }
298 url = strings.TrimRight(url, "/")
299 if i := strings.LastIndexAny(url, "/:"); i >= 0 {
300 url = url[i+1:]
301 }
302 if name := strings.TrimSuffix(url, ".git"); name != "" {
303 return name
304 }
305 return "origin"
306}
307
308// writeRecord writes a record commit holding r, with the parents given,
309// and returns its ID. Its tree holds record.json alone, as a plain file,
310// which is the only shape the hook accepts.
311func writeRecord(g git, r *change.Record, message string, parents ...string) (string, error) {
312 data, err := change.Encode(r)
313 if err != nil {
314 return "", err
315 }
316 if len(data) > maxRecordBlob {
317 return "", failure(fmt.Sprintf("the change's record would be %d bytes, more than the %d a record may be", len(data), maxRecordBlob))
318 }
319 blob, err := g.input(false, bytes.NewReader(data), "hash-object", "-w", "--stdin")
320 if err != nil {
321 return "", failure("could not write the record")
322 }
323 tree, err := g.input(false, strings.NewReader("100644 blob "+blob+"\trecord.json\n"), "mktree")
324 if err != nil {
325 return "", failure("could not write the record's tree")
326 }
327 args := []string{"commit-tree", tree}
328 for _, p := range parents {
329 args = append(args, "-p", p)
330 }
331 commit, err := g.input(false, strings.NewReader(message+"\n"), append(args, "-F", "-")...)
332 if err != nil {
333 return "", failure("could not write the record commit")
334 }
335 return commit, nil
336}
337
338// maxRecordBlob is the most bytes a record.json may hold, as the hook
339// bounds it.
340const maxRecordBlob = 64 << 10
341
342// pushRecord moves the change's record ref on origin from old to commit,
343// leased on old: the push is refused if the ref has moved since it was
344// read, and a record that did not exist must still not exist. The hook's
345// refusal reaches stderr through git.
346func pushRecord(g git, id, old, commit string) error {
347 ref := change.Ref(recordTarget, id)
348 _, err := g.output(false, "push", "--quiet", "--force-with-lease="+ref+":"+old, "origin", commit+":"+ref)
349 if err != nil {
350 return failure("origin did not take the record of " + id)
351 }
352 return nil
353}