ShtukbaseStandard
包文件→ .shtukbase/packages/std-editorconfig/checks/eclib.ts

checks/eclib.ts

207 行, 7.7 KB.

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

  1. // EditorConfig (https://spec.editorconfig.org/, version 0.17.2): reading .editorconfig files, matching their section
  2. // globs, and the properties that apply to a file. Files are only read.
  3. import { existsSync, readFileSync } from 'node:fs';
  4. import { dirname, join, resolve } from 'node:path';
  5. import { excluder, git, inGit, list, projectFiles, ROOT, settings } from './lib/std.ts';
  6. export const PKG = 'std-editorconfig';
  7. export const DEFAULTS = { exclude: ['vendor/**', 'third_party/**', '**/fixtures/**', '**/testdata/**'], maxBytes: 1048576, changedSince: '' };
  8. export function config() {
  9. const c = settings('editorconfig', DEFAULTS);
  10. const since = (c.changedSince as unknown) instanceof Date ? (c.changedSince as unknown as Date).toISOString().slice(0, 10) : String(c.changedSince ?? '').trim();
  11. return { exclude: list(c.exclude), maxBytes: Number(c.maxBytes) || DEFAULTS.maxBytes, changedSince: since };
  12. }
  13. type Section = { re: RegExp; props: Record<string, string> };
  14. export type EcFile = { path: string; dir: string; root: boolean; sections: Section[] };
  15. function esc(s: string): string {
  16. return s.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
  17. }
  18. /** Finds the `}` that closes the `{` at `i`, or -1. */
  19. function closing(g: string, i: number): number {
  20. let depth = 0;
  21. for (let j = i; j < g.length; j++) {
  22. if (g[j] === '\\') j++;
  23. else if (g[j] === '{') depth++;
  24. else if (g[j] === '}' && --depth === 0) return j;
  25. }
  26. return -1;
  27. }
  28. function splitTop(s: string): string[] {
  29. const out: string[] = [];
  30. let depth = 0;
  31. let cur = '';
  32. for (let j = 0; j < s.length; j++) {
  33. const c = s[j];
  34. if (c === '\\') {
  35. cur += c + (s[j + 1] ?? '');
  36. j++;
  37. continue;
  38. }
  39. if (c === '{') depth++;
  40. if (c === '}') depth--;
  41. if (c === ',' && depth === 0) {
  42. out.push(cur);
  43. cur = '';
  44. } else cur += c;
  45. }
  46. out.push(cur);
  47. return out;
  48. }
  49. /** An EditorConfig glob as a regular expression body: `*`, `**`, `?`, `[set]`, `[!set]`, `{a,b}`, `{1..9}`, `\`. */
  50. export function globBody(g: string): string {
  51. let out = '';
  52. for (let i = 0; i < g.length; i++) {
  53. const c = g[i];
  54. if (c === '\\') {
  55. out += esc(g[i + 1] ?? '');
  56. i++;
  57. } else if (c === '*') {
  58. if (g[i + 1] === '*') {
  59. out += '.*';
  60. i++;
  61. } else out += '[^/]*';
  62. } else if (c === '?') out += '[^/]';
  63. else if (c === '[') {
  64. const end = g.indexOf(']', i + 1);
  65. const inner = end > i ? g.slice(i + 1, end) : '';
  66. if (end < 0 || inner.includes('/')) out += '\\[';
  67. else {
  68. const neg = inner.startsWith('!') || inner.startsWith('^');
  69. const body = (neg ? inner.slice(1) : inner).replace(/\\/g, '\\\\').replace(/]/g, '\\]');
  70. out += `[${neg ? '^' : ''}${body}]`;
  71. i = end;
  72. }
  73. } else if (c === '{') {
  74. const end = closing(g, i);
  75. if (end < 0) {
  76. out += '\\{';
  77. continue;
  78. }
  79. const inner = g.slice(i + 1, end);
  80. const range = /^([+-]?\d+)\.\.([+-]?\d+)$/.exec(inner);
  81. const parts = splitTop(inner);
  82. if (range) {
  83. const [a, b] = [Number(range[1]), Number(range[2])].sort((x, y) => x - y);
  84. out += b - a <= 2000 ? `(?:${Array.from({ length: b - a + 1 }, (_, k) => String(a + k)).map(esc).join('|')})` : '[+-]?\\d+';
  85. } else if (parts.length > 1) out += `(?:${parts.map(globBody).join('|')})`;
  86. else out += `\\{${globBody(inner)}\\}`;
  87. i = end;
  88. } else out += esc(c);
  89. }
  90. return out;
  91. }
  92. /** The regular expression of a section header in a file that lives in `dir` (absolute, no trailing slash). */
  93. export function sectionRe(glob: string, dir: string): RegExp {
  94. const anchored = glob.includes('/');
  95. const g = glob.startsWith('/') ? glob.slice(1) : glob;
  96. return new RegExp(`^${esc(dir)}/${anchored ? '' : '(?:.*/)?'}${globBody(g)}$`);
  97. }
  98. export function parseEc(path: string): EcFile {
  99. const dir = dirname(path);
  100. const ec: EcFile = { path, dir, root: false, sections: [] };
  101. let cur: Section | null = null;
  102. for (const raw of readFileSync(path, 'utf8').split(/\r?\n/)) {
  103. const l = raw.trim();
  104. if (!l || l.startsWith('#') || l.startsWith(';')) continue;
  105. const s = /^\[(.*)\]$/.exec(l);
  106. if (s) {
  107. try {
  108. cur = { re: sectionRe(s[1], dir), props: {} };
  109. } catch {
  110. cur = { re: /$^/, props: {} };
  111. }
  112. ec.sections.push(cur);
  113. continue;
  114. }
  115. const kv = /^([^=]+?)\s*=\s*(.*)$/.exec(l);
  116. if (!kv) continue;
  117. const key = kv[1].trim().toLowerCase();
  118. const value = kv[2].trim();
  119. if (!cur) {
  120. if (key === 'root') ec.root = value.toLowerCase() === 'true';
  121. } else cur.props[key] = value;
  122. }
  123. return ec;
  124. }
  125. const LOWER = new Set(['end_of_line', 'indent_style', 'indent_size', 'tab_width', 'insert_final_newline', 'trim_trailing_whitespace', 'charset', 'max_line_length']);
  126. export class Ec {
  127. private cache = new Map<string, EcFile | null>();
  128. private chains = new Map<string, EcFile[]>();
  129. private at(dir: string): EcFile | null {
  130. if (!this.cache.has(dir)) {
  131. const p = join(dir, '.editorconfig');
  132. let v: EcFile | null = null;
  133. if (existsSync(p)) {
  134. try {
  135. v = parseEc(p);
  136. } catch {
  137. v = null;
  138. }
  139. }
  140. this.cache.set(dir, v);
  141. }
  142. return this.cache.get(dir) ?? null;
  143. }
  144. /** The .editorconfig files that apply in `dir`, outermost first (the search stops at one with root = true). */
  145. chain(dir: string): EcFile[] {
  146. const hit = this.chains.get(dir);
  147. if (hit) return hit;
  148. const here = this.at(dir);
  149. let out: EcFile[];
  150. if (here?.root) out = [here];
  151. else {
  152. const up = dirname(dir);
  153. const above = up === dir ? [] : this.chain(up);
  154. out = here ? [...above, here] : above;
  155. }
  156. this.chains.set(dir, out);
  157. return out;
  158. }
  159. /** The properties for a file (relative to the project root); later sections and nearer files win; `unset` removes. */
  160. props(rel: string): Record<string, string> {
  161. const abs = resolve(ROOT, rel);
  162. const out: Record<string, string> = {};
  163. for (const ec of this.chain(dirname(abs)))
  164. for (const s of ec.sections)
  165. if (s.re.test(abs))
  166. for (const [k, v] of Object.entries(s.props)) out[k] = LOWER.has(k) ? v.toLowerCase() : v;
  167. for (const k of Object.keys(out)) if (out[k] === 'unset') delete out[k];
  168. if (out.indent_style === 'tab' && !out.indent_size) out.indent_size = 'tab';
  169. if (out.indent_size && out.indent_size !== 'tab' && !out.tab_width) out.tab_width = out.indent_size;
  170. return out;
  171. }
  172. }
  173. /** The files to check: the project's files minus `.editorconfig` itself and the excluded globs. */
  174. export function targets(): { ec: Ec; files: string[]; maxBytes: number } {
  175. const cfg = config();
  176. const skip = excluder(cfg.exclude);
  177. let files = projectFiles().filter((f) => !skip(f) && !f.endsWith('.editorconfig'));
  178. if (cfg.changedSince && inGit()) {
  179. // Brownfield: only the files touched since the day (commits, uncommitted edits, new files).
  180. const touched = new Set<string>();
  181. 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'])])
  182. for (const l of (out ?? '').split('\n')) if (l.trim()) touched.add(l.trim());
  183. files = files.filter((f) => touched.has(f));
  184. }
  185. return { ec: new Ec(), files, maxBytes: cfg.maxBytes };
  186. }
  187. /** One finding line for a file: the first offending line, how many there are, and the fix. */
  188. export function finding(file: string, lines: number[], what: string, fix: string): string {
  189. const more = lines.length > 1 ? ` (lines: ${lines.length}; first: ${lines.slice(0, 5).join(', ')})` : '';
  190. return `${file}:${lines[0]}: ${what}${more} → ${fix}`;
  191. }