gunk-dev/the-valley

record.go

source32276166ab1fmain's published tip history
10.6 KiB
1// Package change is the change record: the versions of one change, as the
2// valley command writes them and the valley's push hook guards them.
3//
4// A change is one piece of work aimed at a target branch, with a stable
5// ID that survives rebases. Each time its author marks a new head ready,
6// the change gains a version. The record lists every version in order,
7// says which one is active, and says whether the change is ready, a draft
8// or withdrawn.
9//
10// A record lives at refs/the-valley/changes/<target>/<change ID>. The ref
11// points at a record commit whose tree holds one file, record.json, in the
12// schema valley-change-record/v1:
13//
14// {
15// "schema": "valley-change-record/v1",
16// "change_id": "nxvpwlkmqtsrzyoukklnpmqrstuvwxyz",
17// "target": "main",
18// "owner": "klaus-env",
19// "state": "ready",
20// "seq": 1,
21// "versions": [
22// {"n": 1, "head": "git-sha1:<40 hex>", "title": "the head's subject",
23// "branch": "topic", "uploader": "klaus-env"}
24// ],
25// "active": 1
26// }
27//
28// Reading is strict. The record must be valid UTF-8, name no key twice in
29// any object, hold no field the schema does not, and hold nothing after
30// the object. Every field has exactly the type above, and every integer is
31// in range. This package is the one reading of a record: the valley
32// command reads the record it is about to extend with it, and the hook
33// reads both sides of every pushed update with it, so a record one of them
34// accepts is a record the other accepts.
35//
36// The package depends on the standard library alone, like everything that
37// uses it.
38package change
39
40import (
41 "bytes"
42 "encoding/json"
43 "errors"
44 "fmt"
45 "regexp"
46 "strconv"
47 "strings"
48 "unicode"
49 "unicode/utf8"
50)
51
52// Schema names the record format.
53const Schema = "valley-change-record/v1"
54
55// The states a change can be in. A ready change is one its owner wants
56// landed. A draft is one paused, to be readied again. A withdrawn change is
57// one given up, until it is readied again.
58const (
59 Ready = "ready"
60 Draft = "draft"
61 Withdrawn = "withdrawn"
62)
63
64// The bounds a record is held to.
65const (
66 MaxSeq = 100000 // record updates in a change's life
67 MaxVersions = 1000 // versions of one change
68 MaxTitle = 200 // bytes in a version's title
69)
70
71// HeadPrefix opens a version's head: the head is named by its hash
72// function and then its object ID.
73const HeadPrefix = "git-sha1:"
74
75// Record is one change's record.
76type Record struct {
77 Schema string `json:"schema"`
78 ChangeID string `json:"change_id"`
79 Target string `json:"target"`
80 Owner string `json:"owner"`
81 State string `json:"state"`
82 Seq int `json:"seq"`
83 Versions []Version `json:"versions"`
84 Active int `json:"active"`
85}
86
87// Version is one head a change was marked ready at.
88type Version struct {
89 N int `json:"n"`
90 Head string `json:"head"`
91 Title string `json:"title"`
92 Branch string `json:"branch"`
93 Uploader string `json:"uploader"`
94}
95
96// ActiveVersion is the version Active names. A record that parsed always
97// has one.
98func (r *Record) ActiveVersion() Version {
99 return r.Versions[r.Active-1]
100}
101
102// Last is the newest version.
103func (r *Record) Last() Version {
104 return r.Versions[len(r.Versions)-1]
105}
106
107// Parse reads record.json, strictly.
108func Parse(data []byte) (*Record, error) {
109 v, err := readJSON(data)
110 if err != nil {
111 return nil, err
112 }
113 o, err := fieldsOf(v, "the record", "schema", "change_id", "target", "owner", "state", "seq", "versions", "active")
114 if err != nil {
115 return nil, err
116 }
117 r := &Record{}
118 for _, f := range []struct {
119 name string
120 into *string
121 }{
122 {"schema", &r.Schema}, {"change_id", &r.ChangeID}, {"target", &r.Target},
123 {"owner", &r.Owner}, {"state", &r.State},
124 } {
125 if *f.into, err = stringOf(o[f.name], f.name); err != nil {
126 return nil, err
127 }
128 }
129 if r.Seq, err = integerOf(o["seq"], "seq", MaxSeq); err != nil {
130 return nil, err
131 }
132 if r.Active, err = integerOf(o["active"], "active", MaxVersions); err != nil {
133 return nil, err
134 }
135 versions := o["versions"]
136 if versions.kind != kindArray {
137 return nil, fmt.Errorf("its versions is %s, where an array is expected", versions.kind)
138 }
139 if len(versions.items) > MaxVersions {
140 return nil, fmt.Errorf("it holds %d versions, more than the %d a change may have", len(versions.items), MaxVersions)
141 }
142 for i, item := range versions.items {
143 where := fmt.Sprintf("versions[%d]", i)
144 vo, err := fieldsOf(item, where, "n", "head", "title", "branch", "uploader")
145 if err != nil {
146 return nil, err
147 }
148 var ver Version
149 if ver.N, err = integerOf(vo["n"], where+".n", MaxVersions); err != nil {
150 return nil, err
151 }
152 for _, f := range []struct {
153 name string
154 into *string
155 }{
156 {"head", &ver.Head}, {"title", &ver.Title}, {"branch", &ver.Branch}, {"uploader", &ver.Uploader},
157 } {
158 if *f.into, err = stringOf(vo[f.name], where+"."+f.name); err != nil {
159 return nil, err
160 }
161 }
162 r.Versions = append(r.Versions, ver)
163 }
164 if err := r.Check(); err != nil {
165 return nil, err
166 }
167 return r, nil
168}
169
170// Check holds a record to everything the schema says beyond the types of
171// its fields: the formats of its strings, the ranges of its integers, and
172// versions numbered 1, 2, 3 with no gap. Every string is UTF-8. git
173// accepts a branch name that is not, and encoding/json would write such a
174// name as another one, so Encode refuses it.
175func (r *Record) Check() error {
176 switch {
177 case r.Schema != Schema:
178 return fmt.Errorf("its schema is %q, where %q is expected", r.Schema, Schema)
179 case !ValidID(r.ChangeID):
180 return fmt.Errorf("its change_id %q is not a change ID: 32 letters from k to z", r.ChangeID)
181 case !ValidBranch(r.Target) || !utf8.ValidString(r.Target):
182 return fmt.Errorf("its target %q is not a branch name in UTF-8", r.Target)
183 case !ValidPrincipal(r.Owner):
184 return fmt.Errorf("its owner %q is not a principal name", r.Owner)
185 case r.State != Ready && r.State != Draft && r.State != Withdrawn:
186 return fmt.Errorf("its state is %q, where %q, %q or %q is expected", r.State, Ready, Draft, Withdrawn)
187 case r.Seq < 1 || r.Seq > MaxSeq:
188 return fmt.Errorf("its seq is %d, outside 1 to %d", r.Seq, MaxSeq)
189 case len(r.Versions) == 0:
190 return errors.New("it holds no version, and a change has at least one")
191 case len(r.Versions) > MaxVersions:
192 return fmt.Errorf("it holds %d versions, more than the %d a change may have", len(r.Versions), MaxVersions)
193 case r.Active < 1 || r.Active > len(r.Versions):
194 return fmt.Errorf("its active is %d, which names none of its %d versions", r.Active, len(r.Versions))
195 }
196 for i, v := range r.Versions {
197 where := fmt.Sprintf("versions[%d]", i)
198 switch {
199 case v.N != i+1:
200 return fmt.Errorf("its %s.n is %d, and versions are numbered 1, 2, 3 in order with no gap", where, v.N)
201 case !ValidHead(v.Head):
202 return fmt.Errorf("its %s.head %q is not %s and 40 lowercase hex digits", where, v.Head, HeadPrefix)
203 case !ValidTitle(v.Title):
204 return fmt.Errorf("its %s.title is not 1 to %d bytes free of control characters", where, MaxTitle)
205 case v.Branch != "" && (!ValidBranch(v.Branch) || !utf8.ValidString(v.Branch)):
206 return fmt.Errorf("its %s.branch %q is not a branch name in UTF-8", where, v.Branch)
207 case !ValidPrincipal(v.Uploader):
208 return fmt.Errorf("its %s.uploader %q is not a principal name", where, v.Uploader)
209 }
210 }
211 return nil
212}
213
214// Encode writes a record as record.json. It refuses a record Parse would
215// refuse, so what it writes always reads back as the same record.
216func Encode(r *Record) ([]byte, error) {
217 if err := r.Check(); err != nil {
218 return nil, fmt.Errorf("the record cannot be written: %w", err)
219 }
220 var buf bytes.Buffer
221 enc := json.NewEncoder(&buf)
222 enc.SetEscapeHTML(false)
223 enc.SetIndent("", " ")
224 if err := enc.Encode(r); err != nil {
225 return nil, err
226 }
227 return buf.Bytes(), nil
228}
229
230// fieldsOf is v's fields, when v is an object holding exactly the fields
231// named, no more and no fewer.
232func fieldsOf(v *value, what string, names ...string) (map[string]*value, error) {
233 if v.kind != kindObject {
234 return nil, fmt.Errorf("%s is %s, where an object is expected", what, v.kind)
235 }
236 for _, key := range v.keys {
237 known := false
238 for _, n := range names {
239 known = known || key == n
240 }
241 if !known {
242 return nil, fmt.Errorf("%s holds the field %q, which the schema does not have", what, key)
243 }
244 }
245 for _, n := range names {
246 if _, ok := v.fields[n]; !ok {
247 return nil, fmt.Errorf("%s has no field %q", what, n)
248 }
249 }
250 return v.fields, nil
251}
252
253func stringOf(v *value, name string) (string, error) {
254 if v.kind != kindString {
255 return "", fmt.Errorf("its %s is %s, where a string is expected", name, v.kind)
256 }
257 return v.text, nil
258}
259
260// integerOf reads an integer from 1 to max. Only a plain run of digits is
261// an integer: 3.0 and 3e0 are numbers of another type.
262func integerOf(v *value, name string, max int) (int, error) {
263 if v.kind != kindNumber {
264 return 0, fmt.Errorf("its %s is %s, where an integer is expected", name, v.kind)
265 }
266 for _, c := range []byte(v.text) {
267 if c < '0' || c > '9' {
268 return 0, fmt.Errorf("its %s is %s, where an integer is expected", name, v.text)
269 }
270 }
271 n, err := strconv.Atoi(v.text)
272 if err != nil || n < 1 || n > max {
273 return 0, fmt.Errorf("its %s is %s, outside 1 to %d", name, v.text, max)
274 }
275 return n, nil
276}
277
278// principalName is the shape of a principal's name (#PrincipalName in
279// schema/valley.cue).
280var principalName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]*$`)
281
282// ValidPrincipal reports whether s is a principal's name.
283func ValidPrincipal(s string) bool {
284 return principalName.MatchString(s)
285}
286
287// ValidHead reports whether s names a head the way a version does.
288func ValidHead(s string) bool {
289 if len(s) != len(HeadPrefix)+40 || s[:len(HeadPrefix)] != HeadPrefix {
290 return false
291 }
292 for _, c := range []byte(s[len(HeadPrefix):]) {
293 if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
294 return false
295 }
296 }
297 return true
298}
299
300// ValidTitle reports whether s may be a version's title: UTF-8, 1 to
301// MaxTitle bytes, holding no control character.
302func ValidTitle(s string) bool {
303 if len(s) < 1 || len(s) > MaxTitle || !utf8.ValidString(s) {
304 return false
305 }
306 for _, r := range s {
307 if unicode.IsControl(r) {
308 return false
309 }
310 }
311 return true
312}
313
314// Title makes a version's title from a commit's subject. Each control
315// character becomes a space, and bytes that are not UTF-8 become U+FFFD.
316// The result is cut to MaxTitle bytes at a character boundary. A subject
317// with nothing left is titled "(no subject)".
318func Title(subject string) string {
319 var b strings.Builder
320 for _, r := range strings.ToValidUTF8(subject, "�") {
321 if unicode.IsControl(r) {
322 r = ' '
323 }
324 if b.Len()+utf8.RuneLen(r) > MaxTitle {
325 break
326 }
327 b.WriteRune(r)
328 }
329 if t := strings.TrimSpace(b.String()); t != "" {
330 return t
331 }
332 return "(no subject)"
333}