ShtukbaseStandard
包文件→ .shtukbase/packages/shtukbase-style/actions/adopt.ts

actions/adopt.ts

38 行, 1.7 KB.

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

  1. // shtukbase-style `adopt`: makes this style the project's choice when the project has none yet: sets `style:` in the
  2. // header of /design/design.md when it is empty. Runs by itself after install and update; by hand:
  3. // `shtuk run shtukbase-style adopt`. A page that already names a style (this or another) is left alone.
  4. import { existsSync, readFileSync, writeFileSync } from 'node:fs';
  5. import { join } from 'node:path';
  6. import { ID } from '../lib/stylelib.ts';
  7. export const PAGE = 'design/design.md';
  8. /** The page text with `style: <id>` in its header when no style is set; `null` when nothing has to change. */
  9. export function adopt(text: string, id = ID): string | null {
  10. if (!text.startsWith('---\n')) return `---\nstyle: ${id}\n---\n${text}`;
  11. const end = text.indexOf('\n---', 3);
  12. if (end === -1) return null;
  13. const head = text.slice(4, end).split('\n');
  14. const i = head.findIndex((l) => /^style\s*:/.test(l));
  15. if (i === -1) head.push(`style: ${id}`);
  16. else {
  17. const v = head[i].replace(/^style\s*:/, '').replace(/\s+#.*$/, '').trim().replace(/^["']|["']$/g, '');
  18. if (v && v !== 'null' && v !== '~') return null;
  19. head[i] = `style: ${id}`;
  20. }
  21. return `---\n${head.join('\n')}${text.slice(end)}`;
  22. }
  23. if (import.meta.main) {
  24. const p = join(process.cwd(), PAGE);
  25. 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`);
  26. else {
  27. const text = readFileSync(p, 'utf8');
  28. const next = adopt(text);
  29. if (next === null) console.log(`shtukbase-style: ${PAGE} already names a style; left as it is`);
  30. else {
  31. writeFileSync(p, next);
  32. console.log(`shtukbase-style: ${PAGE} now has style: ${ID}`);
  33. }
  34. }
  35. }