gunk-dev/the-valley

graph.go

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