ShtukbaseStandard
файл пакета→ .shtukbase/packages/std-editorconfig/checks/ec02_files.ts

checks/ec02_files.ts

57 строк, 2.6 КБ.

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

  1. // EC-R02: files match the exact properties of their .editorconfig: end_of_line, insert_final_newline = true,
  2. // trim_trailing_whitespace = true, charset (utf-8, utf-8-bom). Binary and large files are skipped.
  3. import { finding, PKG, targets } from './eclib.ts';
  4. import { finish, norm, readTextBuffer } from './lib/std.ts';
  5. const UTF8 = new TextDecoder('utf-8', { fatal: true });
  6. const n = norm(PKG, 'EC-R02', 'enforce');
  7. const out: string[] = [];
  8. if (n.active) {
  9. const { ec, files, maxBytes } = targets();
  10. for (const f of files) {
  11. const p = ec.props(f);
  12. const keys = ['end_of_line', 'insert_final_newline', 'trim_trailing_whitespace', 'charset'];
  13. if (!keys.some((k) => p[k])) continue;
  14. const buf = readTextBuffer(f, maxBytes);
  15. if (buf === null || !buf.length) continue;
  16. const text = buf.toString('utf8');
  17. const cs = p.charset;
  18. if (cs === 'utf-8' || cs === 'utf-8-bom') {
  19. const bom = text.charCodeAt(0) === 0xfeff;
  20. if (cs === 'utf-8' && bom) out.push(`${f}:1: a BOM at the start, but charset = utf-8 → save without a BOM`);
  21. if (cs === 'utf-8-bom' && !bom) out.push(`${f}:1: no BOM, but charset = utf-8-bom → save with a BOM`);
  22. try {
  23. UTF8.decode(buf);
  24. } catch {
  25. const ln = text.split('\n').findIndex((l) => l.includes('\uFFFD')) + 1;
  26. out.push(`${f}:${ln || 1}: the bytes are not UTF-8 → save again as UTF-8`);
  27. }
  28. }
  29. const lines = text.split('\n');
  30. const eol = p.end_of_line;
  31. if (eol === 'lf' || eol === 'crlf' || eol === 'cr') {
  32. const bad: number[] = [];
  33. lines.forEach((l, i) => {
  34. if (i === lines.length - 1) {
  35. if (eol === 'cr' && l.includes('\n')) bad.push(i + 1);
  36. return;
  37. }
  38. const cr = l.endsWith('\r');
  39. if ((eol === 'lf' && cr) || (eol === 'crlf' && !cr)) bad.push(i + 1);
  40. if (eol === 'cr') bad.push(i + 1);
  41. if (eol !== 'cr' && l.slice(0, -1).includes('\r')) bad.push(i + 1);
  42. });
  43. if (bad.length) out.push(finding(f, [...new Set(bad)], `line endings are not ${eol.toUpperCase()}`, `convert the line endings to ${eol.toUpperCase()}`));
  44. }
  45. 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`);
  46. if (p.trim_trailing_whitespace === 'true') {
  47. const bad: number[] = [];
  48. lines.forEach((l, i) => {
  49. if (/[ \t]+\r?$/.test(l) && l.replace(/\r$/, '').length) bad.push(i + 1);
  50. });
  51. if (bad.length) out.push(finding(f, bad, 'spaces or tabs at the end of a line', 'remove the trailing spaces'));
  52. }
  53. }
  54. }
  55. finish(n, out);