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

lib/write.ts

76 行, 3.7 KB.

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

  1. // Writing factory records: a new page with a head, or new values for some keys of an existing head. Keys the writer
  2. // does not own are carried through unchanged (a block value too). Used by the actions of the packages runs and alarms.
  3. import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
  4. import { join } from 'node:path';
  5. export type Fields = Record<string, unknown>;
  6. /** One value in flow YAML: strings in double quotes, lists in brackets, maps in braces. */
  7. export function yaml(v: unknown): string {
  8. if (v === null || v === undefined) return 'null';
  9. if (typeof v === 'number' || typeof v === 'boolean') return String(v);
  10. if (Array.isArray(v)) return '[' + v.map(yaml).join(', ') + ']';
  11. if (typeof v === 'object') return '{' + Object.entries(v as object).map(([k, x]) => `${k}: ${yaml(x)}`).join(', ') + '}';
  12. return JSON.stringify(String(v));
  13. }
  14. /** A file name from a title: letters and digits in lower case, the rest as one dash. */
  15. export function slug(title: string): string {
  16. const s = title.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-+|-+$/g, '').slice(0, 60).replace(/-+$/, '');
  17. return s || 'record';
  18. }
  19. /** Now as an ISO instant without milliseconds. */
  20. export function now(): string {
  21. return new Date().toISOString().replace(/\.\d+Z$/, 'Z');
  22. }
  23. /** Writes `<folder>/<name>.md` (a free name: `-2`, `-3` … if taken) and returns its project path `/folder/name.md`. */
  24. export function create(root: string, folder: string, name: string, fields: Fields, body: string): string {
  25. const dir = join(root, folder.replace(/^\/+/, ''));
  26. mkdirSync(dir, { recursive: true });
  27. let file = name;
  28. for (let n = 2; existsSync(join(dir, file + '.md')); n++) file = `${name}-${n}`;
  29. const head = Object.entries(fields).filter(([, v]) => v !== undefined).map(([k, v]) => `${k}: ${yaml(v)}`);
  30. writeFileSync(join(dir, file + '.md'), `---\n${head.join('\n')}\n---\n\n${body.trim()}\n`);
  31. return `/${folder.replace(/^\/+|\/+$/g, '')}/${file}.md`;
  32. }
  33. /** Sets keys in the head of an existing page: a key's old line (and its indented lines) goes, the new line is added
  34. * at the end of the head. `undefined` leaves a key alone; `null` removes it. Text, when given, is added to the body. */
  35. export function update(path: string, fields: Fields, addBody?: string): void {
  36. const text = readFileSync(path, 'utf8');
  37. const m = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(text);
  38. if (!m) throw new Error(`${path}: no head`);
  39. const keys = Object.keys(fields).filter((k) => fields[k] !== undefined);
  40. const out: string[] = [];
  41. let skipping = false;
  42. for (const line of m[1].split('\n')) {
  43. const key = /^([^\s#:][^:]*):/.exec(line)?.[1]?.trim();
  44. if (key !== undefined) skipping = keys.includes(key);
  45. else if (!/^\s/.test(line)) skipping = false;
  46. if (!skipping) out.push(line);
  47. }
  48. for (const k of keys) if (fields[k] !== null) out.push(`${k}: ${yaml(fields[k])}`);
  49. let body = m[2];
  50. if (addBody?.trim()) body = body.replace(/\s*$/, '') + `\n\n${addBody.trim()}\n`;
  51. writeFileSync(path, `---\n${out.join('\n')}\n---\n${body.startsWith('\n') ? '' : '\n'}${body}`);
  52. }
  53. /** `--key value` pairs; a key given twice becomes a list; `--flag` with no value is true. Words without a key are
  54. * returned in `_`. */
  55. export function args(argv: string[]): Record<string, any> & { _: string[] } {
  56. const out: Record<string, any> & { _: string[] } = { _: [] };
  57. for (let i = 0; i < argv.length; i++) {
  58. const a = argv[i];
  59. if (!a.startsWith('--')) {
  60. out._.push(a);
  61. continue;
  62. }
  63. const key = a.slice(2);
  64. const val = i + 1 < argv.length && !argv[i + 1].startsWith('--') ? argv[++i] : true;
  65. if (key in out) out[key] = [...(Array.isArray(out[key]) ? out[key] : [out[key]]), val];
  66. else out[key] = val;
  67. }
  68. return out;
  69. }