gunk-dev/the-valley

canon.go

source379aad7baef9main's published tip history
11.7 KiB
1package knot
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "regexp"
8 "slices"
9 "strings"
10 "unicode/utf8"
11)
12
13// The canonical form of a knot's file. Go's standard library has no YAML
14// parser, so the live graph is written in one form the Go code owns: a
15// strict subset of YAML that is still YAML, so the CUE schema and the
16// knowledge lint read the same file. The frontmatter is one line per key,
17// in the order Fields lists them:
18//
19// ---
20// type: outcome
21// id: oc-1a2b3c4
22// status: open
23// title: "Ship the plan graph"
24// created: 2026-10-15
25// created_by: "patrick"
26// parent: oc-7654321
27// blocked_by: [bd-89abcde, "cosmo:oc-0123456"]
28// ---
29//
30// The body, as markdown.
31//
32// type, id, status, created, parent and graduated_into are bare tokens.
33// Every other value is a JSON string, so no title, name or link is read as
34// anything else. A list is a flow list, sorted, of local IDs bare and of
35// everything else as JSON strings. blocked_by is written on every outcome
36// and bug, empty or not, and every other optional key only when it holds
37// something. The body follows the closing --- after one blank line, with
38// no blank line at its end, and a knot with no body ends at the ---.
39//
40// ParseKnot reads a file leniently enough to say which rule it breaks,
41// and then refuses it unless rendering what it read gives back the same
42// bytes. So there is exactly one way to write each knot.
43
44const fence = "---\n"
45
46// keyShape is a line's key, as YAML would read one from it.
47var keyShape = regexp.MustCompile(`^[a-z_][a-z0-9_]*$`)
48
49// checkText refuses content that is not valid UTF-8, or that holds a
50// control character other than newline and tab. U+FFFE and U+FFFF are
51// refused too: YAML does not allow them, so the CUE schema could not read
52// a file holding one.
53func checkText(path string, data []byte) *Error {
54 if !utf8.Valid(data) {
55 return refuse(RuleText, path, "is not valid UTF-8")
56 }
57 for i, r := range string(data) {
58 if (r < 0x20 && r != '\n' && r != '\t') || (r >= 0x7f && r <= 0x9f) || r == 0xfffe || r == 0xffff {
59 return refuse(RuleText, path, fmt.Sprintf("holds the control character %U at byte %d; a knot's text holds no control character but newline and tab", r, i))
60 }
61 }
62 return nil
63}
64
65// frontmatter splits a file into its frontmatter lines and its body. The
66// file opens with a --- line, and the next --- line closes the
67// frontmatter.
68func frontmatter(path string, data []byte) (lines []string, body string, err *Error) {
69 text := string(data)
70 if !strings.HasPrefix(text, fence) {
71 return nil, "", refuse(RuleCanonical, path, "does not open with a --- line: the file opens with its frontmatter")
72 }
73 rest := text[len(fence):]
74 if strings.HasPrefix(rest, fence) {
75 return nil, rest[len(fence):], nil
76 }
77 end := strings.Index(rest, "\n"+fence)
78 if end < 0 {
79 return nil, "", refuse(RuleCanonical, path, "has no --- line closing its frontmatter")
80 }
81 return strings.Split(rest[:end], "\n"), rest[end+1+len(fence):], nil
82}
83
84// readBody reads what follows the frontmatter leniently: one blank line
85// and then the body. Whether it is written canonically is for the
86// comparison with Render.
87func readBody(rest string) string {
88 return strings.TrimPrefix(rest, "\n")
89}
90
91// ParseKnot reads a knot's file. slug is the slug its filename carries,
92// and path is named in a refusal. It refuses a file that breaks any rule
93// about one knot alone; edges to other knots are the graph's to check.
94func ParseKnot(path, slug string, data []byte) (*Knot, error) {
95 k, err := parseKnot(path, slug, data)
96 if err != nil {
97 return nil, err
98 }
99 return k, nil
100}
101
102func parseKnot(path, slug string, data []byte) (*Knot, *Error) {
103 if len(data) > MaxKnotSize {
104 return nil, refuse(RuleLimit, path, fmt.Sprintf("is %d bytes, more than the %d a knot may be", len(data), MaxKnotSize))
105 }
106 if err := checkText(path, data); err != nil {
107 return nil, err
108 }
109 lines, rest, err := frontmatter(path, data)
110 if err != nil {
111 return nil, err
112 }
113 k := &Knot{Slug: slug, Body: readBody(rest)}
114 seen := map[string]bool{}
115 for _, line := range lines {
116 key, value, ok := strings.Cut(line, ": ")
117 if !ok {
118 key, value = strings.TrimSuffix(line, ":"), ""
119 }
120 f, known := FieldNamed(key)
121 switch {
122 case !known && keyShape.MatchString(key):
123 return nil, refuse(RuleFieldOnType, path, fmt.Sprintf("holds the key %s, and a knot's keys are %s", key, strings.Join(FieldNames(""), ", ")))
124 case !known:
125 return nil, refuse(RuleCanonical, path, fmt.Sprintf("holds the line %q, and each line of a knot's frontmatter is one key and its value", line))
126 }
127 if seen[key] {
128 return nil, refuse(RuleCanonical, path, fmt.Sprintf("names %s twice", key))
129 }
130 seen[key] = true
131 if err := k.read(path, f, value); err != nil {
132 return nil, err
133 }
134 }
135 if err := k.check(path); err != nil {
136 return nil, err
137 }
138 if k.Body != NormalBody(k.Body) {
139 return nil, refuse(RuleCanonical, path, "its body opens or ends with a blank line, or does not end with a newline")
140 }
141 if want := Render(k); !bytes.Equal(want, data) {
142 return nil, refuse(RuleCanonical, path, "is not in canonical form, which is:\n"+string(want))
143 }
144 return k, nil
145}
146
147// read sets one field from its written value.
148func (k *Knot) read(path string, f Field, value string) *Error {
149 var s string
150 var list []string
151 var err error
152 switch f.Kind {
153 case "list":
154 list, err = readList(value)
155 default:
156 s, err = readScalar(value)
157 }
158 if err != nil {
159 return refuse(RuleCanonical, path, fmt.Sprintf("%s: %v", f.Name, err))
160 }
161 switch f.Name {
162 case "type":
163 k.Type = s
164 case "id":
165 k.ID = s
166 case "status":
167 k.Status = s
168 case "title":
169 k.Title = s
170 case "created":
171 k.Created = s
172 case "created_by":
173 k.CreatedBy = s
174 case "source":
175 k.Source = s
176 case "parent":
177 k.Parent = s
178 case "owner":
179 k.Owner = s
180 case "blocked_by":
181 k.BlockedBy = list
182 case "claimed_by":
183 k.ClaimedBy = s
184 case "claimed_at":
185 k.ClaimedAt = s
186 case "changes":
187 k.Changes = list
188 case "target":
189 k.Target = s
190 case "graduated_into":
191 k.GraduatedInto = s
192 }
193 return nil
194}
195
196// readScalar reads a bare token or a JSON string.
197func readScalar(value string) (string, error) {
198 if strings.HasPrefix(value, `"`) {
199 var s string
200 if err := json.Unmarshal([]byte(value), &s); err != nil {
201 return "", fmt.Errorf("%s is not a JSON string", value)
202 }
203 return s, nil
204 }
205 if value == "" || strings.ContainsAny(value, " \t[]{},#&*!|>'%@`") {
206 return "", fmt.Errorf("%q is neither a bare token nor a JSON string", value)
207 }
208 return value, nil
209}
210
211// readList reads a flow list of bare tokens and JSON strings.
212func readList(value string) ([]string, error) {
213 if !strings.HasPrefix(value, "[") || !strings.HasSuffix(value, "]") {
214 return nil, fmt.Errorf("%q is not a flow list, [a, b]", value)
215 }
216 inner := value[1 : len(value)-1]
217 list := []string{}
218 for len(inner) > 0 {
219 var item string
220 if strings.HasPrefix(inner, `"`) {
221 end := 1
222 for end < len(inner) && inner[end] != '"' {
223 if inner[end] == '\\' {
224 end++
225 }
226 end++
227 }
228 if end >= len(inner) {
229 return nil, fmt.Errorf("%s holds an unclosed string", value)
230 }
231 if err := json.Unmarshal([]byte(inner[:end+1]), &item); err != nil {
232 return nil, fmt.Errorf("%s holds a string that is not JSON", value)
233 }
234 inner = inner[end+1:]
235 } else {
236 cut := strings.Index(inner, ",")
237 if cut < 0 {
238 cut = len(inner)
239 }
240 item = strings.TrimSpace(inner[:cut])
241 inner = inner[cut:]
242 if item == "" {
243 return nil, fmt.Errorf("%s holds an empty entry", value)
244 }
245 }
246 list = append(list, item)
247 inner = strings.TrimSpace(inner)
248 if inner == "" {
249 break
250 }
251 if !strings.HasPrefix(inner, ",") {
252 return nil, fmt.Errorf("%s does not separate its entries with commas", value)
253 }
254 inner = strings.TrimSpace(inner[1:])
255 if inner == "" {
256 return nil, fmt.Errorf("%s ends with a comma", value)
257 }
258 }
259 return list, nil
260}
261
262// Render writes a knot in its canonical form.
263func Render(k *Knot) []byte {
264 var b bytes.Buffer
265 b.WriteString(fence)
266 line := func(key, value string) { b.WriteString(key + ": " + value + "\n") }
267 work := slices.Contains(workTypes, k.Type)
268 line("type", k.Type)
269 line("id", k.ID)
270 line("status", k.Status)
271 line("title", quote(k.Title))
272 line("created", k.Created)
273 line("created_by", quote(k.CreatedBy))
274 if k.Source != "" {
275 line("source", quote(k.Source))
276 }
277 if k.Parent != "" {
278 line("parent", k.Parent)
279 }
280 if k.Owner != "" {
281 line("owner", quote(k.Owner))
282 }
283 if work || len(k.BlockedBy) > 0 {
284 line("blocked_by", renderList(k.BlockedBy))
285 }
286 if k.ClaimedBy != "" {
287 line("claimed_by", quote(k.ClaimedBy))
288 }
289 if k.ClaimedAt != "" {
290 line("claimed_at", quote(k.ClaimedAt))
291 }
292 if len(k.Changes) > 0 {
293 line("changes", renderList(k.Changes))
294 }
295 if k.Target != "" {
296 line("target", quote(k.Target))
297 }
298 if k.GraduatedInto != "" {
299 line("graduated_into", k.GraduatedInto)
300 }
301 b.WriteString(fence)
302 if k.Body != "" {
303 b.WriteString("\n" + k.Body)
304 }
305 return b.Bytes()
306}
307
308// NormalBody is text as a knot's or a comment's body holds it: with no
309// blank line at either end, no space at the end of the text, and one
310// newline after its last line, or "" when it holds nothing.
311func NormalBody(text string) string {
312 text = strings.ReplaceAll(text, "\r\n", "\n")
313 lines := strings.Split(text, "\n")
314 for len(lines) > 0 && strings.TrimSpace(lines[0]) == "" {
315 lines = lines[1:]
316 }
317 for len(lines) > 0 && strings.TrimSpace(lines[len(lines)-1]) == "" {
318 lines = lines[:len(lines)-1]
319 }
320 if len(lines) == 0 {
321 return ""
322 }
323 return strings.Join(lines, "\n") + "\n"
324}
325
326func renderList(list []string) string {
327 sorted := slices.Clone(list)
328 slices.Sort(sorted)
329 sorted = slices.Compact(sorted)
330 items := make([]string, len(sorted))
331 for i, item := range sorted {
332 if IsLocalID(item) {
333 items[i] = item
334 } else {
335 items[i] = quote(item)
336 }
337 }
338 return "[" + strings.Join(items, ", ") + "]"
339}
340
341// quote writes s as a JSON string, leaving <, > and & as they are.
342func quote(s string) string {
343 var b bytes.Buffer
344 enc := json.NewEncoder(&b)
345 enc.SetEscapeHTML(false)
346 _ = enc.Encode(s)
347 return strings.TrimSuffix(b.String(), "\n")
348}
349
350// ParseComment reads a comment's file:
351//
352// ---
353// author: "patrick"
354// ---
355//
356// The comment, as markdown.
357//
358// The body is required, and the form is as canonical as a knot's.
359func ParseComment(path string, data []byte) (*Comment, error) {
360 c, err := parseComment(path, data)
361 if err != nil {
362 return nil, err
363 }
364 return c, nil
365}
366
367func parseComment(path string, data []byte) (*Comment, *Error) {
368 if len(data) > MaxCommentSize {
369 return nil, refuse(RuleLimit, path, fmt.Sprintf("is %d bytes, more than the %d a comment may be", len(data), MaxCommentSize))
370 }
371 if err := checkText(path, data); err != nil {
372 return nil, err
373 }
374 lines, rest, err := frontmatter(path, data)
375 if err != nil {
376 return nil, err
377 }
378 c := &Comment{Body: readBody(rest)}
379 if len(lines) != 1 || !strings.HasPrefix(lines[0], "author: ") {
380 return nil, refuse(RuleCanonical, path, "a comment's frontmatter is one line, author: \"<principal>\"")
381 }
382 author, rerr := readScalar(strings.TrimPrefix(lines[0], "author: "))
383 if rerr != nil {
384 return nil, refuse(RuleCanonical, path, "author: "+rerr.Error())
385 }
386 c.Author = author
387 switch {
388 case !IsName(c.Author):
389 return nil, refuse(RuleFieldShape, path, fmt.Sprintf("its author %q is not a principal's name", c.Author))
390 case c.Body == "":
391 return nil, refuse(RuleRequired, path, "a comment has a body")
392 case c.Body != NormalBody(c.Body):
393 return nil, refuse(RuleCanonical, path, "its body opens or ends with a blank line, or does not end with a newline")
394 }
395 if want := RenderComment(c); !bytes.Equal(want, data) {
396 return nil, refuse(RuleCanonical, path, "is not in canonical form, which is:\n"+string(want))
397 }
398 return c, nil
399}
400
401// RenderComment writes a comment in its canonical form.
402func RenderComment(c *Comment) []byte {
403 return []byte(fence + "author: " + quote(c.Author) + "\n" + fence + "\n" + c.Body)
404}