archivo del paquete→ .shtukbase/packages/std-semver/checks/lib/std.ts
checks/lib/std.ts
154 líneas, 6.5 KB.
El archivo tal como está en el paquete: el código y sus comentarios no se traducen.
- // Shared helpers of the std-* packages (each package carries its own copy, so a package installs alone).
- // Run with the project root as the working directory. Read only: files are read, git is only asked
- // (ls-files, log, show, tag, check-ignore); nothing is written.
- import { spawnSync } from 'node:child_process';
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
- import { join } from 'node:path';
- export const ROOT = process.cwd();
- export type Head = Record<string, unknown>;
- /** The front matter of a page (empty when the page or its front matter is missing or unreadable). */
- export function frontMatter(path: string): Head {
- if (!existsSync(path)) return {};
- const text = readFileSync(path, 'utf8');
- const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
- if (!m) return {};
- try {
- const v = Bun.YAML.parse(m[1]);
- return v && typeof v === 'object' && !Array.isArray(v) ? (v as Head) : {};
- } catch {
- return {};
- }
- }
- /** Settings from the project page /norms/standards/<page>.md over the package defaults. */
- export function settings<T extends Head>(page: string, defaults: T): T {
- const fm = frontMatter(join(ROOT, 'norms', 'standards', `${page}.md`));
- const out: Head = { ...defaults };
- for (const k of Object.keys(defaults)) if (fm[k] !== undefined && fm[k] !== null) out[k] = fm[k];
- return out as T;
- }
- export function list(v: unknown): string[] {
- if (v === undefined || v === null || v === '') return [];
- return (Array.isArray(v) ? v : [v]).map((x) => String(x).trim()).filter(Boolean);
- }
- export type Norm = { id: string; pkg: string; mode: string; active: boolean };
- /** The norm as the project holds it: its mode (observe, warn, enforce) and whether it is in force. A missing page
- * (for example, the check runs on a repository without the package) falls back to the package default. */
- export function norm(pkg: string, id: string, fallbackMode: string): Norm {
- const path = join(ROOT, 'norms', 'rules', pkg, `${id}.md`);
- if (!existsSync(path)) return { id, pkg, mode: fallbackMode, active: true };
- const fm = frontMatter(path);
- const status = String(fm.status ?? 'active').trim();
- return { id, pkg, mode: String(fm.mode ?? fallbackMode).trim(), active: status === 'active' };
- }
- /** Prints the findings and sets the exit code: only a norm in `enforce` mode fails; observe and warn report. */
- export function finish(n: Norm, findings: string[]): void {
- if (!n.active) {
- process.exitCode = 0;
- return;
- }
- const soft = n.mode !== 'enforce';
- if (findings.length) {
- console.log(findings.map((f) => (soft ? `(${n.mode}) ${f}` : f)).join('\n'));
- if (soft) console.log(`(${n.mode}) ${n.id}: findings ${findings.length}; the mode is not "enforce", the check does not fail`);
- }
- process.exitCode = findings.length && !soft ? 1 : 0;
- }
- /** Runs git read-only in the project root; null when git is missing or the command fails. */
- export function git(args: string[], opts: { okCodes?: number[] } = {}): string | null {
- const r = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
- if (r.error) return null;
- if (r.status !== 0 && !(opts.okCodes ?? []).includes(r.status ?? -1)) return null;
- return r.stdout;
- }
- export function inGit(): boolean {
- return git(['rev-parse', '--is-inside-work-tree'])?.trim() === 'true';
- }
- const SKIP_DIRS = new Set(['.git', 'node_modules', '.shtukbase', 'target', 'dist', 'build', '.venv', 'venv', '__pycache__', '.cache', '.next', '.turbo', '.pnpm-store']);
- /** The project's files, relative to the root: what git sees (tracked and untracked, ignored left out) in a git
- * repository, else a walk that skips the usual build and dependency folders. `.shtukbase/` is never included. */
- export function projectFiles(): string[] {
- let files: string[] = [];
- if (inGit()) {
- const out = git(['ls-files', '-z', '--cached', '--others', '--exclude-standard']);
- if (out !== null) files = [...new Set(out.split('\0').filter(Boolean))];
- } else {
- const walk = (rel: string) => {
- let names: string[] = [];
- try {
- names = readdirSync(join(ROOT, rel));
- } catch {
- return;
- }
- for (const name of names) {
- const r = rel ? `${rel}/${name}` : name;
- let st;
- try {
- st = statSync(join(ROOT, r));
- } catch {
- continue;
- }
- if (st.isDirectory()) {
- if (!SKIP_DIRS.has(name)) walk(r);
- } else if (st.isFile()) files.push(r);
- }
- };
- walk('');
- }
- return files.filter((f) => !f.startsWith('.shtukbase/') && !f.includes('/.shtukbase/') && !f.split('/').includes('node_modules'));
- }
- /** Glob filter from settings (`exclude: [glob, ...]`, Bun glob syntax, paths from the project root). */
- export function excluder(globs: string[]): (path: string) => boolean {
- const gs = globs.map((g) => new Bun.Glob(g));
- return (p) => gs.some((g) => g.match(p));
- }
- 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']);
- /** A text file's bytes, or null for a missing, large (over `maxBytes`) or binary file. */
- export function readTextBuffer(rel: string, maxBytes = 1024 * 1024): Buffer | null {
- const ext = rel.split('.').pop()?.toLowerCase() ?? '';
- if (BINARY_EXT.has(ext)) return null;
- const path = join(ROOT, rel);
- let st;
- try {
- st = statSync(path);
- } catch {
- return null;
- }
- if (!st.isFile() || st.size > maxBytes) return null;
- const buf = readFileSync(path);
- if (buf.subarray(0, 8000).includes(0)) return null;
- return buf;
- }
- /** A text file's content, or null for a missing, large (over `maxBytes`) or binary file. */
- export function readTextFile(rel: string, maxBytes = 1024 * 1024): string | null {
- return readTextBuffer(rel, maxBytes)?.toString('utf8') ?? null;
- }
- /** Named flags of an action: `--name value` and bare `--flag`. */
- export function flags(argv: string[] = process.argv.slice(2)): Record<string, string | true> {
- const out: Record<string, string | true> = {};
- for (let i = 0; i < argv.length; i++) {
- const a = argv[i];
- if (!a.startsWith('--')) continue;
- const eq = a.indexOf('=');
- if (eq > 0) out[a.slice(2, eq)] = a.slice(eq + 1);
- else if (i + 1 < argv.length && !argv[i + 1].startsWith('--')) out[a.slice(2)] = argv[++i];
- else out[a.slice(2)] = true;
- }
- return out;
- }