файл пакета→ .shtukbase/packages/ontology/actions/lib/lenscommon.ts
actions/lib/lenscommon.ts
104 строки, 4.0 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // Shared helpers of the two generators: reading pages, templates, writing the lens, small Python-like helpers.
- // Bun only, no dependencies; YAML is read with Bun.YAML.
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
- import { dirname, join } from 'node:path';
- import * as lenshead from './lenshead.ts';
- export const HERE = import.meta.dir;
- // ---------------------------------------------------------------- small helpers
- /** Order by code point (as Python sorts strings): the same as the order of the UTF-8 bytes. */
- export const cmp = (a: string, b: string): number => Buffer.compare(Buffer.from(a), Buffer.from(b));
- /** Python truthiness: null, false, 0, '' and empty lists and maps are false. */
- export function truthy(v: unknown): boolean {
- if (v === null || v === undefined || v === false || v === 0 || v === '') return false;
- if (Array.isArray(v)) return v.length > 0;
- if (typeof v === 'object') return Object.keys(v as object).length > 0;
- return true;
- }
- /** `a or b or c` of Python: the first true value, else the last. */
- export function or(...vals: unknown[]): any {
- return vals.find(truthy) ?? vals[vals.length - 1];
- }
- /** `str(v)` of Python for the values a YAML header holds. */
- export function str(v: unknown): string {
- if (v === null || v === undefined) return 'None';
- if (v === true) return 'True';
- if (v === false) return 'False';
- return String(v);
- }
- /** html.escape(t, quote=True) */
- export function e(t: unknown): string {
- return str(t).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
- .replaceAll('"', '"').replaceAll("'", ''');
- }
- export const isObject = (v: unknown): v is Record<string, any> => typeof v === 'object' && v !== null && !Array.isArray(v);
- // ---------------------------------------------------------------- reading
- /** A text file; line breaks are read as `\n`, as Python reads text. */
- export function read(path: string): string {
- return readFileSync(path, 'utf8').replace(/\r\n?/g, '\n');
- }
- /** (front matter text or null, body) of a markdown page. */
- export function splitPage(text: string): [string | null, string] {
- if (!text.startsWith('---\n')) return [null, text];
- const end = text.indexOf('\n---\n', 3);
- if (end !== -1) return [text.slice(4, end), text.slice(end + 5)];
- if (text.endsWith('\n---')) return [text.slice(4, -4), ''];
- return [null, text];
- }
- /** (front matter map, body) of a page; `problem` is told when the front matter does not parse (the map is then empty). */
- export function page(path: string, problem?: (err: string) => void): [Record<string, any>, string] {
- const [head, body] = splitPage(read(path));
- let meta: unknown = {};
- if (head) {
- try {
- meta = Bun.YAML.parse(head) ?? {};
- } catch (err) {
- meta = {};
- problem?.((err as Error).message);
- }
- }
- return [isObject(meta) ? meta : {}, body];
- }
- export function template(name: string): string {
- return read(join(HERE, 'templates', `${name}.html`));
- }
- // ---------------------------------------------------------------- writing
- export function write(path: string, text: string): void {
- mkdirSync(dirname(path), { recursive: true });
- writeFileSync(path, text);
- }
- /** Write the lens file: the header (with sourcesHash and outputHash) and the body. */
- export function build(root: string, out: string, meta: Record<string, unknown>, sources: string[], body: string): void {
- write(out, lenshead.make({
- ...meta, sources,
- sourcesHash: lenshead.sourcesHash(root, sources),
- outputHash: lenshead.outputHash(body),
- }, body));
- }
- /** The only option of the actions: `--out <file>` (or `--out=<file>`). Anything else is refused. */
- export function outOption(args: string[]): string | undefined {
- let out: string | undefined;
- for (let i = 0; i < args.length; i++) {
- const a = args[i];
- if (a === '--out' && i + 1 < args.length) out = args[++i];
- else if (a.startsWith('--out=')) out = a.slice(6);
- else throw new Error(`unknown argument ${a}; the only option is --out <file>`);
- }
- return out;
- }