ShtukbaseStandard
файл пакета→ .shtukbase/packages/layers/checks/s04_placement.ts

checks/s04_placement.ts

158 строк, 7.8 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // S4. One kind, one place. The placement map: `placement:` in the head of /ontology/placement.md, rows
  2. // `{itemType, path, writer, reader[, records]}`. `path` is where the collection of the kind lies; `records` (a string or a list) is
  3. // where its records lie, if not in `path`: for example, contours are gathered by the collection /base/contours, but they themselves live
  4. // in layers — `records: /*/contours` (`*` is one segment of an address). Without `records` the records lie in `path`.
  5. //
  6. // Holes (field, kind):
  7. // - the map names a kind twice (itemType, dup-map);
  8. // - a kind is declared in two collections: a hole on each extra one (itemType, dup-collection);
  9. // - the collection of a kind lies not where the map says (itemType, wrong-collection-place);
  10. // - the collection of a kind is not in the map (itemType, not-in-map);
  11. // - a record of a kind from the map lies outside the folder of its place (type, wrong-place).
  12. //
  13. // Records are searched in the whole project (except deleted/, lab/, runs/, assets/, node_modules/, hidden folders and folders
  14. // from `unmapped:` of the map): every `.md` with a `type:` from the map has a folder that is the `path` of its kind or its subfolder (the norm packages
  15. // lie in /norms/<kind>/<package>/). Pages of `type: Collection` are checked as collections; `itemType: Page`
  16. // (a collection of ordinary pages, for example templates) is not a kind of records, we do not count it.
  17. // With --files only the passed files are checked (and the map, if it is among them).
  18. import { existsSync, readFileSync, statSync } from 'node:fs';
  19. import { join } from 'node:path';
  20. // The schema library is the collections package's (layers -> frame -> collections): installed side by side in
  21. // .shtukbase/packages/, and side by side in apps/standard/packages/ of the standard.
  22. import { ctx, hole, onlyPaths, values } from '../../collections/checks/lib/schemalib.ts';
  23. import { type Project, type Result, addr, parseYaml, pystr, readText, splitFrontMatter, truthy } from '../../collections/checks/lib/speclib.ts';
  24. import { main } from '../../collections/checks/lib/runner.ts';
  25. export const RULE = {
  26. id: 's04',
  27. title: 'Schema: one kind of records, one place (the placement map)',
  28. scope: 'the map /ontology/placement.md, the pages of collections and all records of the kinds from the map',
  29. };
  30. const MAP = '/base/ontology/placement.md';
  31. const LEGACY_MAP = '/ontology/placement.md'; // before the service pages moved to base/
  32. const TYPE_RE = /^type:\s*["']?([A-Za-z][A-Za-z0-9]*)["']?\s*$/m;
  33. const ITEM_RE = /^itemType:\s*["']?([A-Za-z][A-Za-z0-9]*)["']?\s*$/m;
  34. const stripSlash = (s: string): string => s.replace(/^\/+|\/+$/g, '');
  35. const isFile = (p: string): boolean => existsSync(p) && statSync(p).isFile();
  36. /** The head of a file (the text between the first `---`) or "". */
  37. function head(root: string, f: string): string {
  38. const text = readFileSync(join(root, f.slice(1)), 'utf8').slice(0, 4096);
  39. if (!text.startsWith('---')) return '';
  40. const end = text.indexOf('\n---', 3);
  41. return text.slice(0, end > 0 ? end : undefined);
  42. }
  43. /** Where the map lies: /base/ontology/placement.md, in a project that is not updated — /ontology/placement.md. */
  44. function mapRel(root: string): string {
  45. if (!isFile(join(root, MAP.slice(1))) && isFile(join(root, LEGACY_MAP.slice(1)))) return LEGACY_MAP;
  46. return MAP;
  47. }
  48. type Row = [itemType: string, path: string, records: string[]];
  49. /** ([(itemType, path, records)], [folders outside the map]) or null if there is no map / it has no placement list. */
  50. function loadMap(root: string): { rows: Row[]; skip: string[] } | null {
  51. const full = join(root, mapRel(root).slice(1));
  52. if (!isFile(full)) return null;
  53. const hd = parseYaml(splitFrontMatter(readText(full))[0]);
  54. const rows = hd.placement;
  55. if (!Array.isArray(rows)) return null;
  56. const out: Row[] = [];
  57. for (const r of rows) {
  58. if (r && typeof r === 'object' && !Array.isArray(r) && truthy(r.itemType) && truthy(r.path)) {
  59. const path = '/' + stripSlash(pystr(r.path).trim());
  60. let recs = values(truthy(r.records) ? r.records : []).map((x) => '/' + stripSlash(pystr(x).trim()));
  61. if (!recs.length) recs = [path];
  62. out.push([pystr(r.itemType).trim(), path, recs]);
  63. }
  64. }
  65. const skip = values(truthy(hd.unmapped) ? hd.unmapped : []).map((x) => '/' + stripSlash(pystr(x).trim()));
  66. return { rows: out, skip };
  67. }
  68. /** path is the folder or its subfolder; `*` in folder is exactly one segment of an address. */
  69. function inside(path: string, folder: string): boolean {
  70. const want = stripSlash(folder).split('/');
  71. const got = stripSlash(path).split('/');
  72. if (folder === '/') return true;
  73. if (got.length < want.length) return false;
  74. return want.every((w, i) => w === '*' || w === got[i]);
  75. }
  76. export function check(p: Project, res: Result): void {
  77. const c = ctx(p);
  78. const theMap = mapRel(c.root);
  79. const got = loadMap(c.root);
  80. if (got === null) {
  81. res.part('placement map', `no ${theMap} with a placement list`);
  82. return;
  83. }
  84. res.part('placement map', null);
  85. const { rows, skip } = got;
  86. const only = onlyPaths();
  87. const want = (f: string): boolean => {
  88. if (skip.some((d) => inside(f, d))) return false;
  89. return only === null || only.has(f.slice(1));
  90. };
  91. const mapaddr = addr(theMap);
  92. const place = new Map<string, string>();
  93. const homes = new Map<string, string[]>();
  94. for (const [it, path, recs] of rows) {
  95. if (place.has(it)) {
  96. if (want(theMap))
  97. hole(res, mapaddr, 'itemType', 'dup-map', `kind ${it} is named in the map twice: ${place.get(it)} and ${path}`, 'keep one row of the kind in the map');
  98. continue;
  99. }
  100. place.set(it, path);
  101. homes.set(it, recs);
  102. }
  103. // Collections: all pages of `type: Collection` (their list is needed whole to see duplicates).
  104. const colls = new Map<string, string[]>();
  105. for (const coll of c.collections()) {
  106. const m = ITEM_RE.exec(head(c.root, coll + '.md'));
  107. if (m && m[1] !== 'Collection' && m[1] !== 'Page') {
  108. if (!colls.has(m[1])) colls.set(m[1], []);
  109. colls.get(m[1])!.push(coll);
  110. }
  111. }
  112. const scope: string[] = [];
  113. for (const [it, paths] of [...colls.entries()].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))) {
  114. const keep = place.get(it);
  115. const first = keep !== undefined && paths.includes(keep) ? keep : paths[0];
  116. for (const coll of paths) {
  117. if (!want(coll + '.md')) continue;
  118. scope.push(addr(coll + '.md'));
  119. const a = addr(coll + '.md');
  120. if (coll !== first)
  121. hole(res, a, 'itemType', 'dup-collection', `kind ${it} is already declared in the collection ${first}`, 'remove the second collection of the kind or rename the kind (and fix the map)');
  122. else if (keep === undefined)
  123. hole(res, a, 'itemType', 'not-in-map', `kind ${it} is not in the map ${MAP}`, 'add a row of the kind to the map or remove the collection');
  124. else if (coll !== keep)
  125. hole(res, a, 'itemType', 'wrong-collection-place', `the collection of kind ${it} lies in ${coll}, by the map — ${keep}`, 'move the collection to the place from the map or fix the map');
  126. }
  127. }
  128. // Records of the kinds from the map: the folder of a record is the place of the kind.
  129. for (const f of [...c.files()].sort()) {
  130. if (!want(f) || f === theMap) continue;
  131. const m = TYPE_RE.exec(head(c.root, f));
  132. if (!m || !place.has(m[1])) continue;
  133. scope.push(addr(f));
  134. const folder = f.slice(0, f.lastIndexOf('/')) || '/';
  135. const recs = homes.get(m[1])!;
  136. if (!recs.some((h) => inside(folder, h))) {
  137. const where = recs.join(', ');
  138. hole(res, addr(f), 'type', 'wrong-place', `a record of kind ${m[1]} lies in ${folder}, its place by the map is ${where}`, `move the record to ${where} (or fix type)`);
  139. }
  140. }
  141. res.scope = scope;
  142. res.scopeText = `placement: ${place.size} kinds in the map, ${scope.length} collections and records`;
  143. }
  144. if (import.meta.main) main({ RULE, check });