gunk-dev/the-valley

graph.go

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