gunk-dev/the-valley

graph.go

source8d1b8d9b3656main's published tip history
15.7 KiB
1package knot
2
3import (
4 "fmt"
5 "path"
6 "slices"
7 "sort"
8 "strings"
9 "time"
10)
11
12// Entry is one entry of a graph's tree, as a listing of it gives it: a
13// path from the root, the entry's mode as git writes it, and its object.
14// A listing holds every tree below the root as well as every file.
15type Entry struct {
16 Path string
17 Mode string
18 OID string
19}
20
21// Index is a graph's layout: where each knot and each comment is, read
22// from the tree's listing alone. A knot's ID and type are in its path, so
23// an index resolves an edge without reading any knot.
24type Index struct {
25 // Knots maps each knot's ID to its file.
26 Knots map[string]File
27 // Comments maps each comment's path to its file.
28 Comments map[string]File
29 // Files maps every file's path to its object.
30 Files map[string]string
31 // knotAt maps each knot's path to its ID.
32 knotAt map[string]string
33}
34
35// File is one knot's or comment's file in a graph.
36type File struct {
37 Path string
38 OID string
39 // For a knot: its ID, type and slug. For a comment: the ID of the
40 // knot it is on, its stamp and its operation.
41 ID, Type, Slug string
42 Stamp, Op string
43}
44
45// Layout reads a graph's listing into its index, and refuses any listing
46// that is not exactly a graph's layout: the root holds only the four type
47// directories and comments/; a type directory holds only knots of its
48// type, named <id>-<slug>.md; comments/ holds only a directory per knot,
49// named by the knot's ID, holding only comments named <stamp>-<op>.md.
50// Every directory has the mode 40000, exactly as git writes it, and every
51// file is a plain file, mode 100644: no symlink, executable or submodule.
52// Every directory a path passes through is an entry of the listing in its
53// own right, as it is in any listing of a tree git wrote. No directory is
54// empty, no name repeats, and no ID is used twice. The counts are held to
55// MaxKnots and MaxComments. Whether each directory of comments is on a
56// knot the graph holds is the push's to check, since a knot deleted is the
57// clearer refusal.
58func Layout(entries []Entry) (*Index, error) {
59 idx, err := layout(entries)
60 if err != nil {
61 return nil, err
62 }
63 return idx, nil
64}
65
66func layout(entries []Entry) (*Index, *Error) {
67 idx := &Index{Knots: map[string]File{}, Comments: map[string]File{}, Files: map[string]string{}, knotAt: map[string]string{}}
68 seen := map[string]bool{}
69 children := map[string]int{}
70 isDir := map[string]bool{}
71 var dirs []string
72 for _, e := range entries {
73 if seen[e.Path] {
74 return nil, refuse(RuleLayout, e.Path, "is named twice in its tree")
75 }
76 seen[e.Path] = true
77 dir, base := path.Split(e.Path)
78 dir = strings.TrimSuffix(dir, "/")
79 children[dir]++
80 parts := strings.Split(e.Path, "/")
81 if e.Mode == "40000" {
82 dirs = append(dirs, e.Path)
83 isDir[e.Path] = true
84 if err := layoutDir(parts); err != nil {
85 return nil, err
86 }
87 continue
88 }
89 if e.Mode != "100644" {
90 return nil, refuse(RuleLayout, e.Path, fmt.Sprintf("has mode %s, and a graph holds only directories, mode 40000, and plain files, mode 100644: no symlink, executable or submodule", e.Mode))
91 }
92 f, err := layoutFile(parts, base)
93 if err != nil {
94 return nil, err
95 }
96 f.Path, f.OID = e.Path, e.OID
97 idx.Files[e.Path] = e.OID
98 if f.Stamp == "" {
99 if prior, ok := idx.Knots[f.ID]; ok {
100 return nil, refuse(RuleUniqueID, e.Path, fmt.Sprintf("has the id %s, which %s has already", f.ID, prior.Path))
101 }
102 idx.Knots[f.ID] = f
103 idx.knotAt[e.Path] = f.ID
104 } else {
105 idx.Comments[e.Path] = f
106 }
107 }
108 for _, d := range dirs {
109 if children[d] == 0 {
110 return nil, refuse(RuleLayout, d, "is an empty directory, which git does not write")
111 }
112 }
113 for _, e := range entries {
114 parts := strings.Split(e.Path, "/")
115 for i := 1; i < len(parts); i++ {
116 if d := strings.Join(parts[:i], "/"); !isDir[d] {
117 return nil, refuse(RuleLayout, e.Path, fmt.Sprintf("is listed without the directory %s it is in, and a tree git writes names each directory as an entry of its own", d))
118 }
119 }
120 }
121 switch {
122 case len(idx.Knots) > MaxKnots:
123 return nil, refuse(RuleLimit, "", fmt.Sprintf("the graph would hold %d knots, more than the %d it may", len(idx.Knots), MaxKnots))
124 case len(idx.Comments) > MaxComments:
125 return nil, refuse(RuleLimit, "", fmt.Sprintf("the graph would hold %d comments, more than the %d it may", len(idx.Comments), MaxComments))
126 }
127 return idx, nil
128}
129
130func layoutDir(parts []string) *Error {
131 p := strings.Join(parts, "/")
132 switch len(parts) {
133 case 1:
134 if _, ok := typeOfDirectory(parts[0]); ok || parts[0] == CommentsDirectory {
135 return nil
136 }
137 return refuse(RuleLayout, p, fmt.Sprintf("is no directory a graph holds; the root holds %s", strings.Join(rootNames(), ", ")))
138 case 2:
139 if parts[0] == CommentsDirectory && IsLocalID(parts[1]) {
140 return nil
141 }
142 if parts[0] == CommentsDirectory {
143 return refuse(RuleLayout, p, "is not named by a knot's id, as each directory of comments is")
144 }
145 }
146 return refuse(RuleLayout, p, "is a directory where a graph holds files")
147}
148
149func layoutFile(parts []string, base string) (File, *Error) {
150 p := strings.Join(parts, "/")
151 switch {
152 case len(parts) == 2 && parts[0] != CommentsDirectory:
153 t, ok := typeOfDirectory(parts[0])
154 if !ok {
155 break
156 }
157 m := knotFile.FindStringSubmatch(base)
158 if m == nil {
159 return File{}, refuse(RuleLayout, p, fmt.Sprintf("is not named <id>-<slug>.md, as a knot is, with the id %s- and 7 hex digits and the slug lowercase letters, digits and hyphens", t.Prefix))
160 }
161 id, slug := m[1], m[3]
162 if !slugShape.MatchString(slug) || len(slug) > MaxSlug {
163 return File{}, refuse(RuleLayout, p, fmt.Sprintf("has the slug %q, and a slug is at most %d lowercase letters and digits, in words joined by single hyphens", slug, MaxSlug))
164 }
165 if pt, _ := typeOfPrefix(m[2]); pt.Name != t.Name {
166 return File{}, refuse(RuleDirectory, p, fmt.Sprintf("is a%s %s, and a%s %s belongs in %s/", article(pt.Name), pt.Name, article(pt.Name), pt.Name, pt.Directory))
167 }
168 return File{ID: id, Type: t.Name, Slug: slug}, nil
169 case len(parts) == 3 && parts[0] == CommentsDirectory:
170 m := commentFile.FindStringSubmatch(base)
171 if m == nil {
172 return File{}, refuse(RuleLayout, p, "is not named <stamp>-<op>.md, as a comment is, with the stamp YYYYMMDDTHHMMSSZ and the op 16 hex digits")
173 }
174 if _, err := time.Parse(CommentStamp, m[1]); err != nil {
175 return File{}, refuse(RuleLayout, p, fmt.Sprintf("is stamped %s, which is no time: a comment's stamp is when it was written, YYYYMMDDTHHMMSSZ", m[1]))
176 }
177 return File{ID: parts[1], Stamp: m[1], Op: m[2]}, nil
178 }
179 return File{}, refuse(RuleLayout, p, fmt.Sprintf("is outside the graph's layout: a graph holds %s/<id>-<slug>.md and %s/<id>/<stamp>-<op>.md, and nothing else", strings.Join(typeDirectories(), "|"), CommentsDirectory))
180}
181
182func rootNames() []string { return append(typeDirectories(), CommentsDirectory) }
183
184func typeDirectories() []string {
185 var names []string
186 for _, t := range Types {
187 names = append(names, t.Directory)
188 }
189 return names
190}
191
192// Reader reads a file's content by its object, refusing one larger than
193// max bytes before reading it.
194type Reader func(oid string, max int) ([]byte, error)
195
196// Push is one write of a graph to judge: the graph before it, which is nil
197// for the push that creates the ref, and the graph it would leave.
198type Push struct {
199 Old, New *Index
200 Read Reader
201 // Pusher is the principal pushing. A new knot's created_by and a new
202 // comment's author must name it.
203 Pusher string
204}
205
206// Check holds a push to every rule. The graph before it was valid, so only
207// what changed is read: each knot and comment the push adds or changes,
208// and, for cycles, the knots their edges reach. The rules about the whole
209// graph are checked on every push all the same: the counts from the
210// listing, and cycles by walking the edges from every changed knot.
211func (p Push) Check() error {
212 if err := p.check(true); err != nil {
213 return err
214 }
215 return nil
216}
217
218// Validate holds a whole graph to every rule but the push's: it reads
219// every knot and comment, and needs no pusher.
220func Validate(idx *Index, read Reader) error {
221 if err := (Push{New: idx, Read: read}).check(false); err != nil {
222 return err
223 }
224 return nil
225}
226
227func (p Push) check(push bool) *Error {
228 g := &graph{idx: p.New, read: p.Read, knots: map[string]*Knot{}}
229 var changed []string
230 for path, oid := range p.New.Files {
231 if p.Old == nil || p.Old.Files[path] != oid {
232 changed = append(changed, path)
233 }
234 }
235 sort.Strings(changed)
236 if p.Old != nil {
237 var gone []string
238 for path := range p.Old.Files {
239 if _, ok := p.New.Files[path]; !ok {
240 gone = append(gone, path)
241 }
242 }
243 sort.Strings(gone)
244 for _, path := range gone {
245 what := "a knot is never deleted"
246 if _, ok := p.Old.Comments[path]; ok {
247 what = "a comment is never deleted"
248 }
249 return refuse(RuleTransition, path, "is deleted, and "+what+"; a knot that is done is closed by its status, and the history is the record")
250 }
251 }
252 if push && len(changed) > MaxChangedPaths {
253 return refuse(RuleLimit, "", fmt.Sprintf("the push adds or changes %d files, more than the %d one commit may", len(changed), MaxChangedPaths))
254 }
255 var touched []string
256 for _, path := range changed {
257 if c, ok := p.New.Comments[path]; ok {
258 if err := p.checkComment(g, c); err != nil {
259 return err
260 }
261 continue
262 }
263 f := p.New.Knots[p.New.knotAt[path]]
264 k, err := g.knot(f.ID)
265 if err != nil {
266 return err
267 }
268 if err := g.checkEdges(k); err != nil {
269 return err
270 }
271 if err := p.checkTransition(f, k); err != nil {
272 return err
273 }
274 touched = append(touched, f.ID)
275 }
276 return g.checkCycles(touched)
277}
278
279// checkComment holds a comment the push adds to its rules. A comment is
280// only ever added: one whose path the old graph has already is a change to
281// it, and is refused.
282func (p Push) checkComment(g *graph, c File) *Error {
283 if p.Old != nil {
284 if _, ok := p.Old.Files[c.Path]; ok {
285 return refuse(RuleTransition, c.Path, "changes a comment, and a comment stays exactly as it was written")
286 }
287 }
288 // A comment the push leaves unchanged is on a knot the graph holds,
289 // since no knot is deleted. One it adds must be too.
290 if _, ok := p.New.Knots[c.ID]; !ok {
291 return refuse(RuleEdgeResolves, path.Dir(c.Path), fmt.Sprintf("holds comments on %s, which is no knot in the graph", c.ID))
292 }
293 data, err := g.read(c.OID, MaxCommentSize)
294 if err != nil {
295 return refuse(RuleLimit, c.Path, err.Error())
296 }
297 comment, perr := parseComment(c.Path, data)
298 if perr != nil {
299 return perr
300 }
301 if p.Pusher != "" && comment.Author != p.Pusher {
302 return refuse(RuleProvenance, c.Path, fmt.Sprintf("names %s as its author, and %s is pushing it: a comment's author is the principal that writes it", comment.Author, p.Pusher))
303 }
304 return nil
305}
306
307// checkTransition holds a knot the push adds or changes to what a push
308// may do to one: a new knot names the pusher as its creator, and a changed
309// one keeps its id, type, created date and creator.
310func (p Push) checkTransition(f File, k *Knot) *Error {
311 var before File
312 if p.Old != nil {
313 before = p.Old.Knots[f.ID]
314 }
315 if before.Path == "" {
316 if p.Pusher != "" && k.CreatedBy != p.Pusher {
317 return refuse(RuleProvenance, f.Path, fmt.Sprintf("names %s in created_by, and %s is pushing it: a new knot's creator is the principal that pushes it", k.CreatedBy, p.Pusher))
318 }
319 return nil
320 }
321 if before.Path != f.Path {
322 return refuse(RuleTransition, f.Path, fmt.Sprintf("moves %s from %s, and a knot's file never moves", f.ID, before.Path))
323 }
324 data, err := p.Read(before.OID, MaxKnotSize)
325 if err != nil {
326 return refuse(RuleLimit, before.Path, "as it was: "+err.Error())
327 }
328 old, perr := parseKnot(before.Path, before.Slug, data)
329 if perr != nil {
330 return refuse(perr.Rule, before.Path, "as it was: "+perr.Msg)
331 }
332 for _, field := range []string{"id", "type", "created", "created_by"} {
333 if old.Get(field) != k.Get(field) {
334 return refuse(RuleTransition, f.Path, fmt.Sprintf("changes %s from %q to %q, and a knot's id, type, created and created_by never change", field, old.Get(field), k.Get(field)))
335 }
336 }
337 return nil
338}
339
340// graph reads the knots of one index on demand, each once.
341type graph struct {
342 idx *Index
343 read Reader
344 knots map[string]*Knot
345}
346
347// knot is the knot with id, read and held to every rule about it alone,
348// and to its filename.
349func (g *graph) knot(id string) (*Knot, *Error) {
350 if k, ok := g.knots[id]; ok {
351 return k, nil
352 }
353 f := g.idx.Knots[id]
354 data, err := g.read(f.OID, MaxKnotSize)
355 if err != nil {
356 return nil, refuse(RuleLimit, f.Path, err.Error())
357 }
358 k, perr := parseKnot(f.Path, f.Slug, data)
359 if perr != nil {
360 return nil, perr
361 }
362 switch {
363 case k.ID != f.ID:
364 return nil, refuse(RuleFilename, f.Path, fmt.Sprintf("its filename says id %s, and its frontmatter says %s", f.ID, k.ID))
365 case k.Type != f.Type:
366 t, _ := TypeNamed(k.Type)
367 return nil, refuse(RuleDirectory, f.Path, fmt.Sprintf("is a%s %s, and a%s %s belongs in %s/", article(k.Type), k.Type, article(k.Type), k.Type, t.Directory))
368 }
369 if derived := DeriveID(k.TypeOf(), f.Slug); derived != k.ID {
370 return nil, refuse(RuleIDDerived, f.Path, fmt.Sprintf("its id %s is not derived from its slug %q, which gives %s", k.ID, f.Slug, derived))
371 }
372 g.knots[id] = k
373 return k, nil
374}
375
376// checkEdges holds every local edge of k to naming a knot in the graph,
377// of a type the edge takes. A reference to another project's knot is
378// held to its shape alone, which the knot's own check has done.
379func (g *graph) checkEdges(k *Knot) *Error {
380 resolve := func(field, id string, want ...string) *Error {
381 f, ok := g.idx.Knots[id]
382 switch {
383 case !ok:
384 return refuse(RuleEdgeResolves, k.Path(), fmt.Sprintf("%s names %s, which is no knot in the graph", field, id))
385 case len(want) > 0 && !slices.Contains(want, f.Type):
386 return refuse(RuleParentOutcome, k.Path(), fmt.Sprintf("%s names %s, a %s, and it names a%s %s", field, id, f.Type, article(want[0]), strings.Join(want, " or ")))
387 }
388 return nil
389 }
390 if k.Parent != "" {
391 if err := resolve("parent", k.Parent, "outcome"); err != nil {
392 return err
393 }
394 }
395 if k.GraduatedInto != "" {
396 if err := resolve("graduated_into", k.GraduatedInto, "outcome", "question"); err != nil {
397 return err
398 }
399 }
400 for _, ref := range k.BlockedBy {
401 if IsLocalID(ref) {
402 if err := resolve("blocked_by", ref); err != nil {
403 return err
404 }
405 }
406 }
407 return nil
408}
409
410// checkCycles refuses a cycle in parent edges, or in blocked_by edges,
411// through any knot in from. The graph before the push had none, so every
412// cycle the push could make runs through a knot it changed. Each knot
413// reached is read once.
414//
415// The two edges are checked apart. A milestone may wait on one of its own
416// work items, and that is no cycle: the work item can finish.
417func (g *graph) checkCycles(from []string) *Error {
418 for _, edge := range []string{"parent", "blocked_by"} {
419 const (
420 visiting = 1
421 done = 2
422 )
423 state := map[string]int{}
424 var trail []string
425 var visit func(id string) *Error
426 visit = func(id string) *Error {
427 switch state[id] {
428 case visiting:
429 at := 0
430 for trail[at] != id {
431 at++
432 }
433 loop := append(append([]string(nil), trail[at:]...), id)
434 k := g.knots[id]
435 return refuse(RuleCycle, k.Path(), fmt.Sprintf("its %s edges form a cycle, %s", edge, strings.Join(loop, " → ")))
436 case done:
437 return nil
438 }
439 k, err := g.knot(id)
440 if err != nil {
441 return err
442 }
443 state[id] = visiting
444 trail = append(trail, id)
445 var next []string
446 if edge == "parent" && k.Parent != "" {
447 next = []string{k.Parent}
448 } else if edge == "blocked_by" {
449 for _, ref := range k.BlockedBy {
450 if _, ok := g.idx.Knots[ref]; ok {
451 next = append(next, ref)
452 }
453 }
454 }
455 for _, n := range next {
456 if err := visit(n); err != nil {
457 return err
458 }
459 }
460 trail = trail[:len(trail)-1]
461 state[id] = done
462 return nil
463 }
464 for _, id := range from {
465 if err := visit(id); err != nil {
466 return err
467 }
468 }
469 }
470 return nil
471}