ShtukbaseStandard
包文件→ .shtukbase/packages/agents/lib/place.ts

lib/place.ts

44 行, 2.1 KB.

文件按包中的原样显示:代码及其注释不做翻译。

  1. // Adds the kinds of records a factory package brings to the placement map `/base/ontology/placement.md` (package
  2. // layers): a line in the `placement:` head and a row in the table. A kind already in the map is left as it is, so the
  3. // step can run on every install and update. The working directory is the project root.
  4. import { existsSync, readFileSync, writeFileSync } from 'node:fs';
  5. import { join } from 'node:path';
  6. export type Row = { itemType: string; path: string; title: string; pkg: string };
  7. const MAP = 'base/ontology/placement.md';
  8. /** Adds the missing rows; returns the kinds it added. Without the map there is nothing to add to: a line on stderr. */
  9. export function place(rows: Row[], root = process.cwd()): string[] {
  10. const file = join(root, MAP);
  11. if (!existsSync(file)) {
  12. console.error(`no map /${MAP}: kinds ${rows.map((r) => r.itemType).join(', ')} were not added (install the package layers)`);
  13. return [];
  14. }
  15. let text = readFileSync(file, 'utf8');
  16. const added: string[] = [];
  17. for (const r of rows) {
  18. if (new RegExp(`itemType:\\s*"?${r.itemType}"?\\s*[,}]`).test(text)) continue;
  19. const head = ` - {itemType: ${r.itemType}, path: ${r.path}, writer: all, reader: all}`;
  20. const row = `| ${r.title} | \`${r.itemType}\` | \`${r.path}\` | all | all | the collection is brought by the package \`${r.pkg}\` |`;
  21. const lines = text.split('\n');
  22. const end = lines.indexOf('---', 1);
  23. if (end < 0) continue;
  24. let at = -1;
  25. for (let i = 1; i < end; i++) if (/^\s+- \{itemType:/.test(lines[i])) at = i;
  26. if (at < 0) {
  27. const p = lines.findIndex((l, i) => i < end && /^placement:\s*$/.test(l));
  28. if (p < 0) continue;
  29. at = p;
  30. }
  31. lines.splice(at + 1, 0, head);
  32. let last = -1;
  33. for (let i = end + 1; i < lines.length; i++) if (lines[i].startsWith('|')) last = i;
  34. if (last >= 0) lines.splice(last + 1, 0, row);
  35. text = lines.join('\n');
  36. added.push(r.itemType);
  37. }
  38. if (added.length) writeFileSync(file, text);
  39. console.log(added.length ? `placement map: added kinds ${added.join(', ')}` : 'placement map: all kinds are already in place');
  40. return added;
  41. }