@blundergoat/gruff-ts 0.2.0 → 0.3.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/CHANGELOG.md +24 -0
- package/README.md +80 -12
- package/docs/README.md +2 -0
- package/docs/agent-hook.md +80 -0
- package/docs/ci-integration.md +16 -0
- package/docs/configuration.md +21 -2
- package/docs/output-formats.md +10 -0
- package/docs/philosophy.md +21 -0
- package/docs/releasing.md +5 -5
- package/docs/rules.md +24 -15
- package/package.json +5 -5
- package/scripts/bump-version.sh +1 -1
- package/src/analyser.ts +43 -30
- package/src/blocks.ts +20 -67
- package/src/changed-regions.ts +390 -0
- package/src/check-ignore.ts +49 -0
- package/src/class-rules.ts +80 -33
- package/src/cli-program.ts +105 -11
- package/src/comment-rules.ts +4 -0
- package/src/config-parse.ts +458 -0
- package/src/config-preservation.ts +1 -1
- package/src/config.ts +215 -460
- package/src/constants.ts +1 -1
- package/src/context-doc-rules.ts +2 -4
- package/src/dashboard.ts +7 -4
- package/src/discovery.ts +88 -32
- package/src/findings-helpers.ts +41 -5
- package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
- package/src/init-config.ts +3 -0
- package/src/naming-pushers.ts +35 -6
- package/src/profiles.ts +232 -0
- package/src/project-config-rules.ts +5 -5
- package/src/project-rules.ts +2 -1
- package/src/report-html.ts +1 -1
- package/src/report-renderers.ts +58 -0
- package/src/rule-list.ts +22 -1
- package/src/rules.ts +10 -10
- package/src/safety-rules.ts +16 -6
- package/src/scoring.ts +43 -5
- package/src/security-flow-rules.ts +533 -0
- package/src/sensitive-data-rules.ts +138 -2
- package/src/test-block-rules.ts +106 -15
- package/src/test-fixtures.ts +46 -8
- package/src/types.ts +78 -2
package/src/analyser.ts
CHANGED
|
@@ -5,11 +5,12 @@ import { existsSync, readFileSync } from "node:fs";
|
|
|
5
5
|
import { cwd } from "node:process";
|
|
6
6
|
import { basename, join } from "node:path";
|
|
7
7
|
import { applyBaseline, dedupeFindings, DEFAULT_BASELINE, recordHistory, writeBaseline } from "./baseline.ts";
|
|
8
|
+
import { changedRegionScope, filterChangedFindings } from "./changed-regions.ts";
|
|
8
9
|
import { loadConfig, optionNumber, ruleEnabled, ruleSeverity, threshold } from "./config.ts";
|
|
9
10
|
import { VERSION } from "./constants.ts";
|
|
10
11
|
import { absolutize, discoverSources, displayPath, type SourceFile } from "./discovery.ts";
|
|
11
12
|
import { makeFinding } from "./findings.ts";
|
|
12
|
-
import {
|
|
13
|
+
import { finding } from "./findings-helpers.ts";
|
|
13
14
|
import { commentRecords } from "./comment-scanner.ts";
|
|
14
15
|
import { analyseArchitectureRules, analyseTestAdequacyRules, buildProjectIndex, exportedSurface, isProductionSourcePath, isTestPath, type ProjectSource } from "./project-rules.ts";
|
|
15
16
|
import { analyseBlockRules, type BlockRuleContext, blockRuleContext, type FunctionBlock, functionBlocks, parameterNames } from "./blocks.ts";
|
|
@@ -18,6 +19,7 @@ import { analyseDeadCode, analyseUnreachable, analyseUnusedImports } from "./dea
|
|
|
18
19
|
import { analyseCommentQualityRules } from "./comment-rules.ts";
|
|
19
20
|
import { analyseDocRules, analyseFileOverviewDoc, analyseInterfaceDocs } from "./doc-rules.ts";
|
|
20
21
|
import { analyseLineRules } from "./line-rules.ts";
|
|
22
|
+
import { analyseSecurityFlow } from "./security-flow-rules.ts";
|
|
21
23
|
import { pushBooleanPrefixAt, pushIdentifierQualityAt, pushNegativeBooleanAt, pushShortVariableAt } from "./naming-pushers.ts";
|
|
22
24
|
import { analyseTestBlock } from "./test-block-rules.ts";
|
|
23
25
|
import { analyseGithubActionsRules } from "./github-actions-rules.ts";
|
|
@@ -25,7 +27,7 @@ import { analyseProjectConfigRules } from "./project-config-rules.ts";
|
|
|
25
27
|
import { scoreReport, summarize } from "./scoring.ts";
|
|
26
28
|
import { analyseSensitiveData } from "./sensitive-data-rules.ts";
|
|
27
29
|
import { maskNonCode, maskTemplateLiteralBodies, parseDiagnostics } from "./source-text.ts";
|
|
28
|
-
import type { AnalysisOptions, AnalysisReport, Config, Finding, RunDiagnostic } from "./types.ts";
|
|
30
|
+
import type { AnalysisOptions, AnalysisReport, Config, Finding, RunDiagnostic, SkippedPath } from "./types.ts";
|
|
29
31
|
|
|
30
32
|
/**
|
|
31
33
|
* Analyse the configured paths and return the stable gruff.analysis.v2 report contract.
|
|
@@ -38,7 +40,7 @@ export function analyse(options: AnalysisOptions): AnalysisReport {
|
|
|
38
40
|
const config = loadConfig(projectRoot, options);
|
|
39
41
|
const diagnostics: RunDiagnostic[] = [];
|
|
40
42
|
const discovery = discoverSources(projectRoot, options, config);
|
|
41
|
-
|
|
43
|
+
const changedScope = changedRegionScope(options);
|
|
42
44
|
pushMissingPathDiagnostics(discovery.missingPaths, diagnostics);
|
|
43
45
|
|
|
44
46
|
const scanned = scanDiscoveredSources(discovery.files, config, diagnostics);
|
|
@@ -47,12 +49,13 @@ export function analyse(options: AnalysisOptions): AnalysisReport {
|
|
|
47
49
|
...analyseProjectIndex(scanned.projectSources, config).filter((finding) => ruleEnabled(config, finding.ruleId)),
|
|
48
50
|
]);
|
|
49
51
|
const baselineResult = applyBaselineOptions(projectRoot, options, allFindings);
|
|
52
|
+
const changedResult = filterChangedFindings(baselineResult.findings, changedScope, scanned.sources);
|
|
50
53
|
|
|
51
54
|
if (options.historyFile) {
|
|
52
|
-
recordHistory(projectRoot, options.historyFile,
|
|
55
|
+
recordHistory(projectRoot, options.historyFile, changedResult.findings, diagnostics);
|
|
53
56
|
}
|
|
54
57
|
|
|
55
|
-
return buildAnalysisReport(projectRoot, options, discovery, diagnostics, baselineResult);
|
|
58
|
+
return buildAnalysisReport(projectRoot, options, discovery, diagnostics, { ...baselineResult, findings: changedResult.findings }, changedResult.suppressedCount);
|
|
56
59
|
}
|
|
57
60
|
|
|
58
61
|
function buildAnalysisReport(
|
|
@@ -61,6 +64,7 @@ function buildAnalysisReport(
|
|
|
61
64
|
discovery: DiscoverySummary,
|
|
62
65
|
diagnostics: RunDiagnostic[],
|
|
63
66
|
baselineResult: BaselineApplication,
|
|
67
|
+
suppressedCount?: number,
|
|
64
68
|
): AnalysisReport {
|
|
65
69
|
const findings = baselineResult.findings;
|
|
66
70
|
return {
|
|
@@ -76,10 +80,12 @@ function buildAnalysisReport(
|
|
|
76
80
|
paths: {
|
|
77
81
|
analysedFiles: discovery.files.length,
|
|
78
82
|
ignoredPaths: discovery.ignoredPaths,
|
|
83
|
+
skipped: discovery.skipped,
|
|
79
84
|
missingPaths: discovery.missingPaths,
|
|
80
85
|
},
|
|
81
86
|
diagnostics,
|
|
82
87
|
findings,
|
|
88
|
+
...(suppressedCount === undefined ? {} : { suppressedCount }),
|
|
83
89
|
score: scoreReport(findings),
|
|
84
90
|
...(baselineResult.baseline ? { baseline: baselineResult.baseline } : {}),
|
|
85
91
|
};
|
|
@@ -90,6 +96,7 @@ function buildAnalysisReport(
|
|
|
90
96
|
interface DiscoverySummary {
|
|
91
97
|
files: SourceFile[];
|
|
92
98
|
ignoredPaths: string[];
|
|
99
|
+
skipped: SkippedPath[];
|
|
93
100
|
missingPaths: string[];
|
|
94
101
|
}
|
|
95
102
|
|
|
@@ -98,6 +105,7 @@ interface DiscoverySummary {
|
|
|
98
105
|
interface SourceScanResult {
|
|
99
106
|
findings: Finding[];
|
|
100
107
|
projectSources: ProjectSource[];
|
|
108
|
+
sources: Map<string, { file: SourceFile; source: string }>;
|
|
101
109
|
}
|
|
102
110
|
|
|
103
111
|
/*
|
|
@@ -117,16 +125,6 @@ interface BaselineSelection {
|
|
|
117
125
|
source: string;
|
|
118
126
|
}
|
|
119
127
|
|
|
120
|
-
// Mutates `discovery.files` in place to retain only paths that changed against the diff base.
|
|
121
|
-
// Required when `--diff` is set so the scan does not waste time on unchanged files; no-op otherwise.
|
|
122
|
-
function filterDiffSources(discovery: DiscoverySummary, options: AnalysisOptions): void {
|
|
123
|
-
if (!options.diff) {
|
|
124
|
-
return;
|
|
125
|
-
}
|
|
126
|
-
const changed = changedFiles(options.diff);
|
|
127
|
-
discovery.files = discovery.files.filter((file) => changed.has(file.displayPath));
|
|
128
|
-
}
|
|
129
|
-
|
|
130
128
|
// Emits a `missing-path` diagnostic per path that the user requested but discovery could not
|
|
131
129
|
// resolve. Diagnostics force a non-zero exit (see `exitFor`); never throws - partial scans should still report.
|
|
132
130
|
function pushMissingPathDiagnostics(missingPaths: string[], diagnostics: RunDiagnostic[]): void {
|
|
@@ -147,9 +145,11 @@ function pushMissingPathDiagnostics(missingPaths: string[], diagnostics: RunDiag
|
|
|
147
145
|
function scanDiscoveredSources(files: SourceFile[], config: Config, diagnostics: RunDiagnostic[]): SourceScanResult {
|
|
148
146
|
const findings: Finding[] = [];
|
|
149
147
|
const projectSources: ProjectSource[] = [];
|
|
148
|
+
const sources = new Map<string, { file: SourceFile; source: string }>();
|
|
150
149
|
for (const file of files) {
|
|
151
150
|
try {
|
|
152
151
|
const source = readFileSync(file.absolutePath, "utf8");
|
|
152
|
+
sources.set(file.displayPath, { file, source });
|
|
153
153
|
if (shouldRetainProjectSource(file, source)) {
|
|
154
154
|
projectSources.push(projectSource(file, source));
|
|
155
155
|
}
|
|
@@ -164,7 +164,7 @@ function scanDiscoveredSources(files: SourceFile[], config: Config, diagnostics:
|
|
|
164
164
|
});
|
|
165
165
|
}
|
|
166
166
|
}
|
|
167
|
-
return { findings, projectSources };
|
|
167
|
+
return { findings, projectSources, sources };
|
|
168
168
|
}
|
|
169
169
|
|
|
170
170
|
// Retains production files for exported-surface checks, tests for central-suite import coverage,
|
|
@@ -289,18 +289,13 @@ function analyseProjectIndex(projectSources: ProjectSource[], config: Config): F
|
|
|
289
289
|
}
|
|
290
290
|
|
|
291
291
|
/*
|
|
292
|
-
* Per-file text-pillar rules run before script-only rules because config, workflow,
|
|
292
|
+
* Per-file text-pillar rules run before script-only rules because config, workflow, and
|
|
293
293
|
* secret surfaces are not TypeScript. The order is a stable baseline contract: reshuffling these
|
|
294
294
|
* checks changes same-line finding order for machine reports.
|
|
295
295
|
*/
|
|
296
296
|
function analyseTextRules(file: SourceFile, source: string, config: Config, findings: Finding[]): void {
|
|
297
297
|
const lines = lineCount(source);
|
|
298
|
-
if (
|
|
299
|
-
const stylesheetThreshold = threshold(config, "size.stylesheet-length", 1500);
|
|
300
|
-
if (lines > stylesheetThreshold) {
|
|
301
|
-
findings.push(finding({ ruleId: "size.stylesheet-length", message: `Stylesheet has ${lines} lines, above the threshold of ${stylesheetThreshold}.`, file, line: 1, severity: ruleSeverity(config, "size.stylesheet-length", "warning"), pillar: "size" }));
|
|
302
|
-
}
|
|
303
|
-
} else if (!isGeneratedLockfile(file.displayPath)) {
|
|
298
|
+
if (!isGeneratedLockfile(file.displayPath)) {
|
|
304
299
|
const fileLengthThreshold = threshold(config, "size.file-length", 750);
|
|
305
300
|
if (lines > fileLengthThreshold) {
|
|
306
301
|
findings.push(finding({ ruleId: "size.file-length", message: `File has ${lines} lines, above the threshold of ${fileLengthThreshold}.`, file, line: 1, severity: ruleSeverity(config, "size.file-length", "warning"), pillar: "size" }));
|
|
@@ -312,12 +307,6 @@ function analyseTextRules(file: SourceFile, source: string, config: Config, find
|
|
|
312
307
|
analyseProjectConfigRules(file, source, findings);
|
|
313
308
|
}
|
|
314
309
|
|
|
315
|
-
// CSS paths use a dedicated size rule (`size.stylesheet-length`) so stylesheets can have a
|
|
316
|
-
// different threshold and message from generic source files.
|
|
317
|
-
function isCssPath(displayPath: string): boolean {
|
|
318
|
-
return displayPath.toLowerCase().endsWith(".css");
|
|
319
|
-
}
|
|
320
|
-
|
|
321
310
|
// Counts the same logical lines as `source.split(/\r?\n/)` without allocating the full line array.
|
|
322
311
|
function lineCount(source: string): number {
|
|
323
312
|
let count = 1;
|
|
@@ -348,6 +337,7 @@ function analyseTypeScriptRules(file: SourceFile, source: string, config: Config
|
|
|
348
337
|
analyseBlocks(file, blocks, config, findings);
|
|
349
338
|
analyseUnusedImports(file, codeSource, source, findings);
|
|
350
339
|
analyseLineRules(file, source, codeSource, config, findings);
|
|
340
|
+
analyseSecurityFlow(file, source, findings);
|
|
351
341
|
analyseUnreachable(file, codeSource, findings);
|
|
352
342
|
analyseDocRules(file, source, codeSource, findings);
|
|
353
343
|
analyseInterfaceDocs(file, source, codeSource, findings);
|
|
@@ -384,7 +374,9 @@ function pushParameterNamingFindings(context: BlockRuleContext): void {
|
|
|
384
374
|
const line = context.block.declarationLine;
|
|
385
375
|
const params = parameterNames(context.block.params);
|
|
386
376
|
for (const parameter of params) {
|
|
387
|
-
|
|
377
|
+
if (!isComparatorShortParameter(context, params, parameter.name)) {
|
|
378
|
+
pushShortVariableAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
|
|
379
|
+
}
|
|
388
380
|
pushIdentifierQualityAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
|
|
389
381
|
if (isBooleanParameter(parameter.raw)) {
|
|
390
382
|
pushBooleanPrefixAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
|
|
@@ -396,6 +388,27 @@ function pushParameterNamingFindings(context: BlockRuleContext): void {
|
|
|
396
388
|
}
|
|
397
389
|
}
|
|
398
390
|
|
|
391
|
+
// `(a, b)` is a conventional comparator pair when the callable is explicitly shaped like sorting.
|
|
392
|
+
// Keep the exemption narrow so arbitrary two-parameter helpers still need domain names.
|
|
393
|
+
function isComparatorShortParameter(context: BlockRuleContext, params: Array<{ name: string; raw: string }>, name: string): boolean {
|
|
394
|
+
const names = params.map((parameter) => parameter.name);
|
|
395
|
+
if (names.length !== 2 || names[0] !== "a" || names[1] !== "b" || (name !== "a" && name !== "b")) {
|
|
396
|
+
return false;
|
|
397
|
+
}
|
|
398
|
+
return isComparatorCallable(context.block.name, context.block.codeBody);
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// Comparator-shaped callables are either named for ordering (`compare*`, `*Comparator`, `byName`) or
|
|
402
|
+
// their body performs the standard locale/numeric ordering expression over both parameters.
|
|
403
|
+
function isComparatorCallable(name: string, codeBody: string): boolean {
|
|
404
|
+
return (
|
|
405
|
+
/^(?:compare[A-Z0-9_]?|.*Comparator$|by[A-Z])/.test(name) ||
|
|
406
|
+
/\.localeCompare\s*\(/.test(codeBody) ||
|
|
407
|
+
/\breturn\s+a\b[\s\S]*?(?:-\s*b\b|[<>]=?\s*b\b)/.test(codeBody) ||
|
|
408
|
+
/\breturn\s+b\b[\s\S]*?(?:-\s*a\b|[<>]=?\s*a\b)/.test(codeBody)
|
|
409
|
+
);
|
|
410
|
+
}
|
|
411
|
+
|
|
399
412
|
// Generic-parameter rule is context-gated: only fires when the surrounding function is itself
|
|
400
413
|
// large enough to deserve attention (long, complex, or many parameters). Keeps noise down on
|
|
401
414
|
// trivial helpers that legitimately accept a `value` argument.
|
package/src/blocks.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Function-block parsing + per-block rule pass (size, complexity,
|
|
1
|
+
// Function-block parsing + per-block rule pass (size, complexity, doc,
|
|
2
2
|
// empty-function, unused-parameter, redundant-variable, useless-return) and the block-anchored
|
|
3
3
|
// finding factories. Pulls the parser and the rules that operate on parsed blocks out of cli.ts.
|
|
4
4
|
import { ruleSeverity, threshold } from "./config.ts";
|
|
@@ -9,8 +9,6 @@ import { escapeRegex, isGenericName, lineOffset } from "./findings-helpers.ts";
|
|
|
9
9
|
import { countMatches } from "./text-scans.ts";
|
|
10
10
|
import type { Config, Finding, Pillar, Severity } from "./types.ts";
|
|
11
11
|
|
|
12
|
-
const NPATH_CAP = 1_000_000;
|
|
13
|
-
|
|
14
12
|
// Parsed callable body shared by every block-level rule (size, complexity, naming, docs). The
|
|
15
13
|
// `body` / `codeBody` split (raw text vs. comment-masked) lets rules choose between literal
|
|
16
14
|
// inspection and code-only matching without re-running the masker.
|
|
@@ -65,13 +63,6 @@ export interface BlockRuleContext {
|
|
|
65
63
|
functionBody: string;
|
|
66
64
|
}
|
|
67
65
|
|
|
68
|
-
// NPath approximation result. `isCapped: true` signals the value hit `NPATH_CAP` and is a lower
|
|
69
|
-
// bound - the finding message uses this to mark capped values rather than implying precision.
|
|
70
|
-
export interface NpathResult {
|
|
71
|
-
value: number;
|
|
72
|
-
isCapped: boolean;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
66
|
// Input bundle for `blockFinding()`. The block reference replaces the explicit line: the builder
|
|
76
67
|
// reads `block.startLine` and `block.name` so the stable finding anchor and symbol metadata stay
|
|
77
68
|
// in sync with the parsed callable across every block-level rule.
|
|
@@ -100,7 +91,7 @@ export function blockFinding(args: BlockFindingArgs): Finding {
|
|
|
100
91
|
}
|
|
101
92
|
|
|
102
93
|
// Block-anchored variant that ships rule-specific metadata. Confidence defaults to "medium"
|
|
103
|
-
// because metadata-carrying rules (
|
|
94
|
+
// because metadata-carrying rules (e.g. test-quality magic-number) report measurements rather than
|
|
104
95
|
// definitive defects; the metadata payload is part of each rule's stable fingerprint contract.
|
|
105
96
|
export function blockFindingWithMetadata(args: BlockFindingWithMetadataArgs): Finding {
|
|
106
97
|
return makeFinding({ ruleId: args.ruleId, message: args.message, filePath: args.file.displayPath, line: args.block.startLine, severity: args.severity, pillar: args.pillar, confidence: "medium", symbol: args.block.name, metadata: args.metadata });
|
|
@@ -130,8 +121,6 @@ export function analyseBlockRules(context: BlockRuleContext): void {
|
|
|
130
121
|
pushParameterCountFinding(context);
|
|
131
122
|
pushCyclomaticFinding(context);
|
|
132
123
|
pushCognitiveFinding(context);
|
|
133
|
-
pushNpathFinding(context);
|
|
134
|
-
pushGodFunctionFinding(context);
|
|
135
124
|
pushGenericFunctionFinding(context);
|
|
136
125
|
pushMissingFunctionDocFinding(context);
|
|
137
126
|
pushEmptyFunctionFinding(context);
|
|
@@ -175,41 +164,6 @@ function pushCognitiveFinding(context: BlockRuleContext): void {
|
|
|
175
164
|
}
|
|
176
165
|
}
|
|
177
166
|
|
|
178
|
-
// Default threshold 200. NPath is the number of possible execution paths; the message marks
|
|
179
|
-
// `capped` when the calculation hit `NPATH_CAP` so reviewers know it's a lower bound. Reports `complexity.npath`.
|
|
180
|
-
function pushNpathFinding(context: BlockRuleContext): void {
|
|
181
|
-
const npath = approximateNpath(context.functionBody);
|
|
182
|
-
const npathThreshold = threshold(context.config, "complexity.npath", 200);
|
|
183
|
-
if (npath.value > npathThreshold) {
|
|
184
|
-
context.findings.push(npathFinding(context, npath, npathThreshold, ruleSeverity(context.config, "complexity.npath", "warning")));
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
/*
|
|
189
|
-
* Stable `complexity.npath` finding factory. `capped` and `cap` are surfaced in metadata so
|
|
190
|
-
* downstream tooling can distinguish "5000" from "≥ NPATH_CAP" - both would render as the same
|
|
191
|
-
* value otherwise.
|
|
192
|
-
*/
|
|
193
|
-
function npathFinding(context: BlockRuleContext, npath: NpathResult, thresholdValue: number, severity: Severity): Finding {
|
|
194
|
-
return blockFindingWithMetadata({
|
|
195
|
-
ruleId: "complexity.npath",
|
|
196
|
-
message: `Function \`${context.block.name}\` has approximate NPath complexity ${npath.value} above the threshold of ${thresholdValue} (capped at ${NPATH_CAP}).`,
|
|
197
|
-
file: context.file,
|
|
198
|
-
block: context.block,
|
|
199
|
-
severity,
|
|
200
|
-
pillar: "complexity",
|
|
201
|
-
metadata: { npath: npath.value, capped: npath.isCapped, cap: NPATH_CAP, threshold: thresholdValue },
|
|
202
|
-
});
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
// Combined-shape rule: long (>45 lines) AND complex (cyclomatic >10). Thresholds are hard-coded
|
|
206
|
-
// because "god function" is a design heuristic, not a per-rule tunable. Reports `design.god-function`.
|
|
207
|
-
function pushGodFunctionFinding(context: BlockRuleContext): void {
|
|
208
|
-
if (context.block.lineCount > 45 && context.cyclomatic > 10) {
|
|
209
|
-
context.findings.push(blockFinding({ ruleId: "design.god-function", message: `Function \`${context.block.name}\` is both long and complex.`, file: context.file, block: context.block, severity: "warning", pillar: "design" }));
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
|
|
213
167
|
// Names like `process`, `handle`, `run` from `config.bannedGenericNames`. The list is user-configurable;
|
|
214
168
|
// the rule body itself just consults the config. Reports `naming.generic-function`.
|
|
215
169
|
function pushGenericFunctionFinding(context: BlockRuleContext): void {
|
|
@@ -241,10 +195,28 @@ function pushEmptyFunctionFinding(context: BlockRuleContext): void {
|
|
|
241
195
|
return;
|
|
242
196
|
}
|
|
243
197
|
if (isEmptyFunctionBody(context.block.codeBody)) {
|
|
198
|
+
if (isDocumentedEmptyTestDouble(context)) {
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
244
201
|
context.findings.push(blockFinding({ ruleId: "waste.empty-function", message: `Function \`${context.block.name}\` has no executable body.`, file: context.file, block: context.block, severity: "advisory", pillar: "maintainability" }));
|
|
245
202
|
}
|
|
246
203
|
}
|
|
247
204
|
|
|
205
|
+
// Empty test doubles can be required by external interfaces when the body carries a rationale.
|
|
206
|
+
function isDocumentedEmptyTestDouble(context: BlockRuleContext): boolean {
|
|
207
|
+
return isTestOrFixturePath(context.file.displayPath) && hasEmptyTestDoubleRationale(context.block.body);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// Test and fixture paths are the only places where empty protocol stubs are normal.
|
|
211
|
+
function isTestOrFixturePath(path: string): boolean {
|
|
212
|
+
return /(?:^|\/)(?:__tests__|tests?|spec|__fixtures__|fixtures?|testdata)\//.test(path) || /\.(?:test|spec)\.[cm]?[tj]sx?$/.test(path);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Requires an explicit no-op/stub/fake rationale so real empty implementations still surface.
|
|
216
|
+
function hasEmptyTestDoubleRationale(source: string): boolean {
|
|
217
|
+
return /(?:\/\/|\/\*)/.test(source) && /\b(?:intentional no-op|test double|stub|fake|interface contract)\b/i.test(source);
|
|
218
|
+
}
|
|
219
|
+
|
|
248
220
|
// `_`-prefixed parameters are exempted (the standard "intentionally unused" convention).
|
|
249
221
|
// Reports `waste.unused-parameter` for parameter names that never appear in the callable body.
|
|
250
222
|
function pushUnusedParameterFindings(context: BlockRuleContext): void {
|
|
@@ -354,25 +326,6 @@ function pushUselessReturnFindings(context: BlockRuleContext): void {
|
|
|
354
326
|
}
|
|
355
327
|
}
|
|
356
328
|
|
|
357
|
-
// Approximation: each decision keyword (`if`, `case`, `catch`, loops) and short-circuit operator
|
|
358
|
-
// doubles the count. Optional chaining is stripped first so `a?.b` and `??` don't inflate the
|
|
359
|
-
// signal. Capped at `NPATH_CAP` - the `capped` flag tells callers to report the value as ≥, not =.
|
|
360
|
-
export function approximateNpath(source: string): NpathResult {
|
|
361
|
-
let pathCount = 1;
|
|
362
|
-
let isCapped = false;
|
|
363
|
-
const normalized = source.replace(/\?\./g, "").replace(/\?\?/g, "");
|
|
364
|
-
const decisionCount = countMatches(normalized, /\b(if|else if|case|catch|for|while)\b|\?|&&|\|\|/g);
|
|
365
|
-
for (let index = 0; index < decisionCount; index += 1) {
|
|
366
|
-
pathCount *= 2;
|
|
367
|
-
if (pathCount >= NPATH_CAP) {
|
|
368
|
-
pathCount = NPATH_CAP;
|
|
369
|
-
isCapped = true;
|
|
370
|
-
break;
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
return { value: pathCount, isCapped };
|
|
374
|
-
}
|
|
375
|
-
|
|
376
329
|
// Strips line and block comments before measuring - a body containing only documentation is still
|
|
377
330
|
// considered empty for the `waste.empty-function` check, since no executable statements run.
|
|
378
331
|
function isEmptyFunctionBody(source: string): boolean {
|