archivo del paquete→ .shtukbase/packages/code-pragmatic/checks/repeated_literals.ts
checks/repeated_literals.ts
39 líneas, 2.1 KB.
El archivo tal como está en el paquete: el código y sus comentarios no se traducen.
- // PRG-R01 (Hunt & Thomas, DRY). One piece of knowledge written as the same string literal in several files:
- // a literal of at least `minLength` characters (with a letter, on one line) in `minFiles` or more files.
- // Import paths, regex literals and docstrings are skipped. Duplicated code is the refactoring package's check;
- // this one looks for a repeated fact: a path, a key, a message, a format.
- import { type CheckDef, type Finding, num, runCheck } from '../../code-lib/checks/lib/run.ts';
- import { lineText } from '../../code-lib/checks/lib/scan.ts';
- export const CHECK: CheckDef = {
- pkg: 'code-pragmatic',
- rule: 'PRG-R01',
- name: 'repeated-literals',
- defaults: { minLength: 16, minFiles: 3 },
- scan(srcs, set) {
- const minLen = num(set.minLength, 16);
- const minFiles = num(set.minFiles, 3);
- const where = new Map<string, { rel: string; line: number }[]>();
- for (const s of srcs)
- for (const st of s.strings) {
- const v = st.value;
- if (v.length < minLen || v.includes('\n') || !/[A-Za-z]/.test(v) || v.includes('${…}')) continue;
- if (s.raw[st.start] === '/' || s.raw.slice(st.start, st.start + 3).match(/^("""|''')/)) continue;
- const code = lineText(s, st.line).trim();
- if (/^(import|export|from|use|mod|#\[|@)\b|require\(|import\(/.test(code)) continue;
- if (/\bclass(Name)?\s*[=:]|\b(cn|clsx|cva|twMerge)\(/.test(code)) continue; // CSS class lists are styling, not facts
- const list = where.get(v) ?? [];
- if (!list.some((x) => x.rel === s.rel)) list.push({ rel: s.rel, line: st.line });
- where.set(v, list);
- }
- const out: Finding[] = [];
- for (const [v, list] of where)
- if (list.length >= minFiles) {
- const shown = v.length > 60 ? v.slice(0, 57) + '…' : v;
- out.push({ rel: list[0].rel, line: list[0].line, msg: `the string "${shown}" is written in ${list.length} files (${list.slice(1, 4).map((x) => `${x.rel}:${x.line}`).join(', ')}${list.length > 4 ? ', …' : ''}): one piece of knowledge, one place — move it to a constant` });
- }
- return out;
- },
- };
- if (import.meta.main) runCheck(CHECK);