ShtukbaseStandard
package file→ .shtukbase/packages/quality/actions/lib/place.ts

actions/lib/place.ts

39 lines, 2.2 KB.

  1. // Adds the record types a package brings to the placement map /base/ontology/placement.md (package `layers`):
  2. // a `placement:` row in the head and a row in the table. A row whose itemType is already in the map is left alone,
  3. // so running it again changes nothing. Without the map (no `layers`) it does nothing. The working directory is the
  4. // project root.
  5. import { existsSync, readFileSync, writeFileSync } from 'node:fs';
  6. export type Place = { itemType: string; path: string; label: string; pkg: string; records?: string };
  7. const MAP = 'base/ontology/placement.md';
  8. export function place(rows: Place[], root = process.cwd()): string[] {
  9. const file = `${root}/${MAP}`;
  10. if (!existsSync(file)) return [`no /${MAP}: the placement map is installed by the package layers, rows were not added`];
  11. let text = readFileSync(file, 'utf8');
  12. const end = text.indexOf('\n---', 3);
  13. if (!text.startsWith('---') || end < 0) return [`/${MAP}: no head, rows were not added`];
  14. let head = text.slice(0, end), body = text.slice(end);
  15. const done: string[] = [];
  16. for (const r of rows) {
  17. if (new RegExp(`itemType:\\s*["']?${r.itemType}["']?\\s*[,}]`).test(head)) continue;
  18. const line = ` - {itemType: ${r.itemType}, path: ${r.path}${r.records ? `, records: ${r.records}` : ''}, writer: all, reader: all}`;
  19. const lines = head.split('\n');
  20. let at = lines.findIndex((l) => /^placement:\s*$/.test(l));
  21. if (at < 0) { lines.push('placement:'); at = lines.length - 1; }
  22. let last = at;
  23. while (last + 1 < lines.length && /^\s+-\s/.test(lines[last + 1])) last++;
  24. lines.splice(last + 1, 0, line);
  25. head = lines.join('\n');
  26. const tline = `| ${r.label} | \`${r.itemType}\` | \`${r.path}\` | all | all | the collection is brought by the package \`${r.pkg}\` |`;
  27. const bl = body.split('\n');
  28. let lastRow = -1;
  29. for (let i = 0; i < bl.length; i++) if (/^\|.*\|\s*$/.test(bl[i])) lastRow = i;
  30. if (lastRow >= 0) bl.splice(lastRow + 1, 0, tline);
  31. body = bl.join('\n');
  32. done.push(r.itemType);
  33. }
  34. if (done.length) writeFileSync(file, head + body);
  35. return [done.length ? `placement map: added ${done.join(', ')}` : 'placement map: all kinds are already in place'];
  36. }