ShtukbaseStandard
файл пакета→ .shtukbase/packages/design-base/lib/files.ts

lib/files.ts

108 строк, 4.7 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // Which files of the project the design checks look at. The working directory is the project root.
  2. // Settings live on the page /design/design-checks.md (front matter): `scan` (folders or files to look in; default:
  3. // the whole project), `ignore` (globs to skip), `packageFiles` (true: also look at files that packages laid as pages;
  4. // default false — those are the packages' business, and their own norms cover them).
  5. // Folders that are never product code are skipped always: node_modules, .git, .shtukbase, build outputs, caches.
  6. import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
  7. import { join } from 'node:path';
  8. import { readPage } from '../../collections/checks/lib/pages.ts';
  9. export const SETTINGS = 'design/design-checks.md';
  10. export const SKIP_DIRS = new Set([
  11. 'node_modules', '.git', '.shtukbase', 'dist', 'build', 'out', '.next', '.turbo', '.cache', 'coverage',
  12. 'target', '.svelte-kit', '.vercel', '.output', 'storybook-static', '.claude', '.agents',
  13. ]);
  14. /** Test, story and generated files: not the product's screens. */
  15. export const NOT_PRODUCT = /(\.(test|spec|stories|story|d|fixtures?|mocks?)\.[a-z]+$)|(^|\/)(__tests__|__mocks__|fixtures?)\//;
  16. export type Scope = { root: string; scan: string[]; ignore: RegExp[]; packageFiles: boolean };
  17. const list = (v: unknown): string[] =>
  18. Array.isArray(v) ? v.map(String).map((s) => s.trim()).filter(Boolean) : typeof v === 'string' && v.trim() ? [v.trim()] : [];
  19. /** Front matter of a project page (relative path), or {} when there is no such page. */
  20. export function settings(rel: string, root = process.cwd()): Record<string, any> {
  21. const p = join(root, rel);
  22. return existsSync(p) ? readPage(p).fm : {};
  23. }
  24. /** A glob (`*` inside a name, `**` across folders) or a plain path prefix → a regexp on relative paths. */
  25. export function glob(g: string): RegExp {
  26. const s = g.replace(/^\.?\/+/, '').replace(/\/+$/, '');
  27. if (!/[*?]/.test(s)) return new RegExp(`^${s.replace(/[.+^${}()|[\]\\]/g, '\\$&')}(/|$)`);
  28. let re = '';
  29. for (let i = 0; i < s.length; i++) {
  30. const c = s[i];
  31. if (c === '*' && s[i + 1] === '*') { re += '.*'; i++; if (s[i + 1] === '/') i++; }
  32. else if (c === '*') re += '[^/]*';
  33. else if (c === '?') re += '[^/]';
  34. else re += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
  35. }
  36. return new RegExp(`^${re}(/|$)`);
  37. }
  38. export function scope(root = process.cwd()): Scope {
  39. const fm = settings(SETTINGS, root);
  40. return {
  41. root,
  42. scan: list(fm.scan).map((s) => s.replace(/^\/+|\/+$/g, '')),
  43. ignore: list(fm.ignore).map(glob),
  44. packageFiles: fm.packageFiles === true,
  45. };
  46. }
  47. /** Files that packages laid into the project as pages (from .shtukbase/packages.lock). */
  48. export function packageFiles(root = process.cwd()): Set<string> {
  49. const p = join(root, '.shtukbase', 'packages.lock');
  50. const out = new Set<string>();
  51. if (!existsSync(p)) return out;
  52. for (const line of readFileSync(p, 'utf8').split('\n')) {
  53. const m = /^\s{4,}("?)([^"{}]+?)\1:\s*\{base:/.exec(line);
  54. if (m) out.add(m[2]);
  55. }
  56. return out;
  57. }
  58. function walk(root: string, rel: string, out: string[]): void {
  59. const abs = join(root, rel);
  60. if (!existsSync(abs)) return;
  61. if (!statSync(abs).isDirectory()) { out.push(rel); return; }
  62. for (const name of readdirSync(abs).sort()) {
  63. if (SKIP_DIRS.has(name)) continue;
  64. walk(root, rel ? `${rel}/${name}` : name, out);
  65. }
  66. }
  67. /** Project files (relative paths) with one of the extensions, inside the scope. `product`: skip tests and stories. */
  68. export function projectFiles(exts: string[], sc: Scope = scope(), product = true): string[] {
  69. const all: string[] = [];
  70. for (const start of sc.scan.length ? sc.scan : ['']) walk(sc.root, start, all);
  71. const laid = sc.packageFiles ? new Set<string>() : packageFiles(sc.root);
  72. const seen = new Set<string>();
  73. return all.filter((rel) => {
  74. if (seen.has(rel)) return false;
  75. seen.add(rel);
  76. const ext = rel.slice(rel.lastIndexOf('.') + 1).toLowerCase();
  77. if (!exts.includes(ext)) return false;
  78. if (laid.has(rel)) return false;
  79. if (product && NOT_PRODUCT.test(rel)) return false;
  80. return !sc.ignore.some((re) => re.test(rel));
  81. });
  82. }
  83. export function read(rel: string, root = process.cwd()): string {
  84. return readFileSync(join(root, rel), 'utf8');
  85. }
  86. /** 1-based line of an offset in a text. */
  87. export function lineAt(text: string, offset: number): number {
  88. let n = 1;
  89. for (let i = 0; i < offset && i < text.length; i++) if (text.charCodeAt(i) === 10) n++;
  90. return n;
  91. }
  92. /** Prints findings (one per line) and sets the exit code: the shape of every check of the design packages. */
  93. export function report(out: string[]): void {
  94. if (out.length) console.log(out.join('\n'));
  95. process.exitCode = out.length ? 1 : 0;
  96. }