ShtukbaseStandard
包文件→ .shtukbase/packages/std-twelve-factor/checks/lib/std.ts

checks/lib/std.ts

154 行, 6.5 KB.

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

  1. // Shared helpers of the std-* packages (each package carries its own copy, so a package installs alone).
  2. // Run with the project root as the working directory. Read only: files are read, git is only asked
  3. // (ls-files, log, show, tag, check-ignore); nothing is written.
  4. import { spawnSync } from 'node:child_process';
  5. import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
  6. import { join } from 'node:path';
  7. export const ROOT = process.cwd();
  8. export type Head = Record<string, unknown>;
  9. /** The front matter of a page (empty when the page or its front matter is missing or unreadable). */
  10. export function frontMatter(path: string): Head {
  11. if (!existsSync(path)) return {};
  12. const text = readFileSync(path, 'utf8');
  13. const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
  14. if (!m) return {};
  15. try {
  16. const v = Bun.YAML.parse(m[1]);
  17. return v && typeof v === 'object' && !Array.isArray(v) ? (v as Head) : {};
  18. } catch {
  19. return {};
  20. }
  21. }
  22. /** Settings from the project page /norms/standards/<page>.md over the package defaults. */
  23. export function settings<T extends Head>(page: string, defaults: T): T {
  24. const fm = frontMatter(join(ROOT, 'norms', 'standards', `${page}.md`));
  25. const out: Head = { ...defaults };
  26. for (const k of Object.keys(defaults)) if (fm[k] !== undefined && fm[k] !== null) out[k] = fm[k];
  27. return out as T;
  28. }
  29. export function list(v: unknown): string[] {
  30. if (v === undefined || v === null || v === '') return [];
  31. return (Array.isArray(v) ? v : [v]).map((x) => String(x).trim()).filter(Boolean);
  32. }
  33. export type Norm = { id: string; pkg: string; mode: string; active: boolean };
  34. /** The norm as the project holds it: its mode (observe, warn, enforce) and whether it is in force. A missing page
  35. * (for example, the check runs on a repository without the package) falls back to the package default. */
  36. export function norm(pkg: string, id: string, fallbackMode: string): Norm {
  37. const path = join(ROOT, 'norms', 'rules', pkg, `${id}.md`);
  38. if (!existsSync(path)) return { id, pkg, mode: fallbackMode, active: true };
  39. const fm = frontMatter(path);
  40. const status = String(fm.status ?? 'active').trim();
  41. return { id, pkg, mode: String(fm.mode ?? fallbackMode).trim(), active: status === 'active' };
  42. }
  43. /** Prints the findings and sets the exit code: only a norm in `enforce` mode fails; observe and warn report. */
  44. export function finish(n: Norm, findings: string[]): void {
  45. if (!n.active) {
  46. process.exitCode = 0;
  47. return;
  48. }
  49. const soft = n.mode !== 'enforce';
  50. if (findings.length) {
  51. console.log(findings.map((f) => (soft ? `(${n.mode}) ${f}` : f)).join('\n'));
  52. if (soft) console.log(`(${n.mode}) ${n.id}: findings ${findings.length}; the mode is not "enforce", the check does not fail`);
  53. }
  54. process.exitCode = findings.length && !soft ? 1 : 0;
  55. }
  56. /** Runs git read-only in the project root; null when git is missing or the command fails. */
  57. export function git(args: string[], opts: { okCodes?: number[] } = {}): string | null {
  58. const r = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
  59. if (r.error) return null;
  60. if (r.status !== 0 && !(opts.okCodes ?? []).includes(r.status ?? -1)) return null;
  61. return r.stdout;
  62. }
  63. export function inGit(): boolean {
  64. return git(['rev-parse', '--is-inside-work-tree'])?.trim() === 'true';
  65. }
  66. const SKIP_DIRS = new Set(['.git', 'node_modules', '.shtukbase', 'target', 'dist', 'build', '.venv', 'venv', '__pycache__', '.cache', '.next', '.turbo', '.pnpm-store']);
  67. /** The project's files, relative to the root: what git sees (tracked and untracked, ignored left out) in a git
  68. * repository, else a walk that skips the usual build and dependency folders. `.shtukbase/` is never included. */
  69. export function projectFiles(): string[] {
  70. let files: string[] = [];
  71. if (inGit()) {
  72. const out = git(['ls-files', '-z', '--cached', '--others', '--exclude-standard']);
  73. if (out !== null) files = [...new Set(out.split('\0').filter(Boolean))];
  74. } else {
  75. const walk = (rel: string) => {
  76. let names: string[] = [];
  77. try {
  78. names = readdirSync(join(ROOT, rel));
  79. } catch {
  80. return;
  81. }
  82. for (const name of names) {
  83. const r = rel ? `${rel}/${name}` : name;
  84. let st;
  85. try {
  86. st = statSync(join(ROOT, r));
  87. } catch {
  88. continue;
  89. }
  90. if (st.isDirectory()) {
  91. if (!SKIP_DIRS.has(name)) walk(r);
  92. } else if (st.isFile()) files.push(r);
  93. }
  94. };
  95. walk('');
  96. }
  97. return files.filter((f) => !f.startsWith('.shtukbase/') && !f.includes('/.shtukbase/') && !f.split('/').includes('node_modules'));
  98. }
  99. /** Glob filter from settings (`exclude: [glob, ...]`, Bun glob syntax, paths from the project root). */
  100. export function excluder(globs: string[]): (path: string) => boolean {
  101. const gs = globs.map((g) => new Bun.Glob(g));
  102. return (p) => gs.some((g) => g.match(p));
  103. }
  104. const BINARY_EXT = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'ico', 'icns', 'pdf', 'zip', 'gz', 'tgz', 'xz', 'bz2', '7z', 'jar', 'class', 'so', 'dylib', 'dll', 'exe', 'o', 'a', 'wasm', 'mp4', 'mov', 'mp3', 'wav', 'ogg', 'woff', 'woff2', 'ttf', 'otf', 'eot', 'sqlite', 'db', 'bin', 'lockb', 'heic', 'psd', 'avif', 'tiff', 'bmp']);
  105. /** A text file's bytes, or null for a missing, large (over `maxBytes`) or binary file. */
  106. export function readTextBuffer(rel: string, maxBytes = 1024 * 1024): Buffer | null {
  107. const ext = rel.split('.').pop()?.toLowerCase() ?? '';
  108. if (BINARY_EXT.has(ext)) return null;
  109. const path = join(ROOT, rel);
  110. let st;
  111. try {
  112. st = statSync(path);
  113. } catch {
  114. return null;
  115. }
  116. if (!st.isFile() || st.size > maxBytes) return null;
  117. const buf = readFileSync(path);
  118. if (buf.subarray(0, 8000).includes(0)) return null;
  119. return buf;
  120. }
  121. /** A text file's content, or null for a missing, large (over `maxBytes`) or binary file. */
  122. export function readTextFile(rel: string, maxBytes = 1024 * 1024): string | null {
  123. return readTextBuffer(rel, maxBytes)?.toString('utf8') ?? null;
  124. }
  125. /** Named flags of an action: `--name value` and bare `--flag`. */
  126. export function flags(argv: string[] = process.argv.slice(2)): Record<string, string | true> {
  127. const out: Record<string, string | true> = {};
  128. for (let i = 0; i < argv.length; i++) {
  129. const a = argv[i];
  130. if (!a.startsWith('--')) continue;
  131. const eq = a.indexOf('=');
  132. if (eq > 0) out[a.slice(2, eq)] = a.slice(eq + 1);
  133. else if (i + 1 < argv.length && !argv[i + 1].startsWith('--')) out[a.slice(2)] = argv[++i];
  134. else out[a.slice(2)] = true;
  135. }
  136. return out;
  137. }