package file→ .shtukbase/packages/shtukbase-style/actions/adopt.ts
actions/adopt.ts
38 lines, 1.7 KB.
- // shtukbase-style `adopt`: makes this style the project's choice when the project has none yet: sets `style:` in the
- // header of /design/design.md when it is empty. Runs by itself after install and update; by hand:
- // `shtuk run shtukbase-style adopt`. A page that already names a style (this or another) is left alone.
- import { existsSync, readFileSync, writeFileSync } from 'node:fs';
- import { join } from 'node:path';
- import { ID } from '../lib/stylelib.ts';
- export const PAGE = 'design/design.md';
- /** The page text with `style: <id>` in its header when no style is set; `null` when nothing has to change. */
- export function adopt(text: string, id = ID): string | null {
- if (!text.startsWith('---\n')) return `---\nstyle: ${id}\n---\n${text}`;
- const end = text.indexOf('\n---', 3);
- if (end === -1) return null;
- const head = text.slice(4, end).split('\n');
- const i = head.findIndex((l) => /^style\s*:/.test(l));
- if (i === -1) head.push(`style: ${id}`);
- else {
- const v = head[i].replace(/^style\s*:/, '').replace(/\s+#.*$/, '').trim().replace(/^["']|["']$/g, '');
- if (v && v !== 'null' && v !== '~') return null;
- head[i] = `style: ${id}`;
- }
- return `---\n${head.join('\n')}${text.slice(end)}`;
- }
- if (import.meta.main) {
- const p = join(process.cwd(), PAGE);
- if (!existsSync(p)) console.log(`shtukbase-style: ${PAGE} is not there (the design-tokens package lays it); the style is not set — add "style: ${ID}" to the header of that page`);
- else {
- const text = readFileSync(p, 'utf8');
- const next = adopt(text);
- if (next === null) console.log(`shtukbase-style: ${PAGE} already names a style; left as it is`);
- else {
- writeFileSync(p, next);
- console.log(`shtukbase-style: ${PAGE} now has style: ${ID}`);
- }
- }
- }