файл пакета→ .shtukbase/packages/layers/checks/s04_placement.ts
checks/s04_placement.ts
158 строк, 7.8 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // S4. One kind, one place. The placement map: `placement:` in the head of /ontology/placement.md, rows
- // `{itemType, path, writer, reader[, records]}`. `path` is where the collection of the kind lies; `records` (a string or a list) is
- // where its records lie, if not in `path`: for example, contours are gathered by the collection /base/contours, but they themselves live
- // in layers — `records: /*/contours` (`*` is one segment of an address). Without `records` the records lie in `path`.
- //
- // Holes (field, kind):
- // - the map names a kind twice (itemType, dup-map);
- // - a kind is declared in two collections: a hole on each extra one (itemType, dup-collection);
- // - the collection of a kind lies not where the map says (itemType, wrong-collection-place);
- // - the collection of a kind is not in the map (itemType, not-in-map);
- // - a record of a kind from the map lies outside the folder of its place (type, wrong-place).
- //
- // Records are searched in the whole project (except deleted/, lab/, runs/, assets/, node_modules/, hidden folders and folders
- // 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
- // lie in /norms/<kind>/<package>/). Pages of `type: Collection` are checked as collections; `itemType: Page`
- // (a collection of ordinary pages, for example templates) is not a kind of records, we do not count it.
- // With --files only the passed files are checked (and the map, if it is among them).
- import { existsSync, readFileSync, statSync } from 'node:fs';
- import { join } from 'node:path';
- // The schema library is the collections package's (layers -> frame -> collections): installed side by side in
- // .shtukbase/packages/, and side by side in apps/standard/packages/ of the standard.
- import { ctx, hole, onlyPaths, values } from '../../collections/checks/lib/schemalib.ts';
- import { type Project, type Result, addr, parseYaml, pystr, readText, splitFrontMatter, truthy } from '../../collections/checks/lib/speclib.ts';
- import { main } from '../../collections/checks/lib/runner.ts';
- export const RULE = {
- id: 's04',
- title: 'Schema: one kind of records, one place (the placement map)',
- scope: 'the map /ontology/placement.md, the pages of collections and all records of the kinds from the map',
- };
- const MAP = '/base/ontology/placement.md';
- const LEGACY_MAP = '/ontology/placement.md'; // before the service pages moved to base/
- const TYPE_RE = /^type:\s*["']?([A-Za-z][A-Za-z0-9]*)["']?\s*$/m;
- const ITEM_RE = /^itemType:\s*["']?([A-Za-z][A-Za-z0-9]*)["']?\s*$/m;
- const stripSlash = (s: string): string => s.replace(/^\/+|\/+$/g, '');
- const isFile = (p: string): boolean => existsSync(p) && statSync(p).isFile();
- /** The head of a file (the text between the first `---`) or "". */
- function head(root: string, f: string): string {
- const text = readFileSync(join(root, f.slice(1)), 'utf8').slice(0, 4096);
- if (!text.startsWith('---')) return '';
- const end = text.indexOf('\n---', 3);
- return text.slice(0, end > 0 ? end : undefined);
- }
- /** Where the map lies: /base/ontology/placement.md, in a project that is not updated — /ontology/placement.md. */
- function mapRel(root: string): string {
- if (!isFile(join(root, MAP.slice(1))) && isFile(join(root, LEGACY_MAP.slice(1)))) return LEGACY_MAP;
- return MAP;
- }
- type Row = [itemType: string, path: string, records: string[]];
- /** ([(itemType, path, records)], [folders outside the map]) or null if there is no map / it has no placement list. */
- function loadMap(root: string): { rows: Row[]; skip: string[] } | null {
- const full = join(root, mapRel(root).slice(1));
- if (!isFile(full)) return null;
- const hd = parseYaml(splitFrontMatter(readText(full))[0]);
- const rows = hd.placement;
- if (!Array.isArray(rows)) return null;
- const out: Row[] = [];
- for (const r of rows) {
- if (r && typeof r === 'object' && !Array.isArray(r) && truthy(r.itemType) && truthy(r.path)) {
- const path = '/' + stripSlash(pystr(r.path).trim());
- let recs = values(truthy(r.records) ? r.records : []).map((x) => '/' + stripSlash(pystr(x).trim()));
- if (!recs.length) recs = [path];
- out.push([pystr(r.itemType).trim(), path, recs]);
- }
- }
- const skip = values(truthy(hd.unmapped) ? hd.unmapped : []).map((x) => '/' + stripSlash(pystr(x).trim()));
- return { rows: out, skip };
- }
- /** path is the folder or its subfolder; `*` in folder is exactly one segment of an address. */
- function inside(path: string, folder: string): boolean {
- const want = stripSlash(folder).split('/');
- const got = stripSlash(path).split('/');
- if (folder === '/') return true;
- if (got.length < want.length) return false;
- return want.every((w, i) => w === '*' || w === got[i]);
- }
- export function check(p: Project, res: Result): void {
- const c = ctx(p);
- const theMap = mapRel(c.root);
- const got = loadMap(c.root);
- if (got === null) {
- res.part('placement map', `no ${theMap} with a placement list`);
- return;
- }
- res.part('placement map', null);
- const { rows, skip } = got;
- const only = onlyPaths();
- const want = (f: string): boolean => {
- if (skip.some((d) => inside(f, d))) return false;
- return only === null || only.has(f.slice(1));
- };
- const mapaddr = addr(theMap);
- const place = new Map<string, string>();
- const homes = new Map<string, string[]>();
- for (const [it, path, recs] of rows) {
- if (place.has(it)) {
- if (want(theMap))
- 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');
- continue;
- }
- place.set(it, path);
- homes.set(it, recs);
- }
- // Collections: all pages of `type: Collection` (their list is needed whole to see duplicates).
- const colls = new Map<string, string[]>();
- for (const coll of c.collections()) {
- const m = ITEM_RE.exec(head(c.root, coll + '.md'));
- if (m && m[1] !== 'Collection' && m[1] !== 'Page') {
- if (!colls.has(m[1])) colls.set(m[1], []);
- colls.get(m[1])!.push(coll);
- }
- }
- const scope: string[] = [];
- for (const [it, paths] of [...colls.entries()].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))) {
- const keep = place.get(it);
- const first = keep !== undefined && paths.includes(keep) ? keep : paths[0];
- for (const coll of paths) {
- if (!want(coll + '.md')) continue;
- scope.push(addr(coll + '.md'));
- const a = addr(coll + '.md');
- if (coll !== first)
- 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)');
- else if (keep === undefined)
- 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');
- else if (coll !== keep)
- 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');
- }
- }
- // Records of the kinds from the map: the folder of a record is the place of the kind.
- for (const f of [...c.files()].sort()) {
- if (!want(f) || f === theMap) continue;
- const m = TYPE_RE.exec(head(c.root, f));
- if (!m || !place.has(m[1])) continue;
- scope.push(addr(f));
- const folder = f.slice(0, f.lastIndexOf('/')) || '/';
- const recs = homes.get(m[1])!;
- if (!recs.some((h) => inside(folder, h))) {
- const where = recs.join(', ');
- 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)`);
- }
- }
- res.scope = scope;
- res.scopeText = `placement: ${place.size} kinds in the map, ${scope.length} collections and records`;
- }
- if (import.meta.main) main({ RULE, check });