gunk-dev/the-valley

knot_test.go

source8acdd24b6d8amain's published tip history
26.9 KiB
1package knot
2
3import (
4 "crypto/sha1"
5 "encoding/hex"
6 "errors"
7 "fmt"
8 "path"
9 "sort"
10 "strings"
11 "testing"
12 "time"
13)
14
15// tree is a graph's files in memory, each named by the SHA-1 of its
16// content, as git would name it.
17type tree map[string]string
18
19func oid(content string) string {
20 sum := sha1.Sum([]byte(content))
21 return hex.EncodeToString(sum[:])
22}
23
24func (t tree) entries() []Entry {
25 var es []Entry
26 dirs := map[string]bool{}
27 for p, content := range t {
28 es = append(es, Entry{Path: p, Mode: "100644", OID: oid(content)})
29 for d := path.Dir(p); d != "."; d = path.Dir(d) {
30 dirs[d] = true
31 }
32 }
33 for d := range dirs {
34 es = append(es, Entry{Path: d, Mode: "40000"})
35 }
36 sort.Slice(es, func(i, j int) bool { return es[i].Path < es[j].Path })
37 return es
38}
39
40func (t tree) index(tb testing.TB) *Index {
41 tb.Helper()
42 idx, err := Layout(t.entries())
43 if err != nil {
44 tb.Fatalf("layout: %v", err)
45 }
46 return idx
47}
48
49func (t tree) reader() Reader {
50 byOID := map[string]string{}
51 for _, content := range t {
52 byOID[oid(content)] = content
53 }
54 return func(id string, max int) ([]byte, error) {
55 content, ok := byOID[id]
56 if !ok {
57 return nil, errors.New("names an object the push did not bring")
58 }
59 if len(content) > max {
60 return nil, fmt.Errorf("is %d bytes, more than %d", len(content), max)
61 }
62 return []byte(content), nil
63 }
64}
65
66func (t tree) with(knots ...*Knot) tree {
67 out := tree{}
68 for p, c := range t {
69 out[p] = c
70 }
71 for _, k := range knots {
72 out[k.Path()] = string(Render(k))
73 }
74 return out
75}
76
77func newKnot(t, title string) *Knot {
78 ty, _ := TypeNamed(t)
79 slug := Slug(title)
80 k := &Knot{Type: t, ID: DeriveID(ty, slug), Slug: slug, Status: ty.Initial(), Title: title,
81 Created: "2026-10-15", CreatedBy: "operator"}
82 if t == "outcome" || t == "bug" {
83 k.BlockedBy = []string{}
84 }
85 return k
86}
87
88// ruleOf is the rule err refuses under, or "" for no refusal.
89func ruleOf(err error) Rule {
90 var e *Error
91 if errors.As(err, &e) {
92 return e.Rule
93 }
94 if err != nil {
95 return "unruled: " + Rule(err.Error())
96 }
97 return ""
98}
99
100func push(old, new tree, pusher string) error {
101 p := Push{New: new.indexOrNil(), Read: new.mergedReader(old), Pusher: pusher}
102 if p.New == nil {
103 _, err := Layout(new.entries())
104 return err
105 }
106 if old != nil {
107 p.Old = old.indexOrNil()
108 }
109 return p.Check()
110}
111
112func (t tree) indexOrNil() *Index {
113 idx, err := Layout(t.entries())
114 if err != nil {
115 return nil
116 }
117 return idx
118}
119
120// mergedReader reads objects of both trees, as a repository holding both
121// would.
122func (t tree) mergedReader(old tree) Reader {
123 all := tree{}
124 for p, c := range old {
125 all["old/"+p] = c
126 }
127 for p, c := range t {
128 all[p] = c
129 }
130 return all.reader()
131}
132
133func TestTheCanonicalFormReadsBackExactly(t *testing.T) {
134 k := newKnot("outcome", "Ship the \"plan\" graph <now> & then")
135 k.Status, k.Parent, k.Owner, k.Source = "in-progress", "oc-1234567", "alice", "2026-10-15, a design"
136 k.BlockedBy = []string{"oc-89abcde", "bd-0123456", "app:oc-7654321"}
137 k.ClaimedBy, k.ClaimedAt = "run-1", "2026-10-15T00:58:00Z"
138 k.Changes = []string{"https://github.com/a/b/pull/3", "valley:x/kkkkllllmmmmnnnnooooppppqqqqrrrr"}
139 k.Target = "app:bd-0123456"
140 k.Body = "A body.\n\n\twith a tab, and ünïcode.\n"
141 data := Render(k)
142 want := `---
143type: outcome
144id: ` + k.ID + `
145status: in-progress
146title: "Ship the \"plan\" graph <now> & then"
147created: 2026-10-15
148created_by: "operator"
149source: "2026-10-15, a design"
150parent: oc-1234567
151owner: "alice"
152blocked_by: ["app:oc-7654321", bd-0123456, oc-89abcde]
153claimed_by: "run-1"
154claimed_at: "2026-10-15T00:58:00Z"
155changes: ["https://github.com/a/b/pull/3", "valley:x/kkkkllllmmmmnnnnooooppppqqqqrrrr"]
156target: "app:bd-0123456"
157---
158
159A body.
160
161 with a tab, and ünïcode.
162`
163 if string(data) != want {
164 t.Fatalf("Render =\n%s\nwant\n%s", data, want)
165 }
166 got, err := ParseKnot(k.Path(), k.Slug, data)
167 if err != nil {
168 t.Fatal(err)
169 }
170 if string(Render(got)) != want {
171 t.Errorf("a parsed knot renders as\n%s", Render(got))
172 }
173
174 // Each of these says the same thing in YAML, or nearly, and each is
175 // refused, so there is one way to write the knot.
176 canonical := string(data)
177 for _, c := range []struct{ what, from, to string }{
178 {"keys out of order", "status: in-progress\ntitle: ", "title: \"x\"\nstatus: in-progress\ntitle: "},
179 {"a string written bare", `created_by: "operator"`, "created_by: operator"},
180 {"a token written as a string", "status: in-progress", `status: "in-progress"`},
181 {"a list out of order", `["app:oc-7654321", bd-0123456, oc-89abcde]`, `[oc-89abcde, bd-0123456, "app:oc-7654321"]`},
182 {"an entry twice", `["app:oc-7654321", bd-0123456, oc-89abcde]`, `["app:oc-7654321", bd-0123456, bd-0123456, oc-89abcde]`},
183 {"a local id quoted", `, bd-0123456,`, `, "bd-0123456",`},
184 {"a list without spaces", `["app:oc-7654321", bd-0123456, oc-89abcde]`, `["app:oc-7654321",bd-0123456,oc-89abcde]`},
185 {"a block list", "changes: [\"https://github.com/a/b/pull/3\", \"valley:x/kkkkllllmmmmnnnnooooppppqqqqrrrr\"]", "changes:\n - \"https://github.com/a/b/pull/3\""},
186 {"an escape where a character would do", `"Ship the`, `"` + "\\" + `u0053hip the`},
187 {"two spaces after a key", "owner: ", "owner: "},
188 {"a space at the end of a line", "status: in-progress\n", "status: in-progress \n"},
189 {"a YAML comment", "status: in-progress\n", "status: in-progress\n# a comment\n"},
190 {"no blank line before the body", "---\n\nA body.", "---\nA body."},
191 {"two blank lines before the body", "---\n\nA body.", "---\n\n\nA body."},
192 {"a blank line at the end", "ünïcode.\n", "ünïcode.\n\n"},
193 {"no newline at the end", "ünïcode.\n", "ünïcode."},
194 {"a key named twice", "owner: \"alice\"\n", "owner: \"alice\"\nowner: \"alice\"\n"},
195 {"an empty optional key", "owner: \"alice\"\n", "owner: \"\"\n"},
196 {"an empty optional list", "target:", "changes: []\ntarget:"},
197 } {
198 variant := strings.Replace(canonical, c.from, c.to, 1)
199 if variant == canonical {
200 t.Fatalf("%s: the edit changed nothing", c.what)
201 }
202 _, err := ParseKnot(k.Path(), k.Slug, []byte(variant))
203 if r := ruleOf(err); r != RuleCanonical && r != RuleFieldShape {
204 t.Errorf("%s: rule %q, want canonical: %v", c.what, r, err)
205 }
206 }
207}
208
209func TestTextHoldsNoControlCharacters(t *testing.T) {
210 k := newKnot("bug", "A bug")
211 for _, bad := range []string{"\x1b[31m", "\r", "\x00", "\u0085", "\x7f", "￾", "\xff"} {
212 k.Body = "text " + bad + " more\n"
213 if _, err := ParseKnot(k.Path(), k.Slug, Render(k)); ruleOf(err) != RuleText {
214 t.Errorf("a body holding %q: %v, want a refusal under %s", bad, err, RuleText)
215 }
216 }
217 for _, good := range []string{"\t", "​", "日本"} {
218 k.Body = "text " + good + " more\n"
219 if _, err := ParseKnot(k.Path(), k.Slug, Render(k)); err != nil {
220 t.Errorf("a body holding %q: %v", good, err)
221 }
222 }
223 // A title is a JSON string, which can write a control character as
224 // an escape: the file holds none, and the title it reads as does.
225 for _, title := range []string{"two\nlines", "a \x1b[2J clear", "a \u0007 bell", "a\ttab"} {
226 k.Body, k.Title = "", title
227 if _, err := ParseKnot(k.Path(), k.Slug, Render(k)); ruleOf(err) != RuleText {
228 t.Errorf("the title %q: %v", title, err)
229 }
230 }
231}
232
233func TestEdgesFormNoCycle(t *testing.T) {
234 a, b, c := newKnot("outcome", "A"), newKnot("outcome", "B"), newKnot("outcome", "C")
235 acyclic := tree{}.with(a, b, c)
236 if err := Validate(acyclic.index(t), acyclic.reader()); err != nil {
237 t.Fatal(err)
238 }
239 link := func(f func(a, b, c *Knot)) tree {
240 a, b, c := a.Clone(), b.Clone(), c.Clone()
241 f(a, b, c)
242 return tree{}.with(a, b, c)
243 }
244 for _, x := range []struct {
245 what string
246 graph tree
247 rule Rule
248 }{
249 {"a parent loop", link(func(a, b, c *Knot) { a.Parent, b.Parent, c.Parent = b.ID, c.ID, a.ID }), RuleCycle},
250 {"a knot its own parent", link(func(a, b, c *Knot) { a.Parent = a.ID }), RuleCycle},
251 {"a blocker loop", link(func(a, b, c *Knot) {
252 a.BlockedBy, b.BlockedBy = []string{b.ID}, []string{c.ID, "x:oc-1234567"}
253 c.BlockedBy = []string{a.ID}
254 }), RuleCycle},
255 {"a knot blocking itself", link(func(a, b, c *Knot) { b.BlockedBy = []string{b.ID} }), RuleCycle},
256 // A milestone waiting on its own work item is no cycle: the two
257 // kinds of edge are checked apart.
258 {"a parent waiting on its child", link(func(a, b, c *Knot) { b.Parent = a.ID; a.BlockedBy = []string{b.ID} }), ""},
259 {"a diamond", link(func(a, b, c *Knot) { a.BlockedBy = []string{b.ID, c.ID}; b.BlockedBy = []string{c.ID} }), ""},
260 } {
261 err := Validate(x.graph.index(t), x.graph.reader())
262 if ruleOf(err) != x.rule {
263 t.Errorf("%s: %v, want rule %q", x.what, err, x.rule)
264 }
265 }
266
267 // A push is checked from what it changes, and that finds a cycle the
268 // push closes even when the knot it changes is not on the loop's
269 // first edge.
270 before := link(func(a, b, c *Knot) { a.BlockedBy = []string{b.ID}; b.BlockedBy = []string{c.ID} })
271 after := link(func(a, b, c *Knot) {
272 a.BlockedBy = []string{b.ID}
273 b.BlockedBy = []string{c.ID}
274 c.BlockedBy = []string{a.ID}
275 })
276 if err := push(before, after, "operator"); ruleOf(err) != RuleCycle {
277 t.Errorf("a push closing a loop: %v", err)
278 }
279}
280
281func TestWhatAPushMayChange(t *testing.T) {
282 a, b := newKnot("outcome", "A"), newKnot("idea", "B")
283 comment := CommentsDirectory + "/" + a.ID + "/20261015T005800Z-0123456789abcdef.md"
284 before := tree{}.with(a, b)
285 before[comment] = string(RenderComment(&Comment{Author: "operator", Body: "Noted.\n"}))
286 if err := push(nil, before, "operator"); err != nil {
287 t.Fatalf("the create: %v", err)
288 }
289 if err := push(nil, before, "alice"); ruleOf(err) != RuleProvenance {
290 t.Errorf("a create naming another creator: %v", err)
291 }
292 change := func(f func(t tree)) tree {
293 next := tree{}
294 for p, c := range before {
295 next[p] = c
296 }
297 f(next)
298 return next
299 }
300 edited := func(f func(k *Knot)) func(t tree) {
301 return func(t tree) {
302 k := a.Clone()
303 f(k)
304 delete(t, a.Path())
305 t[k.Path()] = string(Render(k))
306 }
307 }
308 for _, x := range []struct {
309 what string
310 after tree
311 pusher string
312 rule Rule
313 }{
314 {"a status change by anyone", change(edited(func(k *Knot) { k.Status = "done" })), "alice", ""},
315 {"a new knot by its creator", change(func(t tree) { k := newKnot("bug", "New"); k.CreatedBy = "alice"; t[k.Path()] = string(Render(k)) }), "alice", ""},
316 {"a new knot naming another creator", change(func(t tree) { k := newKnot("bug", "New"); t[k.Path()] = string(Render(k)) }), "alice", RuleProvenance},
317 {"a comment by its author", change(func(t tree) {
318 t[CommentsDirectory+"/"+b.ID+"/20261016T000000Z-0123456789abcdef.md"] = string(RenderComment(&Comment{Author: "alice", Body: "Yes.\n"}))
319 }), "alice", ""},
320 {"a comment naming another author", change(func(t tree) {
321 t[CommentsDirectory+"/"+b.ID+"/20261016T000000Z-0123456789abcdef.md"] = string(RenderComment(&Comment{Author: "operator", Body: "Yes.\n"}))
322 }), "alice", RuleProvenance},
323 {"a comment stamped with no time", change(func(t tree) {
324 t[CommentsDirectory+"/"+b.ID+"/20261315T000000Z-0123456789abcdef.md"] = string(RenderComment(&Comment{Author: "operator", Body: "Yes.\n"}))
325 }), "operator", RuleLayout},
326 {"a comment on no knot", change(func(t tree) {
327 t[CommentsDirectory+"/oc-0000000/20261016T000000Z-0123456789abcdef.md"] = string(RenderComment(&Comment{Author: "operator", Body: "Yes.\n"}))
328 }), "operator", RuleEdgeResolves},
329 {"a changed comment that records no edit", change(func(t tree) { t[comment] = string(RenderComment(&Comment{Author: "operator", Body: "Unsaid.\n"})) }), "operator", RuleProvenance},
330 {"a deleted comment", change(func(t tree) { delete(t, comment) }), "operator", RuleTransition},
331 {"a deleted knot", change(func(t tree) { delete(t, b.Path()) }), "operator", RuleTransition},
332 {"a moved knot", change(func(t tree) {
333 k := b.Clone()
334 k.Slug = "b-2"
335 k.ID = DeriveID(k.TypeOf(), k.Slug)
336 delete(t, b.Path())
337 t[k.Path()] = string(Render(k))
338 }), "operator", RuleTransition},
339 {"a changed created_by", change(edited(func(k *Knot) { k.CreatedBy = "alice" })), "alice", RuleTransition},
340 {"a changed created date", change(edited(func(k *Knot) { k.Created = "2026-10-16" })), "operator", RuleTransition},
341 {"a changed type", change(func(t tree) {
342 k := a.Clone()
343 k.Type, k.BlockedBy = "bug", []string{}
344 t[a.Path()] = string(Render(k))
345 }), "operator", RuleIDShape},
346 {"a changed id", change(func(t tree) { k := a.Clone(); k.ID = "oc-0000000"; t[a.Path()] = string(Render(k)) }), "operator", RuleFilename},
347 {"an edge to no knot", change(edited(func(k *Knot) { k.BlockedBy = []string{"oc-0000000"} })), "operator", RuleEdgeResolves},
348 {"a parent that is an idea", change(edited(func(k *Knot) { k.Parent = b.ID })), "operator", RuleParentOutcome},
349 {"a claim with no time", change(edited(func(k *Knot) { k.ClaimedBy = "run" })), "operator", RuleClaim},
350 } {
351 if err := push(before, x.after, x.pusher); ruleOf(err) != x.rule {
352 t.Errorf("%s: %v, want rule %q", x.what, err, x.rule)
353 }
354 }
355}
356
357// A comment is edited in place: the edit replaces its body, keeps its
358// author, and records who edited it and when. Its author edits it, and
359// another principal only where the push's MayEdit allows, as the hook's
360// grants do. A whole graph is held to the form of its comments alone.
361func TestWhoMayEditAComment(t *testing.T) {
362 a := newKnot("outcome", "A")
363 a.CreatedBy = "alice"
364 id := "20261025T120000Z-0123456789abcdef"
365 at := CommentPath(a.ID, id)
366 written := &Comment{Author: "alice", Body: "First thought.\n"}
367 before := tree{}.with(a)
368 before[at] = string(RenderComment(written))
369 if err := (Push{New: before.index(t), Read: before.reader(), Pusher: "alice"}).Check(); err != nil {
370 t.Fatalf("the create: %v", err)
371 }
372 with := func(c Comment) tree {
373 next := tree{}.with(a)
374 next[at] = string(RenderComment(&c))
375 return next
376 }
377 edit := func(by, body string) Comment {
378 return Comment{Author: "alice", Body: body, Edited: "2026-10-25T13:00:00Z", EditedBy: by}
379 }
380 byApprover := func(string) error { return nil }
381 refusing := func(string) error { return errors.New("only an approver edits another's comment") }
382 for _, x := range []struct {
383 what string
384 before tree
385 after tree
386 pusher string
387 mayEdit func(string) error
388 rule Rule
389 }{
390 {"its author's edit", before, with(edit("alice", "Second thought.\n")), "alice", nil, ""},
391 {"its author's second edit", with(edit("alice", "Second thought.\n")), with(edit("alice", "Third thought.\n")), "alice", nil, ""},
392 {"another's edit, with no MayEdit", before, with(edit("operator", "Removed.\n")), "operator", nil, RuleTransition},
393 {"another's edit, which MayEdit allows", before, with(edit("operator", "Removed.\n")), "operator", byApprover, ""},
394 {"another's edit, which MayEdit refuses", before, with(edit("operator", "Removed.\n")), "operator", refusing, RuleTransition},
395 {"an edit that records no edit", before, with(Comment{Author: "alice", Body: "Quietly.\n"}), "alice", nil, RuleProvenance},
396 {"an edit naming another editor", before, with(edit("operator", "Not mine.\n")), "alice", byApprover, RuleProvenance},
397 {"an edit that changes the author", before, with(Comment{Author: "operator", Body: "Mine now.\n", Edited: "2026-10-25T13:00:00Z", EditedBy: "operator"}), "operator", byApprover, RuleTransition},
398 {"an edit that deletes the comment", before, tree{}.with(a), "alice", nil, RuleTransition},
399 {"a new comment that records an edit", tree{}.with(a), with(edit("alice", "Never written.\n")), "alice", nil, RuleProvenance},
400 {"a create whose comment records an edit", nil, with(edit("alice", "Never written.\n")), "alice", nil, RuleProvenance},
401 } {
402 p := Push{New: x.after.index(t), Read: x.after.mergedReader(x.before), Pusher: x.pusher, MayEdit: x.mayEdit}
403 if x.before != nil {
404 p.Old = x.before.index(t)
405 }
406 err := p.Check()
407 if ruleOf(err) != x.rule {
408 t.Errorf("%s: %v, want rule %q", x.what, err, x.rule)
409 }
410 }
411 refused := Push{Old: before.index(t), New: with(edit("operator", "Removed.\n")).index(t), Pusher: "operator", MayEdit: refusing,
412 Read: with(edit("operator", "Removed.\n")).mergedReader(before)}.Check()
413 if refused == nil || !strings.Contains(refused.Error(), "a comment by alice, and operator is editing it: only an approver edits another's comment") {
414 t.Errorf("a refused edit does not say whose comment it is, who edits it, and MayEdit's reason: %v", refused)
415 }
416
417 // A whole graph holds edited comments, and what it reads of one is
418 // what the edit wrote.
419 edited := with(edit("operator", "Removed.\n"))
420 g, err := Load(edited.index(t), edited.reader())
421 if err != nil {
422 t.Fatalf("a graph with an edited comment: %v", err)
423 }
424 if n := g.Comments[a.ID][0]; n.ID != id || n.Author != "alice" || n.EditedBy != "operator" || n.Edited != "2026-10-25T13:00:00Z" || n.Body != "Removed.\n" {
425 t.Errorf("the edited comment reads as %+v", n)
426 }
427}
428
429// A comment's frontmatter is the author line, and on an edited comment the
430// two edit lines after it, both or neither. A comment written before edits
431// existed reads and writes back unchanged.
432func TestACommentsForm(t *testing.T) {
433 legacy := "---\nauthor: \"alice\"\n---\n\nNoted.\n"
434 c, err := ParseComment("c", []byte(legacy))
435 if err != nil || c.Edited != "" || c.EditedBy != "" || string(RenderComment(c)) != legacy {
436 t.Fatalf("a comment that was never edited reads as %+v, %v", c, err)
437 }
438 edited := "---\nauthor: \"alice\"\nedited: \"2026-10-25T13:00:00Z\"\nedited_by: \"operator\"\n---\n\nNoted.\n"
439 if c, err := ParseComment("c", []byte(edited)); err != nil || string(RenderComment(c)) != edited {
440 t.Fatalf("an edited comment reads as %+v, %v", c, err)
441 }
442 for _, x := range []struct {
443 what, front string
444 rule Rule
445 }{
446 {"the edit lines in the other order", "author: \"alice\"\nedited_by: \"operator\"\nedited: \"2026-10-25T13:00:00Z\"\n", RuleCanonical},
447 {"the author after the edit", "edited: \"2026-10-25T13:00:00Z\"\nedited_by: \"operator\"\nauthor: \"alice\"\n", RuleCanonical},
448 {"edited alone", "author: \"alice\"\nedited: \"2026-10-25T13:00:00Z\"\n", RuleProvenance},
449 {"edited_by alone", "author: \"alice\"\nedited_by: \"operator\"\n", RuleProvenance},
450 {"an edit time that is no UTC time", "author: \"alice\"\nedited: \"2026-10-25 13:00\"\nedited_by: \"operator\"\n", RuleFieldShape},
451 {"an editor that is no name", "author: \"alice\"\nedited: \"2026-10-25T13:00:00Z\"\nedited_by: \"two words\"\n", RuleFieldShape},
452 {"an edit time as a bare token", "author: \"alice\"\nedited: 2026-10-25T13:00:00Z\nedited_by: \"operator\"\n", RuleCanonical},
453 {"an author named twice", "author: \"alice\"\nauthor: \"alice\"\n", RuleCanonical},
454 {"no author", "edited: \"2026-10-25T13:00:00Z\"\nedited_by: \"operator\"\n", RuleCanonical},
455 {"another key", "author: \"alice\"\nowner: \"alice\"\n", RuleCanonical},
456 } {
457 if _, err := ParseComment("c", []byte("---\n"+x.front+"---\n\nNoted.\n")); ruleOf(err) != x.rule {
458 t.Errorf("%s: %v, want rule %q", x.what, err, x.rule)
459 }
460 }
461 if !IsCommentID("20261025T120000Z-0123456789abcdef") || IsCommentID("20261025T120000Z-0123456789abcdef.md") ||
462 IsCommentID("../oc-1234567/20261025T120000Z-0123456789abcdef") {
463 t.Error("IsCommentID does not hold a comment's ID to <stamp>-<op>")
464 }
465}
466
467// A listing is read as git writes a tree: every directory is an entry of
468// its own, in the mode 40000 exactly. A tree written by hand can name a
469// file ideas/<id>-<slug>.md at its root, which lists no ideas directory,
470// or a directory in the mode 040000, which git reads as a tree and never
471// writes.
472func TestALayoutListsEveryDirectoryAsGitWritesIt(t *testing.T) {
473 k := newKnot("idea", "Listed")
474 knotFile := Entry{Path: k.Path(), Mode: "100644", OID: oid("knot")}
475 commentDir := Entry{Path: CommentsDirectory + "/" + k.ID, Mode: "40000"}
476 comment := Entry{Path: commentDir.Path + "/20261015T000000Z-0123456789abcdef.md", Mode: "100644", OID: oid("comment")}
477 ideas, comments := Entry{Path: "ideas", Mode: "40000"}, Entry{Path: CommentsDirectory, Mode: "40000"}
478 for _, x := range []struct {
479 what string
480 es []Entry
481 rule Rule
482 }{
483 {"every directory listed", []Entry{ideas, knotFile, comments, commentDir, comment}, ""},
484 {"a knot without its directory", []Entry{knotFile}, RuleLayout},
485 {"a comment without its knot's directory", []Entry{ideas, knotFile, comments, comment}, RuleLayout},
486 {"a comment without comments/", []Entry{ideas, knotFile, commentDir, comment}, RuleLayout},
487 {"a directory in the mode 040000", []Entry{{Path: "ideas", Mode: "040000"}, knotFile}, RuleLayout},
488 } {
489 if _, err := Layout(x.es); ruleOf(err) != x.rule {
490 t.Errorf("%s: %v, want rule %q", x.what, err, x.rule)
491 }
492 }
493}
494
495// Each limit, at its edge and one past it.
496func TestTheLimitsHoldAtTheirEdges(t *testing.T) {
497 sized := func(n int) *Knot {
498 k := newKnot("idea", "Sized")
499 k.Body = "x\n"
500 k.Body = strings.Repeat("x", n-len(Render(k))+1) + "\n"
501 return k
502 }
503 for _, x := range []struct {
504 what string
505 k *Knot
506 rule Rule
507 }{
508 {"a knot of the most bytes", sized(MaxKnotSize), ""},
509 {"a knot one byte larger", sized(MaxKnotSize + 1), RuleLimit},
510 {"a title of the most bytes", func() *Knot { k := newKnot("idea", "T"); k.Title = strings.Repeat("t", MaxTitle); return k }(), ""},
511 {"a title one byte longer", func() *Knot { k := newKnot("idea", "T"); k.Title = strings.Repeat("t", MaxTitle+1); return k }(), RuleLimit},
512 {"a name of the most bytes", func() *Knot { k := newKnot("idea", "T"); k.Owner = strings.Repeat("o", MaxName); return k }(), ""},
513 {"a name one byte longer", func() *Knot { k := newKnot("idea", "T"); k.Owner = strings.Repeat("o", MaxName+1); return k }(), RuleLimit},
514 {"a list of the most entries", func() *Knot { k := newKnot("bug", "T"); k.BlockedBy = refs(MaxListItems); return k }(), ""},
515 {"a list one entry longer", func() *Knot { k := newKnot("bug", "T"); k.BlockedBy = refs(MaxListItems + 1); return k }(), RuleLimit},
516 } {
517 if len(Render(x.k)) > MaxKnotSize+1 {
518 t.Fatalf("%s: the knot is %d bytes", x.what, len(Render(x.k)))
519 }
520 _, err := ParseKnot(x.k.Path(), x.k.Slug, Render(x.k))
521 if ruleOf(err) != x.rule {
522 t.Errorf("%s: %v, want rule %q", x.what, err, x.rule)
523 }
524 }
525 if n := len(Render(sized(MaxKnotSize))); n != MaxKnotSize {
526 t.Fatalf("the largest knot is %d bytes", n)
527 }
528
529 c := &Comment{Author: "operator", Body: "x\n"}
530 c.Body = strings.Repeat("x", MaxCommentSize-len(RenderComment(c))+1) + "\n"
531 if _, err := ParseComment("c", RenderComment(c)); err != nil || len(RenderComment(c)) != MaxCommentSize {
532 t.Errorf("a comment of the most bytes: %v", err)
533 }
534 c.Body = "x" + c.Body
535 if _, err := ParseComment("c", RenderComment(c)); ruleOf(err) != RuleLimit {
536 t.Errorf("a comment one byte larger: %v", err)
537 }
538
539 // The counts are read from the listing alone.
540 listing := func(knots, comments int) []Entry {
541 es := []Entry{{Path: "ideas", Mode: "40000"}, {Path: "comments", Mode: "40000"}}
542 var first string
543 for i := range knots {
544 slug := fmt.Sprintf("k%d", i)
545 id := DeriveID(Types[2], slug)
546 first = id
547 es = append(es, Entry{Path: "ideas/" + id + "-" + slug + ".md", Mode: "100644", OID: id})
548 }
549 es = append(es, Entry{Path: "comments/" + first, Mode: "40000"})
550 for i := range comments {
551 es = append(es, Entry{Path: fmt.Sprintf("comments/%s/20261015T000000Z-%016x.md", first, i), Mode: "100644", OID: "c"})
552 }
553 return es
554 }
555 for _, x := range []struct {
556 knots, comments int
557 rule Rule
558 }{{MaxKnots, MaxComments, ""}, {MaxKnots + 1, 1, RuleLimit}, {1, MaxComments + 1, RuleLimit}} {
559 if _, err := Layout(listing(x.knots, x.comments)); ruleOf(err) != x.rule {
560 t.Errorf("%d knots and %d comments: %v, want rule %q", x.knots, x.comments, err, x.rule)
561 }
562 }
563
564 // A slug of the most bytes, and one byte longer.
565 for _, x := range []struct {
566 n int
567 rule Rule
568 }{{MaxSlug, ""}, {MaxSlug + 1, RuleLimit}} {
569 slug := strings.Repeat("s", x.n)
570 id := DeriveID(Types[2], slug)
571 _, err := Layout([]Entry{{Path: "ideas", Mode: "40000"}, {Path: "ideas/" + id + "-" + slug + ".md", Mode: "100644"}})
572 if r := ruleOf(err); (x.rule == "") != (r == "") {
573 t.Errorf("a slug of %d bytes: %v", x.n, err)
574 }
575 }
576
577 // The paths one push may add or change.
578 before := tree{}.with(newKnot("outcome", "Base"))
579 grow := func(n int) tree {
580 after := tree{}.with(newKnot("outcome", "Base"))
581 for i := range n {
582 after = after.with(newKnot("idea", fmt.Sprintf("Idea %d", i)))
583 }
584 return after
585 }
586 if err := push(before, grow(MaxChangedPaths), "operator"); err != nil {
587 t.Errorf("a push of %d files: %v", MaxChangedPaths, err)
588 }
589 if err := push(before, grow(MaxChangedPaths+1), "operator"); ruleOf(err) != RuleLimit {
590 t.Errorf("a push of %d files: %v", MaxChangedPaths+1, err)
591 }
592}
593
594func refs(n int) []string {
595 var list []string
596 for i := range n {
597 list = append(list, fmt.Sprintf("app:oc-%07x", i))
598 }
599 return list
600}
601
602func TestANewIDTakesASuffixOnACollision(t *testing.T) {
603 ty, _ := TypeNamed("outcome")
604 taken := map[string]bool{}
605 var slugs []string
606 for range 3 {
607 id, slug := NewID(ty, "Ship it", func(id string) bool { return taken[id] })
608 taken[id] = true
609 slugs = append(slugs, slug)
610 if id != DeriveID(ty, slug) {
611 t.Errorf("%s is not derived from %s", id, slug)
612 }
613 }
614 if strings.Join(slugs, " ") != "ship-it ship-it-2 ship-it-3" {
615 t.Errorf("slugs = %v", slugs)
616 }
617 long := strings.Repeat("word ", 20)
618 _, slug := NewID(ty, long, func(id string) bool { return id == DeriveID(ty, Slug(long)) })
619 if len(slug) > MaxSlug || !strings.HasSuffix(slug, "-2") || !slugShape.MatchString(slug) {
620 t.Errorf("a long title's suffixed slug is %q", slug)
621 }
622 if s := Slug("¿Qué? — 日本"); s != "qu" {
623 t.Errorf("Slug = %q", s)
624 }
625 if s := Slug("日本"); s != "knot" {
626 t.Errorf("Slug of a title with no ASCII letter = %q", s)
627 }
628}
629
630func TestACommitNamesItsOperationOnce(t *testing.T) {
631 tree := strings.Repeat("a", 40)
632 head := "tree " + tree + "\nparent " + strings.Repeat("b", 40) + "\nauthor p <p> 1 +0000\ncommitter operator <p@x> 1 +0000\n\n"
633 c, err := ParseCommit([]byte(head+Message("knot new oc-1234567: x", "0123456789abcdef")), 20)
634 if err != nil || c.Op != "0123456789abcdef" || c.Committer != "operator" || len(c.Parents) != 1 || !c.Time.Equal(time.Unix(1, 0)) {
635 t.Fatalf("ParseCommit = %+v, %v", c, err)
636 }
637 zoned := strings.Replace(head, "committer operator <p@x> 1 +0000", "committer operator <p@x> 1761397200 -0700", 1)
638 if c, err := ParseCommit([]byte(zoned+Message("x", "0123456789abcdef")), 20); err != nil || c.Time != time.Date(2025, 10, 25, 13, 0, 0, 0, time.UTC) {
639 t.Errorf("a commit's time in another zone reads as %v, %v", c.Time, err)
640 }
641 for _, line := range []string{"committer operator <p@x>", "committer operator <p@x> soon +0000", "committer operator <p@x> 1 UTC"} {
642 if _, err := ParseCommit([]byte(strings.Replace(head, "committer operator <p@x> 1 +0000", line, 1)+Message("x", "0123456789abcdef")), 20); err == nil {
643 t.Errorf("a committer line %q was read", line)
644 }
645 }
646 for _, bad := range []string{
647 "knot new\n",
648 "knot new\n\nValley-Op: 0123\n",
649 "knot new\n\nValley-Op: 0123456789abcdef\nmore\n",
650 "Valley-Op: fedcba9876543210\n\nValley-Op: 0123456789abcdef\n",
651 } {
652 if _, err := ParseCommit([]byte(head+bad), 20); err == nil {
653 t.Errorf("a message %q was read", bad)
654 }
655 }
656 if _, err := ParseCommit([]byte("tree "+tree+"\ncommitter a <a> 1 +0000\nparent "+strings.Repeat("b", 40)+"\n\n"+Message("x", "0123456789abcdef")), 20); err == nil {
657 t.Error("a parent after the other headers was read")
658 }
659}