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