archivo del paquete→ .shtukbase/packages/std-editorconfig/checks/ec02_files.ts
checks/ec02_files.ts
57 líneas, 2.6 KB.
El archivo tal como está en el paquete: el código y sus comentarios no se traducen.
- // EC-R02: files match the exact properties of their .editorconfig: end_of_line, insert_final_newline = true,
- // trim_trailing_whitespace = true, charset (utf-8, utf-8-bom). Binary and large files are skipped.
- import { finding, PKG, targets } from './eclib.ts';
- import { finish, norm, readTextBuffer } from './lib/std.ts';
- const UTF8 = new TextDecoder('utf-8', { fatal: true });
- const n = norm(PKG, 'EC-R02', 'enforce');
- const out: string[] = [];
- if (n.active) {
- const { ec, files, maxBytes } = targets();
- for (const f of files) {
- const p = ec.props(f);
- const keys = ['end_of_line', 'insert_final_newline', 'trim_trailing_whitespace', 'charset'];
- if (!keys.some((k) => p[k])) continue;
- const buf = readTextBuffer(f, maxBytes);
- if (buf === null || !buf.length) continue;
- const text = buf.toString('utf8');
- const cs = p.charset;
- if (cs === 'utf-8' || cs === 'utf-8-bom') {
- const bom = text.charCodeAt(0) === 0xfeff;
- if (cs === 'utf-8' && bom) out.push(`${f}:1: a BOM at the start, but charset = utf-8 → save without a BOM`);
- if (cs === 'utf-8-bom' && !bom) out.push(`${f}:1: no BOM, but charset = utf-8-bom → save with a BOM`);
- try {
- UTF8.decode(buf);
- } catch {
- const ln = text.split('\n').findIndex((l) => l.includes('\uFFFD')) + 1;
- out.push(`${f}:${ln || 1}: the bytes are not UTF-8 → save again as UTF-8`);
- }
- }
- const lines = text.split('\n');
- const eol = p.end_of_line;
- if (eol === 'lf' || eol === 'crlf' || eol === 'cr') {
- const bad: number[] = [];
- lines.forEach((l, i) => {
- if (i === lines.length - 1) {
- if (eol === 'cr' && l.includes('\n')) bad.push(i + 1);
- return;
- }
- const cr = l.endsWith('\r');
- if ((eol === 'lf' && cr) || (eol === 'crlf' && !cr)) bad.push(i + 1);
- if (eol === 'cr') bad.push(i + 1);
- if (eol !== 'cr' && l.slice(0, -1).includes('\r')) bad.push(i + 1);
- });
- if (bad.length) out.push(finding(f, [...new Set(bad)], `line endings are not ${eol.toUpperCase()}`, `convert the line endings to ${eol.toUpperCase()}`));
- }
- if (p.insert_final_newline === 'true' && !text.endsWith('\n') && !text.endsWith('\r')) out.push(`${f}:${lines.length}: no newline at the end of the file → add it`);
- if (p.trim_trailing_whitespace === 'true') {
- const bad: number[] = [];
- lines.forEach((l, i) => {
- if (/[ \t]+\r?$/.test(l) && l.replace(/\r$/, '').length) bad.push(i + 1);
- });
- if (bad.length) out.push(finding(f, bad, 'spaces or tabs at the end of a line', 'remove the trailing spaces'));
- }
- }
- }
- finish(n, out);