файл пакета→ .shtukbase/packages/agents/lib/write.ts
lib/write.ts
76 строк, 3.7 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // Writing factory records: a new page with a head, or new values for some keys of an existing head. Keys the writer
- // does not own are carried through unchanged (a block value too). Used by the actions of the packages runs and alarms.
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
- import { join } from 'node:path';
- export type Fields = Record<string, unknown>;
- /** One value in flow YAML: strings in double quotes, lists in brackets, maps in braces. */
- export function yaml(v: unknown): string {
- if (v === null || v === undefined) return 'null';
- if (typeof v === 'number' || typeof v === 'boolean') return String(v);
- if (Array.isArray(v)) return '[' + v.map(yaml).join(', ') + ']';
- if (typeof v === 'object') return '{' + Object.entries(v as object).map(([k, x]) => `${k}: ${yaml(x)}`).join(', ') + '}';
- return JSON.stringify(String(v));
- }
- /** A file name from a title: letters and digits in lower case, the rest as one dash. */
- export function slug(title: string): string {
- const s = title.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-+|-+$/g, '').slice(0, 60).replace(/-+$/, '');
- return s || 'record';
- }
- /** Now as an ISO instant without milliseconds. */
- export function now(): string {
- return new Date().toISOString().replace(/\.\d+Z$/, 'Z');
- }
- /** Writes `<folder>/<name>.md` (a free name: `-2`, `-3` … if taken) and returns its project path `/folder/name.md`. */
- export function create(root: string, folder: string, name: string, fields: Fields, body: string): string {
- const dir = join(root, folder.replace(/^\/+/, ''));
- mkdirSync(dir, { recursive: true });
- let file = name;
- for (let n = 2; existsSync(join(dir, file + '.md')); n++) file = `${name}-${n}`;
- const head = Object.entries(fields).filter(([, v]) => v !== undefined).map(([k, v]) => `${k}: ${yaml(v)}`);
- writeFileSync(join(dir, file + '.md'), `---\n${head.join('\n')}\n---\n\n${body.trim()}\n`);
- return `/${folder.replace(/^\/+|\/+$/g, '')}/${file}.md`;
- }
- /** Sets keys in the head of an existing page: a key's old line (and its indented lines) goes, the new line is added
- * at the end of the head. `undefined` leaves a key alone; `null` removes it. Text, when given, is added to the body. */
- export function update(path: string, fields: Fields, addBody?: string): void {
- const text = readFileSync(path, 'utf8');
- const m = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(text);
- if (!m) throw new Error(`${path}: no head`);
- const keys = Object.keys(fields).filter((k) => fields[k] !== undefined);
- const out: string[] = [];
- let skipping = false;
- for (const line of m[1].split('\n')) {
- const key = /^([^\s#:][^:]*):/.exec(line)?.[1]?.trim();
- if (key !== undefined) skipping = keys.includes(key);
- else if (!/^\s/.test(line)) skipping = false;
- if (!skipping) out.push(line);
- }
- for (const k of keys) if (fields[k] !== null) out.push(`${k}: ${yaml(fields[k])}`);
- let body = m[2];
- if (addBody?.trim()) body = body.replace(/\s*$/, '') + `\n\n${addBody.trim()}\n`;
- writeFileSync(path, `---\n${out.join('\n')}\n---\n${body.startsWith('\n') ? '' : '\n'}${body}`);
- }
- /** `--key value` pairs; a key given twice becomes a list; `--flag` with no value is true. Words without a key are
- * returned in `_`. */
- export function args(argv: string[]): Record<string, any> & { _: string[] } {
- const out: Record<string, any> & { _: string[] } = { _: [] };
- for (let i = 0; i < argv.length; i++) {
- const a = argv[i];
- if (!a.startsWith('--')) {
- out._.push(a);
- continue;
- }
- const key = a.slice(2);
- const val = i + 1 < argv.length && !argv[i + 1].startsWith('--') ? argv[++i] : true;
- if (key in out) out[key] = [...(Array.isArray(out[key]) ? out[key] : [out[key]]), val];
- else out[key] = val;
- }
- return out;
- }