@blundergoat/gruff-ts 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/line-rules.ts CHANGED
@@ -33,6 +33,10 @@ interface LineRuleContext {
33
33
  file: SourceFile;
34
34
  line: string;
35
35
  codeLine: string;
36
+ // Full masked source as one array per line, indexed 0-based. Exposed so per-line rules that need
37
+ // forward look-ahead (for-of body brace-balancing in `pushVariableNameFindings`) can scan beyond
38
+ // the current line without re-splitting the source.
39
+ codeLines: readonly string[];
36
40
  lineNumber: number;
37
41
  config: Config;
38
42
  findings: Finding[];
@@ -57,6 +61,7 @@ export function analyseLineRules(file: SourceFile, source: string, codeSource: s
57
61
  file,
58
62
  line: "",
59
63
  codeLine: "",
64
+ codeLines,
60
65
  lineNumber: 0,
61
66
  config,
62
67
  findings,
@@ -281,10 +286,18 @@ function isSuppressedByPathContext(ruleId: string, displayPath: string): boolean
281
286
 
282
287
  // Per-line variable-name pass that runs short/identifier-quality checks on both
283
288
  // regular `const`/`let` declarations and destructured names. Reports any findings produced.
289
+ // Single-character for-of bindings whose body is ≤ 10 lines are idiomatic (e.g. `for (const f of
290
+ // files) { write(f); }`) and skip the short-variable check; longer bodies still flag. The
291
+ // exemption is gated on a real `of` token after the binding so C-style `for (let i = 0; …)` and
292
+ // `for (const k in obj)` headers stay covered by the rule.
284
293
  function pushVariableNameFindings(context: LineRuleContext): void {
285
294
  for (const match of context.codeLine.matchAll(context.variables)) {
286
295
  const name = match[1] ?? "";
287
- pushShortVariableFinding(context, name);
296
+ const matchText = match[0] ?? "";
297
+ const headerTail = context.codeLine.slice((match.index ?? 0) + matchText.length);
298
+ const isForOfHeader = matchText.startsWith("for") && /^\s+of\b/.test(headerTail);
299
+ const loopBodyLineCount = isForOfHeader ? forOfBodyLineSpan(context.codeLines, context.lineNumber - 1) : undefined;
300
+ pushShortVariableFinding(context, name, loopBodyLineCount);
288
301
  pushIdentifierQualityFinding(context, name);
289
302
  }
290
303
  for (const name of destructuredLocalNames(context.codeLine)) {
@@ -293,6 +306,45 @@ function pushVariableNameFindings(context: LineRuleContext): void {
293
306
  }
294
307
  }
295
308
 
309
+ /*
310
+ * Counts the line span of a for-of body starting at the opener line index. Brace-less
311
+ * single-statement bodies return 1 because the body is trivially short. When the opener has `{`,
312
+ * brace-balance tracking finds the matching `}` and returns the line count from `{` to `}`
313
+ * inclusive. The walker uses the masked codeLines so braces inside string literals are blanked
314
+ * out; this avoids the false "balanced" claim a raw-source walker would make on template strings.
315
+ * A 50-line scan window guards against unterminated scans because malformed input must not stall
316
+ * the whole-file walker; an unbalanced result returns Infinity so a long-but-unclosed for-of
317
+ * still fires the rule rather than getting silently exempted.
318
+ */
319
+ function forOfBodyLineSpan(codeLines: readonly string[], openerLineIndex: number): number {
320
+ const maxLines = 50;
321
+ const end = Math.min(codeLines.length, openerLineIndex + maxLines);
322
+ let state: ForOfBraceScanState = { depth: 0, bodyOpenerLine: -1 };
323
+ for (let i = openerLineIndex; i < end; i += 1) {
324
+ state = advanceForOfBraceScan(state, codeLines[i] ?? "", i);
325
+ if (state.bodyOpenerLine !== -1 && state.depth <= 0) {
326
+ return i - state.bodyOpenerLine + 1;
327
+ }
328
+ }
329
+ return state.bodyOpenerLine === -1 ? 1 : Infinity;
330
+ }
331
+
332
+ // Working state for the per-line brace scan. Returning a fresh value each line keeps the outer
333
+ // loop's npath low and the transition rules explicit.
334
+ interface ForOfBraceScanState {
335
+ depth: number;
336
+ bodyOpenerLine: number;
337
+ }
338
+
339
+ // Per-line brace-balance update. Records the first line that introduced a `{` so the caller can
340
+ // compute the body span when the balancing `}` lands.
341
+ function advanceForOfBraceScan(state: ForOfBraceScanState, line: string, lineIndex: number): ForOfBraceScanState {
342
+ const opens = (line.match(/\{/g) ?? []).length;
343
+ const closes = (line.match(/\}/g) ?? []).length;
344
+ const bodyOpenerLine = opens > 0 && state.bodyOpenerLine === -1 ? lineIndex : state.bodyOpenerLine;
345
+ return { depth: state.depth + opens - closes, bodyOpenerLine };
346
+ }
347
+
296
348
  // Walks `const { foo, bar: alias } = ...` patterns. Aliased names (the part after `:`) become the
297
349
  // local binding; defaults are stripped. Required because the naming rules check the local name only.
298
350
  function destructuredLocalNames(codeLine: string): string[] {
@@ -313,9 +365,11 @@ function destructuredLocalNames(codeLine: string): string[] {
313
365
  }
314
366
 
315
367
  // Thin wrapper that fills in `"declaration"` for the surface field. Same back-end as parameter
316
- // and destructure callers, which use their own surface labels.
317
- function pushShortVariableFinding(context: LineRuleContext, name: string): void {
318
- pushShortVariableAt(context.file, context.lineNumber, name, context.config, context.findings, "declaration");
368
+ // and destructure callers, which use their own surface labels. `loopBodyLineCount` is forwarded so
369
+ // the underlying rule can apply the for-of short-body exemption when the declaration came from a
370
+ // `for (const X of …)` head.
371
+ function pushShortVariableFinding(context: LineRuleContext, name: string, loopBodyLineCount?: number): void {
372
+ pushShortVariableAt(context.file, context.lineNumber, name, context.config, context.findings, "declaration", loopBodyLineCount);
319
373
  }
320
374
 
321
375
 
@@ -77,8 +77,14 @@ function isAcceptedBooleanStateName(name: string): boolean {
77
77
  /*
78
78
  * Allows the standard `i`, `j`, `k` loop counters and anything on `acceptedAbbreviations`. Reports
79
79
  * `naming.short-variable` for any other one or two character name as a stable advisory finding.
80
+ * `loopBodyLineCount` is the for-of caller's signal: when the binding came from a `for (const X of
81
+ * Y) { … }` head and the body spans ≤ 10 lines, the rule suppresses the finding because the name's
82
+ * lifetime is locally obvious. Other call sites (declaration, parameter, destructure) pass undefined.
80
83
  */
81
- export function pushShortVariableAt(file: SourceFile, line: number, name: string, config: Config, findings: Finding[], surface: NamingSurface): void {
84
+ export function pushShortVariableAt(file: SourceFile, line: number, name: string, config: Config, findings: Finding[], surface: NamingSurface, loopBodyLineCount?: number): void {
85
+ if (loopBodyLineCount !== undefined && loopBodyLineCount <= 10) {
86
+ return;
87
+ }
82
88
  if (name.length > 2 || ["i", "j", "k"].includes(name) || config.acceptedAbbreviations.has(name.toLowerCase())) {
83
89
  return;
84
90
  }
@@ -0,0 +1,129 @@
1
+ /*
2
+ * Shared pillar-row construction + grade helper. Lives in its own module so the text/markdown
3
+ * renderers (`report-renderers.ts`), the HTML renderer (`report-html.ts`), and the score builder
4
+ * (`scoring.ts`) can all source the same `buildPillarRows` and `grade` logic without forming a
5
+ * dependency cycle between the renderer modules. Every row this module emits feeds the cross-port
6
+ * `gruff.summary.v2` Pillars table contract, so the schema invariant - findings DESC, pillar ASC,
7
+ * and a clean A/100 fallback per pillar - must stay byte-stable across runs.
8
+ */
9
+ import { ruleDescriptors } from "./rules.ts";
10
+ import type { AnalysisReport, Finding, Pillar } from "./types.ts";
11
+
12
+ // Aggregated per-pillar row used by every renderer. `applicable` is derived from the rule
13
+ // catalogue rather than the live findings so the row set stays stable across runs (a pillar with
14
+ // zero findings today is still applicable). `grade` is derived from `score` via the shared
15
+ // `grade()` helper so historical pillar scores keep their existing grade letters.
16
+ interface PillarRow {
17
+ pillar: Pillar;
18
+ grade: string;
19
+ score: number;
20
+ penalty: number;
21
+ isApplicable: boolean;
22
+ findings: number;
23
+ advisory: number;
24
+ warning: number;
25
+ error: number;
26
+ }
27
+
28
+ // Per-pillar severity tally - one entry per pillar that produced at least one finding. Renderers
29
+ // see these counts indirectly through `buildPillarRows`; the type is exported only so other
30
+ // modules in this package can name it when consuming `countSeverityByPillar`.
31
+ interface PillarSeverityCounts {
32
+ advisory: number;
33
+ warning: number;
34
+ error: number;
35
+ }
36
+
37
+ /*
38
+ * Builds the canonical cross-port pillar row list shared by `gruff.summary.v2` text, JSON, and
39
+ * HTML renderers. The shape is intentionally a single deterministic list - one row per applicable
40
+ * pillar even when the run has zero findings - because cross-port consumers diff this output
41
+ * byte-for-byte and a missing row would read as a contract drift. Pillars without findings default
42
+ * to a clean A/100 row to preserve that invariant. Sort order is `findings DESC, pillar ASC` to
43
+ * keep the public Pillars-table contract deterministic across runs.
44
+ */
45
+ function buildPillarRows(report: AnalysisReport): PillarRow[] {
46
+ const scoreByPillar = new Map(report.score.pillars.map((entry) => [entry.pillar, entry] as const));
47
+ const severityByPillar = countSeverityByPillar(report.findings);
48
+ const rows: PillarRow[] = [...applicablePillarSet()].map((pillar) => buildPillarRow(pillar, scoreByPillar.get(pillar), severityByPillar.get(pillar)));
49
+ rows.sort(comparePillarRows);
50
+ return rows;
51
+ }
52
+
53
+ // Tallies advisory/warning/error counts per pillar from the live findings list. Returning a Map
54
+ // rather than mutating an accumulator keeps `buildPillarRows` linear and easy to read; this is
55
+ // the deterministic per-pillar tally feeding the public Pillars-table schema.
56
+ function countSeverityByPillar(findings: Finding[]): Map<Pillar, PillarSeverityCounts> {
57
+ const severityByPillar = new Map<Pillar, PillarSeverityCounts>();
58
+ for (const finding of findings) {
59
+ const counts = severityByPillar.get(finding.pillar) ?? { advisory: 0, warning: 0, error: 0 };
60
+ counts[finding.severity] += 1;
61
+ severityByPillar.set(finding.pillar, counts);
62
+ }
63
+ return severityByPillar;
64
+ }
65
+
66
+ /*
67
+ * Assembles one PillarRow from the optional analyser score entry and optional severity tally.
68
+ * Defaults preserve the clean A/100 row contract when a pillar produced no findings, keeping the
69
+ * `gruff.summary.v2` per-pillar shape deterministic across runs. Invariant: `findings` is derived
70
+ * from the severity tally (not `scoreEntry.findings`) so the row's total and its per-severity
71
+ * columns share a single source and can never disagree - the Finding list is the schema's single
72
+ * source of truth for what was actually reported in this run.
73
+ */
74
+ function buildPillarRow(pillar: Pillar, scoreEntry: AnalysisReport["score"]["pillars"][number] | undefined, severities: PillarSeverityCounts | undefined): PillarRow {
75
+ const score = scoreEntry?.score ?? 100;
76
+ const counts = severities ?? { advisory: 0, warning: 0, error: 0 };
77
+ return {
78
+ pillar,
79
+ grade: grade(score),
80
+ score,
81
+ penalty: scoreEntry?.penalty ?? 0,
82
+ isApplicable: true,
83
+ findings: counts.advisory + counts.warning + counts.error,
84
+ advisory: counts.advisory,
85
+ warning: counts.warning,
86
+ error: counts.error,
87
+ };
88
+ }
89
+
90
+ // Findings DESC, then pillar ASC. Extracted so the cross-port sort contract lives in one place and
91
+ // any tweak (e.g. a stable secondary key) only has to land here.
92
+ function comparePillarRows(leftRow: PillarRow, rightRow: PillarRow): number {
93
+ if (leftRow.findings !== rightRow.findings) {
94
+ return rightRow.findings - leftRow.findings;
95
+ }
96
+ return leftRow.pillar.localeCompare(rightRow.pillar);
97
+ }
98
+
99
+ // Pillar applicability is sourced from the rule catalogue: a pillar is applicable when at least
100
+ // one rule declares it. This keeps the cross-port `gruff.summary.v2` contract stable - every
101
+ // pillar that *could* fire shows up even when the current run produced zero findings for it.
102
+ function applicablePillarSet(): Set<Pillar> {
103
+ const pillars = new Set<Pillar>();
104
+ for (const descriptor of ruleDescriptors()) {
105
+ pillars.add(descriptor.pillar);
106
+ }
107
+ return pillars;
108
+ }
109
+
110
+ // Composite-score → letter grade conversion. 90/80/70/60 boundaries are part of the stable rule
111
+ // surface; changing them would shift every historical report grade and the headline on the dashboard.
112
+ function grade(score: number): string {
113
+ if (score >= 90) {
114
+ return "A";
115
+ }
116
+ if (score >= 80) {
117
+ return "B";
118
+ }
119
+ if (score >= 70) {
120
+ return "C";
121
+ }
122
+ if (score >= 60) {
123
+ return "D";
124
+ }
125
+ return "F";
126
+ }
127
+
128
+ export { buildPillarRows, grade };
129
+ export type { PillarRow, PillarSeverityCounts };