package file→ .shtukbase/packages/std-editorconfig/checks/eclib.ts
checks/eclib.ts
207 lines, 7.7 KB.
- // EditorConfig (https://spec.editorconfig.org/, version 0.17.2): reading .editorconfig files, matching their section
- // globs, and the properties that apply to a file. Files are only read.
- import { existsSync, readFileSync } from 'node:fs';
- import { dirname, join, resolve } from 'node:path';
- import { excluder, git, inGit, list, projectFiles, ROOT, settings } from './lib/std.ts';
- export const PKG = 'std-editorconfig';
- export const DEFAULTS = { exclude: ['vendor/**', 'third_party/**', '**/fixtures/**', '**/testdata/**'], maxBytes: 1048576, changedSince: '' };
- export function config() {
- const c = settings('editorconfig', DEFAULTS);
- const since = (c.changedSince as unknown) instanceof Date ? (c.changedSince as unknown as Date).toISOString().slice(0, 10) : String(c.changedSince ?? '').trim();
- return { exclude: list(c.exclude), maxBytes: Number(c.maxBytes) || DEFAULTS.maxBytes, changedSince: since };
- }
- type Section = { re: RegExp; props: Record<string, string> };
- export type EcFile = { path: string; dir: string; root: boolean; sections: Section[] };
- function esc(s: string): string {
- return s.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
- }
- /** Finds the `}` that closes the `{` at `i`, or -1. */
- function closing(g: string, i: number): number {
- let depth = 0;
- for (let j = i; j < g.length; j++) {
- if (g[j] === '\\') j++;
- else if (g[j] === '{') depth++;
- else if (g[j] === '}' && --depth === 0) return j;
- }
- return -1;
- }
- function splitTop(s: string): string[] {
- const out: string[] = [];
- let depth = 0;
- let cur = '';
- for (let j = 0; j < s.length; j++) {
- const c = s[j];
- if (c === '\\') {
- cur += c + (s[j + 1] ?? '');
- j++;
- continue;
- }
- if (c === '{') depth++;
- if (c === '}') depth--;
- if (c === ',' && depth === 0) {
- out.push(cur);
- cur = '';
- } else cur += c;
- }
- out.push(cur);
- return out;
- }
- /** An EditorConfig glob as a regular expression body: `*`, `**`, `?`, `[set]`, `[!set]`, `{a,b}`, `{1..9}`, `\`. */
- export function globBody(g: string): string {
- let out = '';
- for (let i = 0; i < g.length; i++) {
- const c = g[i];
- if (c === '\\') {
- out += esc(g[i + 1] ?? '');
- i++;
- } else if (c === '*') {
- if (g[i + 1] === '*') {
- out += '.*';
- i++;
- } else out += '[^/]*';
- } else if (c === '?') out += '[^/]';
- else if (c === '[') {
- const end = g.indexOf(']', i + 1);
- const inner = end > i ? g.slice(i + 1, end) : '';
- if (end < 0 || inner.includes('/')) out += '\\[';
- else {
- const neg = inner.startsWith('!') || inner.startsWith('^');
- const body = (neg ? inner.slice(1) : inner).replace(/\\/g, '\\\\').replace(/]/g, '\\]');
- out += `[${neg ? '^' : ''}${body}]`;
- i = end;
- }
- } else if (c === '{') {
- const end = closing(g, i);
- if (end < 0) {
- out += '\\{';
- continue;
- }
- const inner = g.slice(i + 1, end);
- const range = /^([+-]?\d+)\.\.([+-]?\d+)$/.exec(inner);
- const parts = splitTop(inner);
- if (range) {
- const [a, b] = [Number(range[1]), Number(range[2])].sort((x, y) => x - y);
- out += b - a <= 2000 ? `(?:${Array.from({ length: b - a + 1 }, (_, k) => String(a + k)).map(esc).join('|')})` : '[+-]?\\d+';
- } else if (parts.length > 1) out += `(?:${parts.map(globBody).join('|')})`;
- else out += `\\{${globBody(inner)}\\}`;
- i = end;
- } else out += esc(c);
- }
- return out;
- }
- /** The regular expression of a section header in a file that lives in `dir` (absolute, no trailing slash). */
- export function sectionRe(glob: string, dir: string): RegExp {
- const anchored = glob.includes('/');
- const g = glob.startsWith('/') ? glob.slice(1) : glob;
- return new RegExp(`^${esc(dir)}/${anchored ? '' : '(?:.*/)?'}${globBody(g)}$`);
- }
- export function parseEc(path: string): EcFile {
- const dir = dirname(path);
- const ec: EcFile = { path, dir, root: false, sections: [] };
- let cur: Section | null = null;
- for (const raw of readFileSync(path, 'utf8').split(/\r?\n/)) {
- const l = raw.trim();
- if (!l || l.startsWith('#') || l.startsWith(';')) continue;
- const s = /^\[(.*)\]$/.exec(l);
- if (s) {
- try {
- cur = { re: sectionRe(s[1], dir), props: {} };
- } catch {
- cur = { re: /$^/, props: {} };
- }
- ec.sections.push(cur);
- continue;
- }
- const kv = /^([^=]+?)\s*=\s*(.*)$/.exec(l);
- if (!kv) continue;
- const key = kv[1].trim().toLowerCase();
- const value = kv[2].trim();
- if (!cur) {
- if (key === 'root') ec.root = value.toLowerCase() === 'true';
- } else cur.props[key] = value;
- }
- return ec;
- }
- const LOWER = new Set(['end_of_line', 'indent_style', 'indent_size', 'tab_width', 'insert_final_newline', 'trim_trailing_whitespace', 'charset', 'max_line_length']);
- export class Ec {
- private cache = new Map<string, EcFile | null>();
- private chains = new Map<string, EcFile[]>();
- private at(dir: string): EcFile | null {
- if (!this.cache.has(dir)) {
- const p = join(dir, '.editorconfig');
- let v: EcFile | null = null;
- if (existsSync(p)) {
- try {
- v = parseEc(p);
- } catch {
- v = null;
- }
- }
- this.cache.set(dir, v);
- }
- return this.cache.get(dir) ?? null;
- }
- /** The .editorconfig files that apply in `dir`, outermost first (the search stops at one with root = true). */
- chain(dir: string): EcFile[] {
- const hit = this.chains.get(dir);
- if (hit) return hit;
- const here = this.at(dir);
- let out: EcFile[];
- if (here?.root) out = [here];
- else {
- const up = dirname(dir);
- const above = up === dir ? [] : this.chain(up);
- out = here ? [...above, here] : above;
- }
- this.chains.set(dir, out);
- return out;
- }
- /** The properties for a file (relative to the project root); later sections and nearer files win; `unset` removes. */
- props(rel: string): Record<string, string> {
- const abs = resolve(ROOT, rel);
- const out: Record<string, string> = {};
- for (const ec of this.chain(dirname(abs)))
- for (const s of ec.sections)
- if (s.re.test(abs))
- for (const [k, v] of Object.entries(s.props)) out[k] = LOWER.has(k) ? v.toLowerCase() : v;
- for (const k of Object.keys(out)) if (out[k] === 'unset') delete out[k];
- if (out.indent_style === 'tab' && !out.indent_size) out.indent_size = 'tab';
- if (out.indent_size && out.indent_size !== 'tab' && !out.tab_width) out.tab_width = out.indent_size;
- return out;
- }
- }
- /** The files to check: the project's files minus `.editorconfig` itself and the excluded globs. */
- export function targets(): { ec: Ec; files: string[]; maxBytes: number } {
- const cfg = config();
- const skip = excluder(cfg.exclude);
- let files = projectFiles().filter((f) => !skip(f) && !f.endsWith('.editorconfig'));
- if (cfg.changedSince && inGit()) {
- // Brownfield: only the files touched since the day (commits, uncommitted edits, new files).
- const touched = new Set<string>();
- for (const out of [git(['log', '--relative', '--name-only', '--format=', `--since=${cfg.changedSince} 00:00:00`]), git(['diff', '--relative', '--name-only', 'HEAD']), git(['ls-files', '--others', '--exclude-standard'])])
- for (const l of (out ?? '').split('\n')) if (l.trim()) touched.add(l.trim());
- files = files.filter((f) => touched.has(f));
- }
- return { ec: new Ec(), files, maxBytes: cfg.maxBytes };
- }
- /** One finding line for a file: the first offending line, how many there are, and the fix. */
- export function finding(file: string, lines: number[], what: string, fix: string): string {
- const more = lines.length > 1 ? ` (lines: ${lines.length}; first: ${lines.slice(0, 5).join(', ')})` : '';
- return `${file}:${lines[0]}: ${what}${more} → ${fix}`;
- }