ShtukbaseStandard
package file→ .shtukbase/packages/code-pragmatic/checks/repeated_literals.ts

checks/repeated_literals.ts

39 lines, 2.1 KB.

  1. // PRG-R01 (Hunt & Thomas, DRY). One piece of knowledge written as the same string literal in several files:
  2. // a literal of at least `minLength` characters (with a letter, on one line) in `minFiles` or more files.
  3. // Import paths, regex literals and docstrings are skipped. Duplicated code is the refactoring package's check;
  4. // this one looks for a repeated fact: a path, a key, a message, a format.
  5. import { type CheckDef, type Finding, num, runCheck } from '../../code-lib/checks/lib/run.ts';
  6. import { lineText } from '../../code-lib/checks/lib/scan.ts';
  7. export const CHECK: CheckDef = {
  8. pkg: 'code-pragmatic',
  9. rule: 'PRG-R01',
  10. name: 'repeated-literals',
  11. defaults: { minLength: 16, minFiles: 3 },
  12. scan(srcs, set) {
  13. const minLen = num(set.minLength, 16);
  14. const minFiles = num(set.minFiles, 3);
  15. const where = new Map<string, { rel: string; line: number }[]>();
  16. for (const s of srcs)
  17. for (const st of s.strings) {
  18. const v = st.value;
  19. if (v.length < minLen || v.includes('\n') || !/[A-Za-z]/.test(v) || v.includes('${…}')) continue;
  20. if (s.raw[st.start] === '/' || s.raw.slice(st.start, st.start + 3).match(/^("""|''')/)) continue;
  21. const code = lineText(s, st.line).trim();
  22. if (/^(import|export|from|use|mod|#\[|@)\b|require\(|import\(/.test(code)) continue;
  23. if (/\bclass(Name)?\s*[=:]|\b(cn|clsx|cva|twMerge)\(/.test(code)) continue; // CSS class lists are styling, not facts
  24. const list = where.get(v) ?? [];
  25. if (!list.some((x) => x.rel === s.rel)) list.push({ rel: s.rel, line: st.line });
  26. where.set(v, list);
  27. }
  28. const out: Finding[] = [];
  29. for (const [v, list] of where)
  30. if (list.length >= minFiles) {
  31. const shown = v.length > 60 ? v.slice(0, 57) + '…' : v;
  32. 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` });
  33. }
  34. return out;
  35. },
  36. };
  37. if (import.meta.main) runCheck(CHECK);