@blundergoat/gruff-ts 0.4.0 → 0.5.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 +41 -1
- package/README.md +16 -6
- package/SECURITY.md +2 -1
- package/docs/README.md +1 -4
- package/docs/agent-hook.md +14 -2
- package/docs/configuration.md +32 -1
- package/docs/dashboard.md +3 -3
- package/docs/reports-and-ci.md +15 -0
- package/docs/rules.md +35 -29
- package/package.json +1 -1
- package/src/analyser.ts +163 -53
- package/src/baseline.ts +39 -3
- package/src/blocks.ts +116 -77
- package/src/changed-regions.ts +59 -11
- package/src/class-rules.ts +226 -76
- package/src/cli-program.ts +61 -14
- package/src/cli.ts +1 -0
- package/src/comment-rules.ts +58 -13
- package/src/comment-scanner.ts +27 -0
- package/src/complexity-metrics.ts +244 -0
- package/src/config.ts +56 -16
- package/src/constants.ts +1 -1
- package/src/context-doc-rules.ts +9 -10
- package/src/discovery.ts +39 -19
- package/src/doc-rules.ts +22 -53
- package/src/findings-helpers.ts +127 -1
- package/src/findings.ts +4 -0
- package/src/fixture-purpose-rules.ts +39 -5
- package/src/github-actions-rules.ts +24 -1
- package/src/hook-contract.ts +85 -14
- package/src/init-config.ts +15 -5
- package/src/line-rules.ts +54 -5
- package/src/naming-pushers.ts +26 -5
- package/src/parsed-script.ts +652 -0
- package/src/process-exec-metadata.ts +16 -6
- package/src/profiles.ts +14 -0
- package/src/project-config-rules.ts +15 -10
- package/src/public-exports.ts +220 -0
- package/src/report-renderers.ts +55 -4
- package/src/rules.ts +11 -11
- package/src/scoring.ts +13 -4
- package/src/security-flow-rules.ts +169 -24
- package/src/sensitive-data-rules.ts +132 -78
- package/src/source-text.ts +4 -46
- package/src/test-block-rules.ts +118 -14
- package/src/test-fixtures.ts +4 -1
- package/src/text-scans.ts +8 -1
- package/src/types.ts +5 -3
package/src/comment-rules.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { existsSync } from "node:fs";
|
|
|
6
6
|
import { dirname as dirnamePath, resolve } from "node:path";
|
|
7
7
|
import { cwd } from "node:process";
|
|
8
8
|
import { type FunctionBlock } from "./blocks.ts";
|
|
9
|
-
import { type CommentRecord } from "./comment-scanner.ts";
|
|
9
|
+
import { combinedContextLineComment, type CommentRecord } from "./comment-scanner.ts";
|
|
10
10
|
import { type SourceFile } from "./discovery.ts";
|
|
11
11
|
import { type ExportedDeclaration, interfaceDeclarations } from "./doc-rules.ts";
|
|
12
12
|
import { type CommentedDeclaration, pushDeclarationContextFindings, pushFunctionContextFindings } from "./context-doc-rules.ts";
|
|
@@ -55,7 +55,7 @@ export function analyseCommentQualityRules(input: CommentQualityRuleInput): void
|
|
|
55
55
|
const lines = source.split(/\r?\n/);
|
|
56
56
|
const declarations = commentedDeclarations(blocks, interfaceDeclarations(source, codeSource));
|
|
57
57
|
|
|
58
|
-
analyseStandaloneCommentQuality(file, comments, DESCRIPTOR_IDS, CLI_FLAGS, findings);
|
|
58
|
+
analyseStandaloneCommentQuality(file, source, comments, DESCRIPTOR_IDS, CLI_FLAGS, findings);
|
|
59
59
|
analyseCommentedDeclarationQuality(file, lines, comments, declarations, findings);
|
|
60
60
|
analyseFunctionContextCommentQuality({ file, lines, comments, blocks, config, findings });
|
|
61
61
|
pushMagicThresholdFindings(file, lines, codeSource, comments, findings);
|
|
@@ -67,9 +67,9 @@ export function analyseCommentQualityRules(input: CommentQualityRuleInput): void
|
|
|
67
67
|
* stale CLI flag refs) that run on every comment regardless of whether it documents a declaration.
|
|
68
68
|
* Stable, deterministic emission order across the five sub-checks.
|
|
69
69
|
*/
|
|
70
|
-
function analyseStandaloneCommentQuality(file: SourceFile, comments: CommentRecord[], ruleIdSet: Set<string>, optionFlagSet: Set<string>, findings: Finding[]): void {
|
|
70
|
+
function analyseStandaloneCommentQuality(file: SourceFile, source: string, comments: CommentRecord[], ruleIdSet: Set<string>, optionFlagSet: Set<string>, findings: Finding[]): void {
|
|
71
71
|
for (const comment of comments) {
|
|
72
|
-
pushTodoWithoutTrackingFinding(file, comment, findings);
|
|
72
|
+
pushTodoWithoutTrackingFinding(file, source, comment, findings);
|
|
73
73
|
pushSuppressionWithoutRationaleFinding(file, comment, findings);
|
|
74
74
|
pushStaleFileReferenceFindings(file, comment, findings);
|
|
75
75
|
pushStaleRuleReferenceFindings(file, comment, ruleIdSet, findings);
|
|
@@ -91,7 +91,7 @@ function analyseCommentedDeclarationQuality(file: SourceFile, lines: string[], c
|
|
|
91
91
|
pushStaleDeclarationCommentFinding(file, comment, declaration, findings);
|
|
92
92
|
pushRestatingSignatureCommentFinding(file, comment, declaration, findings);
|
|
93
93
|
if (!isRestatingSignatureComment(comment.text, declaration.name, declaration.kind)) {
|
|
94
|
-
pushDeclarationContextFindings(file, lines, declaration, comment, findings);
|
|
94
|
+
pushDeclarationContextFindings(file, lines, declaration, combinedContextLineComment(comments, comment), findings);
|
|
95
95
|
}
|
|
96
96
|
}
|
|
97
97
|
}
|
|
@@ -105,7 +105,7 @@ function analyseFunctionContextCommentQuality(input: FunctionContextCommentQuali
|
|
|
105
105
|
if (!comment || isRestatingSignatureComment(comment.text, block.name, "function")) {
|
|
106
106
|
continue;
|
|
107
107
|
}
|
|
108
|
-
pushFunctionContextFindings(file, block, comment, config, findings);
|
|
108
|
+
pushFunctionContextFindings(file, block, combinedContextLineComment(comments, comment), config, findings);
|
|
109
109
|
}
|
|
110
110
|
}
|
|
111
111
|
|
|
@@ -125,8 +125,8 @@ function commentedDeclarations(blocks: FunctionBlock[], interfaces: ExportedDecl
|
|
|
125
125
|
* preserved in stable metadata so consumers can group by marker kind. Reports the stable
|
|
126
126
|
* untracked-task-marker finding when no tracking reference is attached.
|
|
127
127
|
*/
|
|
128
|
-
function pushTodoWithoutTrackingFinding(file: SourceFile, comment: CommentRecord, findings: Finding[]): void {
|
|
129
|
-
const marker = todoMarker(comment
|
|
128
|
+
function pushTodoWithoutTrackingFinding(file: SourceFile, source: string, comment: CommentRecord, findings: Finding[]): void {
|
|
129
|
+
const marker = todoMarker(source, comment);
|
|
130
130
|
if (!marker || hasTodoTracking(comment.text)) {
|
|
131
131
|
return;
|
|
132
132
|
}
|
|
@@ -146,9 +146,52 @@ function pushTodoWithoutTrackingFinding(file: SourceFile, comment: CommentRecord
|
|
|
146
146
|
}
|
|
147
147
|
|
|
148
148
|
// Four canonical task-marker words, returned in uppercase so the finding message reads consistently
|
|
149
|
-
// regardless of how the maintainer wrote them.
|
|
150
|
-
|
|
151
|
-
|
|
149
|
+
// regardless of how the maintainer wrote them. A marker must INTRODUCE a comment body line - prose
|
|
150
|
+
// that merely mentions a marker word (quoted, backticked, or mid-sentence) stays quiet.
|
|
151
|
+
function todoMarker(source: string, comment: CommentRecord): string | undefined {
|
|
152
|
+
for (const line of commentBodyLines(source, comment)) {
|
|
153
|
+
const marker = leadingTodoMarker(line);
|
|
154
|
+
if (marker) {
|
|
155
|
+
return marker;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return undefined;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// One body line per physical comment line: the trimmed `//` text, or each block-comment line with
|
|
162
|
+
// its `*` decoration stripped. Lines inside ``` fences are dropped so marker examples shown in
|
|
163
|
+
// doc comments cannot become findings.
|
|
164
|
+
function commentBodyLines(source: string, comment: CommentRecord): string[] {
|
|
165
|
+
if (comment.kind === "line") {
|
|
166
|
+
return [comment.text];
|
|
167
|
+
}
|
|
168
|
+
const body = source.slice(comment.startIndex + 2, Math.max(comment.startIndex + 2, comment.endIndex - 1));
|
|
169
|
+
const lines: string[] = [];
|
|
170
|
+
let isInsideFence = false;
|
|
171
|
+
for (const rawLine of body.split(/\r?\n/)) {
|
|
172
|
+
const line = rawLine.replace(/^[ \t]*\*[ \t]?/, "").trim();
|
|
173
|
+
if (line.startsWith("```")) {
|
|
174
|
+
isInsideFence = !isInsideFence;
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
if (!isInsideFence) {
|
|
178
|
+
lines.push(line);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return lines;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Leading-marker grammar: optional list bullet, the marker word, then a delimiter real markers use
|
|
185
|
+
// (":", "(", "-", whitespace, or end of line). Any other next character - a quote, slash, or
|
|
186
|
+
// backtick - means the line talks ABOUT a marker instead of being one.
|
|
187
|
+
function leadingTodoMarker(line: string): string | undefined {
|
|
188
|
+
const match = line.match(/^(?:(?:[-*>]|\d+[.)])\s+)?(TODO|FIXME|HACK|XXX)\b(.*)$/i);
|
|
189
|
+
const marker = match?.[1];
|
|
190
|
+
if (!marker) {
|
|
191
|
+
return undefined;
|
|
192
|
+
}
|
|
193
|
+
const rest = match?.[2] ?? "";
|
|
194
|
+
return rest === "" || /^[\s:(-]/.test(rest) ? marker.toUpperCase() : undefined;
|
|
152
195
|
}
|
|
153
196
|
|
|
154
197
|
const TODO_TRACKING_PATTERNS = [
|
|
@@ -296,6 +339,7 @@ function knownCliFlags(): Set<string> {
|
|
|
296
339
|
"--changed-ranges",
|
|
297
340
|
"--changed-scope",
|
|
298
341
|
"--fail-on",
|
|
342
|
+
"--fail-on-diagnostics",
|
|
299
343
|
"--force",
|
|
300
344
|
"--format",
|
|
301
345
|
"--generate-baseline",
|
|
@@ -487,14 +531,15 @@ function isCommonSafeNumber(numericLiteral: string): boolean {
|
|
|
487
531
|
}
|
|
488
532
|
|
|
489
533
|
// Two acceptable positions for the explanatory comment: same line as the constant, or directly
|
|
490
|
-
// above with a blank-line gap. Mirrors `hasFixturePurposeComment` adjacency rules
|
|
534
|
+
// above with a blank-line gap. Mirrors `hasFixturePurposeComment` adjacency rules, including
|
|
535
|
+
// reading a stacked `//` header as one comment so rationale on an earlier line counts.
|
|
491
536
|
function hasNearbyThresholdRationale(lines: string[], comments: CommentRecord[], line: number): boolean {
|
|
492
537
|
const sameLine = comments.find((comment) => comment.line <= line && comment.endLine >= line);
|
|
493
538
|
if (sameLine && hasThresholdRationaleMarker(sameLine.text)) {
|
|
494
539
|
return true;
|
|
495
540
|
}
|
|
496
541
|
const leading = leadingCommentForLine(lines, comments, line);
|
|
497
|
-
return Boolean(leading && hasThresholdRationaleMarker(leading.text));
|
|
542
|
+
return Boolean(leading && hasThresholdRationaleMarker(combinedContextLineComment(comments, leading).text));
|
|
498
543
|
}
|
|
499
544
|
|
|
500
545
|
// Vocabulary used by the magic-threshold rule. A numeric constant followed by a comment containing
|
package/src/comment-scanner.ts
CHANGED
|
@@ -281,6 +281,33 @@ function normalizedBlockCommentText(text: string): string {
|
|
|
281
281
|
.trim();
|
|
282
282
|
}
|
|
283
283
|
|
|
284
|
+
// Reads a contiguous `//` run as one maintainer comment while keeping the final record's anchor.
|
|
285
|
+
// Rules that accept a leading comment use this so a purpose or context statement on an earlier
|
|
286
|
+
// line of a stacked header still counts; block comments pass through unchanged.
|
|
287
|
+
export function combinedContextLineComment(comments: CommentRecord[], finalComment: CommentRecord): CommentRecord {
|
|
288
|
+
if (finalComment.kind !== "line") {
|
|
289
|
+
return finalComment;
|
|
290
|
+
}
|
|
291
|
+
const finalIndex = comments.indexOf(finalComment);
|
|
292
|
+
if (finalIndex < 0) {
|
|
293
|
+
return finalComment;
|
|
294
|
+
}
|
|
295
|
+
let firstIndex = finalIndex;
|
|
296
|
+
while (firstIndex > 0) {
|
|
297
|
+
const previous = comments[firstIndex - 1];
|
|
298
|
+
const current = comments[firstIndex];
|
|
299
|
+
if (!previous || !current || previous.kind !== "line" || previous.endLine + 1 !== current.line) {
|
|
300
|
+
break;
|
|
301
|
+
}
|
|
302
|
+
firstIndex -= 1;
|
|
303
|
+
}
|
|
304
|
+
const text = comments
|
|
305
|
+
.slice(firstIndex, finalIndex + 1)
|
|
306
|
+
.map((comment) => comment.text)
|
|
307
|
+
.join(" ");
|
|
308
|
+
return { ...finalComment, text };
|
|
309
|
+
}
|
|
310
|
+
|
|
284
311
|
// String-input wrapper around `hasLeadingCommentBeforeLines`. Keeps call sites that already hold
|
|
285
312
|
// a split line array from re-splitting on every lookup.
|
|
286
313
|
export function hasLeadingCommentBeforeLine(source: string, line: number): boolean {
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
// Syntax-aware complexity measurement for each callable discovered by the shared script parse.
|
|
2
|
+
// It turns real decision nodes into the values shown in CLI and JSON findings while leaving
|
|
3
|
+
// defaulting, optional access, presentation objects, and ordinary blocks out of the score.
|
|
4
|
+
// Nested callable ownership follows the same M07 block inventory, so every body counts once.
|
|
5
|
+
import { createRequire } from "node:module";
|
|
6
|
+
|
|
7
|
+
// TypeScript is CommonJS at runtime; this module only walks nodes from the existing shared parse.
|
|
8
|
+
const require = createRequire(import.meta.url);
|
|
9
|
+
const typescriptSyntax = require("typescript") as typeof import("typescript");
|
|
10
|
+
|
|
11
|
+
// Syntax node identity links measurements to the callable inventory from the shared parser.
|
|
12
|
+
// Nodes never leave the internal scan pipeline or appear in JSON and UI report payloads.
|
|
13
|
+
// Equality is object identity within one parse, which preserves single ownership.
|
|
14
|
+
type TypeScriptNode = import("typescript").Node;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Stable per-kind decision counts attached to complexity findings for report consumers.
|
|
18
|
+
* Every key is always present, including zero values, so JSON comparisons stay deterministic.
|
|
19
|
+
* `maxNesting` describes control-flow nesting only, never object or callback braces.
|
|
20
|
+
*/
|
|
21
|
+
export interface ComplexityBreakdown {
|
|
22
|
+
if: number;
|
|
23
|
+
loop: number;
|
|
24
|
+
catch: number;
|
|
25
|
+
case: number;
|
|
26
|
+
ternary: number;
|
|
27
|
+
logicalAnd: number;
|
|
28
|
+
logicalOr: number;
|
|
29
|
+
maxNesting: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* One callable's shared complexity result used by both findings and documentation checks.
|
|
34
|
+
* Cyclomatic starts at one; cognitive adds maximum control-flow nesting to that value.
|
|
35
|
+
* A CLI user reaches these measurements when a configured threshold produces a finding.
|
|
36
|
+
*/
|
|
37
|
+
export interface ComplexityMetrics {
|
|
38
|
+
cyclomatic: number;
|
|
39
|
+
cognitive: number;
|
|
40
|
+
maximumControlFlowNesting: number;
|
|
41
|
+
breakdown: ComplexityBreakdown;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Mutable counters used only during one syntax-tree walk for one reported callable.
|
|
46
|
+
* The accumulator is converted to an immutable report-shaped result after traversal.
|
|
47
|
+
* No state survives between files or CLI scans.
|
|
48
|
+
*/
|
|
49
|
+
interface ComplexityAccumulator {
|
|
50
|
+
ifCount: number;
|
|
51
|
+
loopCount: number;
|
|
52
|
+
catchCount: number;
|
|
53
|
+
caseCount: number;
|
|
54
|
+
ternaryCount: number;
|
|
55
|
+
logicalAndCount: number;
|
|
56
|
+
logicalOrCount: number;
|
|
57
|
+
maximumControlFlowNesting: number;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Context threaded through the recursive walk so nested callable bodies keep one owner.
|
|
62
|
+
* `callableNode` is the block being measured; `ownedCallableNodes` are sibling report blocks.
|
|
63
|
+
* The shared accumulator becomes metadata visible to report and hook consumers.
|
|
64
|
+
*/
|
|
65
|
+
interface ComplexityWalkContext {
|
|
66
|
+
callableNode: TypeScriptNode;
|
|
67
|
+
ownedCallableNodes: ReadonlySet<TypeScriptNode>;
|
|
68
|
+
accumulator: ComplexityAccumulator;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Returns the base measurement used only when a caller has no parsed script, such as a legacy span probe.
|
|
72
|
+
export function baseComplexityMetrics(): ComplexityMetrics {
|
|
73
|
+
return {
|
|
74
|
+
cyclomatic: 1,
|
|
75
|
+
cognitive: 1,
|
|
76
|
+
maximumControlFlowNesting: 0,
|
|
77
|
+
breakdown: emptyBreakdown(),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Measures one parsed callable without reparsing the source or walking another reported callable.
|
|
82
|
+
// It reports one deterministic breakdown to CLI complexity findings and documentation checks.
|
|
83
|
+
export function complexityMetrics(callableNode: TypeScriptNode, ownedCallableNodes: ReadonlySet<TypeScriptNode>): ComplexityMetrics {
|
|
84
|
+
const accumulator: ComplexityAccumulator = {
|
|
85
|
+
ifCount: 0,
|
|
86
|
+
loopCount: 0,
|
|
87
|
+
catchCount: 0,
|
|
88
|
+
caseCount: 0,
|
|
89
|
+
ternaryCount: 0,
|
|
90
|
+
logicalAndCount: 0,
|
|
91
|
+
logicalOrCount: 0,
|
|
92
|
+
maximumControlFlowNesting: 0,
|
|
93
|
+
};
|
|
94
|
+
const context: ComplexityWalkContext = { callableNode, ownedCallableNodes, accumulator };
|
|
95
|
+
// The root callable owns its parameters and body; separately reported nested callables are pruned below.
|
|
96
|
+
callableNode.forEachChild((child) => walkComplexityNode(child, 0, context));
|
|
97
|
+
const decisionCount = accumulator.ifCount
|
|
98
|
+
+ accumulator.loopCount
|
|
99
|
+
+ accumulator.catchCount
|
|
100
|
+
+ accumulator.caseCount
|
|
101
|
+
+ accumulator.ternaryCount
|
|
102
|
+
+ accumulator.logicalAndCount
|
|
103
|
+
+ accumulator.logicalOrCount;
|
|
104
|
+
const cyclomatic = decisionCount + 1;
|
|
105
|
+
const breakdown: ComplexityBreakdown = {
|
|
106
|
+
if: accumulator.ifCount,
|
|
107
|
+
loop: accumulator.loopCount,
|
|
108
|
+
catch: accumulator.catchCount,
|
|
109
|
+
case: accumulator.caseCount,
|
|
110
|
+
ternary: accumulator.ternaryCount,
|
|
111
|
+
logicalAnd: accumulator.logicalAndCount,
|
|
112
|
+
logicalOr: accumulator.logicalOrCount,
|
|
113
|
+
maxNesting: accumulator.maximumControlFlowNesting,
|
|
114
|
+
};
|
|
115
|
+
return {
|
|
116
|
+
cyclomatic,
|
|
117
|
+
cognitive: cyclomatic + accumulator.maximumControlFlowNesting,
|
|
118
|
+
maximumControlFlowNesting: accumulator.maximumControlFlowNesting,
|
|
119
|
+
breakdown,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Walks one node using the counting law, carrying only control-flow depth between syntax children.
|
|
124
|
+
function walkComplexityNode(node: TypeScriptNode, controlFlowDepth: number, context: ComplexityWalkContext): void {
|
|
125
|
+
// When M07 reports a nested callable separately, its body belongs to that report block, not this parent.
|
|
126
|
+
if (node !== context.callableNode && context.ownedCallableNodes.has(node)) {
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
// A user's if statement adds one decision and one control-flow nesting level.
|
|
130
|
+
if (typescriptSyntax.isIfStatement(node)) {
|
|
131
|
+
walkIfStatement(node, controlFlowDepth, context);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
// Every loop form adds one decision and one control-flow nesting level.
|
|
135
|
+
if (isLoopStatement(node)) {
|
|
136
|
+
context.accumulator.loopCount += 1;
|
|
137
|
+
walkNestedControlFlow(node, controlFlowDepth, context);
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
// A switch adds nesting for its choices but no decision beyond its non-default cases.
|
|
141
|
+
if (typescriptSyntax.isSwitchStatement(node)) {
|
|
142
|
+
walkNestedControlFlow(node, controlFlowDepth, context);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
// Catch represents one recovery path and one control-flow nesting level.
|
|
146
|
+
if (typescriptSyntax.isCatchClause(node)) {
|
|
147
|
+
context.accumulator.catchCount += 1;
|
|
148
|
+
walkNestedControlFlow(node, controlFlowDepth, context);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
// Each explicit case adds a decision; default and the case wrapper add no nesting.
|
|
152
|
+
if (typescriptSyntax.isCaseClause(node)) {
|
|
153
|
+
context.accumulator.caseCount += 1;
|
|
154
|
+
walkChildrenAtDepth(node, controlFlowDepth, context);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
// A conditional expression adds one decision and one control-flow nesting level.
|
|
158
|
+
if (typescriptSyntax.isConditionalExpression(node)) {
|
|
159
|
+
context.accumulator.ternaryCount += 1;
|
|
160
|
+
walkNestedControlFlow(node, controlFlowDepth, context);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
// Logical operators count as decisions but do not deepen control flow.
|
|
164
|
+
if (typescriptSyntax.isBinaryExpression(node)) {
|
|
165
|
+
walkBinaryExpression(node, controlFlowDepth, context);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
// Optional access, nullish coalescing, ordinary blocks, and presentation syntax keep the same depth.
|
|
169
|
+
walkChildrenAtDepth(node, controlFlowDepth, context);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Counts an if and keeps an `else if` at peer depth while ordinary else bodies stay nested.
|
|
173
|
+
function walkIfStatement(node: import("typescript").IfStatement, controlFlowDepth: number, context: ComplexityWalkContext): void {
|
|
174
|
+
context.accumulator.ifCount += 1;
|
|
175
|
+
const nestedDepth = enterControlFlow(controlFlowDepth, context.accumulator);
|
|
176
|
+
walkComplexityNode(node.expression, nestedDepth, context);
|
|
177
|
+
walkComplexityNode(node.thenStatement, nestedDepth, context);
|
|
178
|
+
// A source without an else branch has no further control-flow subtree for the user to review.
|
|
179
|
+
if (!node.elseStatement) {
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
// An `else if` is another peer decision, not an extra nesting layer created by AST parentage.
|
|
183
|
+
if (typescriptSyntax.isIfStatement(node.elseStatement)) {
|
|
184
|
+
walkComplexityNode(node.elseStatement, controlFlowDepth, context);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
walkComplexityNode(node.elseStatement, nestedDepth, context);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Counts each logical binary node once; all other binary operators, including `??`, stay neutral.
|
|
191
|
+
function walkBinaryExpression(node: import("typescript").BinaryExpression, controlFlowDepth: number, context: ComplexityWalkContext): void {
|
|
192
|
+
// A user's logical AND adds one decision without changing nesting depth.
|
|
193
|
+
if (node.operatorToken.kind === typescriptSyntax.SyntaxKind.AmpersandAmpersandToken) {
|
|
194
|
+
context.accumulator.logicalAndCount += 1;
|
|
195
|
+
}
|
|
196
|
+
// A user's logical OR adds one decision without changing nesting depth.
|
|
197
|
+
if (node.operatorToken.kind === typescriptSyntax.SyntaxKind.BarBarToken) {
|
|
198
|
+
context.accumulator.logicalOrCount += 1;
|
|
199
|
+
}
|
|
200
|
+
walkChildrenAtDepth(node, controlFlowDepth, context);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Enters one control construct, records the deepest user-visible level, and walks its children there.
|
|
204
|
+
function walkNestedControlFlow(node: TypeScriptNode, controlFlowDepth: number, context: ComplexityWalkContext): void {
|
|
205
|
+
const nestedDepth = enterControlFlow(controlFlowDepth, context.accumulator);
|
|
206
|
+
walkChildrenAtDepth(node, nestedDepth, context);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Visits every syntax child at an unchanged depth so punctuation and ordinary braces stay free.
|
|
210
|
+
function walkChildrenAtDepth(node: TypeScriptNode, controlFlowDepth: number, context: ComplexityWalkContext): void {
|
|
211
|
+
// Every child stays with the nearest reported callable unless the ownership guard prunes it.
|
|
212
|
+
node.forEachChild((child) => walkComplexityNode(child, controlFlowDepth, context));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Advances and records control-flow depth for an if, loop, switch, catch, or ternary.
|
|
216
|
+
function enterControlFlow(controlFlowDepth: number, accumulator: ComplexityAccumulator): number {
|
|
217
|
+
const nestedDepth = controlFlowDepth + 1;
|
|
218
|
+
accumulator.maximumControlFlowNesting = Math.max(accumulator.maximumControlFlowNesting, nestedDepth);
|
|
219
|
+
return nestedDepth;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Recognizes every loop syntax counted by the public complexity policy.
|
|
223
|
+
function isLoopStatement(node: TypeScriptNode): boolean {
|
|
224
|
+
return typescriptSyntax.isForStatement(node)
|
|
225
|
+
|| typescriptSyntax.isForInStatement(node)
|
|
226
|
+
|| typescriptSyntax.isForOfStatement(node)
|
|
227
|
+
|| typescriptSyntax.isWhileStatement(node)
|
|
228
|
+
|| typescriptSyntax.isDoStatement(node);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// Builds the fixed zero-valued metadata shape used when a source has no decisions.
|
|
232
|
+
// It never throws because no source or parser state is read here.
|
|
233
|
+
function emptyBreakdown(): ComplexityBreakdown {
|
|
234
|
+
return {
|
|
235
|
+
if: 0,
|
|
236
|
+
loop: 0,
|
|
237
|
+
catch: 0,
|
|
238
|
+
case: 0,
|
|
239
|
+
ternary: 0,
|
|
240
|
+
logicalAnd: 0,
|
|
241
|
+
logicalOr: 0,
|
|
242
|
+
maxNesting: 0,
|
|
243
|
+
};
|
|
244
|
+
}
|
package/src/config.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { existsSync } from "node:fs";
|
|
|
4
4
|
import { dirname, isAbsolute, join } from "node:path";
|
|
5
5
|
import { arrayValue, isString, objectValue, parseConfigFile, SUGGEST_EDIT_CONFIG, SUGGEST_INIT_FORCE } from "./config-parse.ts";
|
|
6
6
|
import { ConfigLoadError } from "./config-load-error.ts";
|
|
7
|
-
import { BUILT_IN_PROFILES, builtInProfileNames, DEFAULT_PROFILE_NAME, isKnownRuleId } from "./profiles.ts";
|
|
7
|
+
import { BUILT_IN_PROFILES, builtInProfileNames, DEFAULT_PROFILE_NAME, isKnownRuleId, ruleOptionKeys } from "./profiles.ts";
|
|
8
8
|
import type { AnalysisOptions, Config, FailThreshold, InlineProfileSpec, MinimumSeverityCommand, ProfileDefinition, ProfileRuleSetting, ProfileSpec, Severity } from "./types.ts";
|
|
9
9
|
|
|
10
10
|
type RuleOverride = Config["rules"] extends Map<string, infer RuleOverrideValue> ? RuleOverrideValue : never;
|
|
@@ -19,10 +19,12 @@ function defaultConfig(): Config {
|
|
|
19
19
|
return {
|
|
20
20
|
schemaVersion: "gruff-ts.config.v0.1",
|
|
21
21
|
ignoredPaths: [],
|
|
22
|
-
acceptedAbbreviations: new Set(["age", "app", "
|
|
22
|
+
acceptedAbbreviations: new Set(["age", "app", "db", "fs", "id", "io", "key", "log", "max", "min", "now", "raw", "rx", "tx", "ui", "url"]),
|
|
23
23
|
secretPreviews: new Set(),
|
|
24
24
|
bannedGenericNames: new Set(["process", "handle", "doit", "run", "execute", "manage"]),
|
|
25
25
|
acceptedBooleanNames: new Set(["all", "apply", "check", "dev", "enabled", "force", "fresh", "harness", "json", "ok", "verbose", "yes"]),
|
|
26
|
+
acceptedClassFilePairs: new Set(),
|
|
27
|
+
acceptedCasingPairs: new Set(),
|
|
26
28
|
booleanPrefixes: new Set(["is", "has", "can", "should", "does", "did", "was", "will", "may", "in", "scan", "supports", "requires", "allow", "check", "enable", "exclude", "include", "omit", "skip", "with", "without"]),
|
|
27
29
|
hungarianPrefixes: new Set(["str", "obj", "arr", "bool", "int", "num"]),
|
|
28
30
|
placeholderNames: new Set(["foo", "bar", "baz", "tmp", "temp", "thing", "stuff", "data", "value", "item"]),
|
|
@@ -240,13 +242,14 @@ function inlineSpecFromObject(block: Record<string, unknown>): InlineProfileSpec
|
|
|
240
242
|
}
|
|
241
243
|
|
|
242
244
|
// Builds the per-rule settings map for an inline profile, reusing the same validation as the
|
|
243
|
-
// top-level `rules:` block (`ruleConfigValue` throws on
|
|
245
|
+
// top-level `rules:` block (`ruleConfigValue` throws on unknown/malformed fields; rule ids are
|
|
246
|
+
// validated by the profile resolver so direct and profile rules reject identically).
|
|
244
247
|
function profileRulesFromBlock(rulesBlock: Record<string, unknown>): Record<string, ProfileRuleSetting> {
|
|
245
248
|
const rules: Record<string, ProfileRuleSetting> = {};
|
|
246
249
|
for (const [ruleId, value] of Object.entries(rulesBlock)) {
|
|
247
250
|
const rule = objectValue(value);
|
|
248
251
|
if (rule) {
|
|
249
|
-
rules[ruleId] = ruleConfigValue(rule);
|
|
252
|
+
rules[ruleId] = ruleConfigValue(ruleId, rule);
|
|
250
253
|
}
|
|
251
254
|
}
|
|
252
255
|
return rules;
|
|
@@ -347,7 +350,7 @@ function applyPathConfig(config: Config, raw: Record<string, unknown>): void {
|
|
|
347
350
|
}
|
|
348
351
|
|
|
349
352
|
// The allowlist section is the main lever users have for tuning gruff to their conventions.
|
|
350
|
-
// `acceptedAbbreviations` and the
|
|
353
|
+
// `acceptedAbbreviations` and the naming lists are lowercased on import so case-insensitive
|
|
351
354
|
// matching is the stable behaviour regardless of how users write entries.
|
|
352
355
|
function applyAllowlistConfig(config: Config, raw: Record<string, unknown>): void {
|
|
353
356
|
const allowlists = objectValue(raw.allowlists);
|
|
@@ -358,6 +361,8 @@ function applyAllowlistConfig(config: Config, raw: Record<string, unknown>): voi
|
|
|
358
361
|
config.secretPreviews = new Set(arrayValue(allowlists?.secretPreviews).filter(isString));
|
|
359
362
|
applyNamingAllowlist(config, allowlists, "bannedGenericNames");
|
|
360
363
|
applyNamingAllowlist(config, allowlists, "acceptedBooleanNames");
|
|
364
|
+
applyNamingAllowlist(config, allowlists, "acceptedClassFilePairs");
|
|
365
|
+
applyNamingAllowlist(config, allowlists, "acceptedCasingPairs");
|
|
361
366
|
applyNamingAllowlist(config, allowlists, "booleanPrefixes");
|
|
362
367
|
applyNamingAllowlist(config, allowlists, "hungarianPrefixes");
|
|
363
368
|
applyNamingAllowlist(config, allowlists, "placeholderNames");
|
|
@@ -367,7 +372,7 @@ function applyAllowlistConfig(config: Config, raw: Record<string, unknown>): voi
|
|
|
367
372
|
|
|
368
373
|
// Replaces the entire list when the user provides that key - there is no merge with defaults.
|
|
369
374
|
// The "set the whole list" semantic is intentional so users can deliberately empty a list.
|
|
370
|
-
function applyNamingAllowlist(config: Config, allowlists: Record<string, unknown> | undefined, key: "bannedGenericNames" | "acceptedBooleanNames" | "booleanPrefixes" | "hungarianPrefixes" | "placeholderNames" | "negativeBooleanAllowed" | "knownAcronyms"): void {
|
|
375
|
+
function applyNamingAllowlist(config: Config, allowlists: Record<string, unknown> | undefined, key: "bannedGenericNames" | "acceptedBooleanNames" | "acceptedClassFilePairs" | "acceptedCasingPairs" | "booleanPrefixes" | "hungarianPrefixes" | "placeholderNames" | "negativeBooleanAllowed" | "knownAcronyms"): void {
|
|
371
376
|
if (!allowlists || !(key in allowlists)) {
|
|
372
377
|
return;
|
|
373
378
|
}
|
|
@@ -375,7 +380,8 @@ function applyNamingAllowlist(config: Config, allowlists: Record<string, unknown
|
|
|
375
380
|
}
|
|
376
381
|
|
|
377
382
|
// Per-rule overrides under the `rules:` key. Each entry can carry enabled / threshold / severity /
|
|
378
|
-
// options - only the keys the user actually sets become overrides; unset keys fall through to
|
|
383
|
+
// options - only the keys the user actually sets become overrides; unset keys fall through to
|
|
384
|
+
// defaults. Throws ConfigLoadError on rule ids outside the catalogue and on malformed field values.
|
|
379
385
|
function applyRuleConfig(config: Config, raw: Record<string, unknown>): void {
|
|
380
386
|
const rules = objectValue(raw.rules);
|
|
381
387
|
if (!rules) {
|
|
@@ -386,21 +392,44 @@ function applyRuleConfig(config: Config, raw: Record<string, unknown>): void {
|
|
|
386
392
|
if (!rule) {
|
|
387
393
|
continue;
|
|
388
394
|
}
|
|
389
|
-
|
|
395
|
+
// A misspelled id would otherwise sit in the map as a silent no-op the user believes is policy.
|
|
396
|
+
if (!isKnownRuleId(ruleId)) {
|
|
397
|
+
throw new ConfigLoadError(
|
|
398
|
+
`Unknown rule id: ${JSON.stringify(ruleId)}.`,
|
|
399
|
+
"Use a rule id from `gruff-ts list-rules`; `rules:` keys must match the catalogue exactly.",
|
|
400
|
+
);
|
|
401
|
+
}
|
|
402
|
+
config.rules.set(ruleId, ruleConfigValue(ruleId, rule));
|
|
390
403
|
}
|
|
391
404
|
}
|
|
392
405
|
|
|
393
|
-
// Builds one rule's override entry after
|
|
406
|
+
// Builds one rule's override entry after the field asserts have thrown on malformed input.
|
|
394
407
|
// Validation happens before extraction so users see a useful error rather than a silently dropped key.
|
|
395
|
-
function ruleConfigValue(rule: Record<string, unknown>): RuleOverride {
|
|
408
|
+
function ruleConfigValue(ruleId: string, rule: Record<string, unknown>): RuleOverride {
|
|
396
409
|
assertRuleThresholdConfig(rule);
|
|
397
|
-
|
|
410
|
+
assertRuleEnabledConfig(rule);
|
|
411
|
+
const ruleOverride: RuleOverride = { options: validatedRuleOptions(ruleId, rule.options) };
|
|
398
412
|
applyRuleEnabledConfig(ruleOverride, rule);
|
|
399
413
|
applyRuleThresholdConfig(ruleOverride, rule);
|
|
400
414
|
applyRuleSeverityConfig(ruleOverride, rule);
|
|
401
415
|
return ruleOverride;
|
|
402
416
|
}
|
|
403
417
|
|
|
418
|
+
/*
|
|
419
|
+
* Rejects non-boolean `enabled` values loudly. YAML 1.2 core scalars keep `no`/`off`/`yes`/`on` as
|
|
420
|
+
* strings (only `true`/`false` parse as booleans), so a user writing `enabled: no` previously got a
|
|
421
|
+
* silent no-op while believing the rule was off. Throws ConfigLoadError naming the offending value
|
|
422
|
+
* and the accepted forms; returns silently when the key is absent.
|
|
423
|
+
*/
|
|
424
|
+
function assertRuleEnabledConfig(rule: Record<string, unknown>): void {
|
|
425
|
+
if ("enabled" in rule && typeof rule.enabled !== "boolean") {
|
|
426
|
+
throw new ConfigLoadError(
|
|
427
|
+
`Rule config key "enabled" must be true or false; got ${JSON.stringify(rule.enabled)}.`,
|
|
428
|
+
"YAML 1.2 treats `no`/`off`/`yes`/`on` as strings - write `enabled: true` or `enabled: false`.",
|
|
429
|
+
);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
404
433
|
/*
|
|
405
434
|
* Validates individual `threshold` and `severity` types. Either, neither, or both may be present:
|
|
406
435
|
* many rules have no `threshold` knob at all (security.eval-call, waste.any-type, etc.), so a
|
|
@@ -442,18 +471,29 @@ function applyRuleSeverityConfig(ruleOverride: RuleOverride, rule: Record<string
|
|
|
442
471
|
}
|
|
443
472
|
}
|
|
444
473
|
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
474
|
+
/*
|
|
475
|
+
* Validates `rules.<id>.options` against the rule descriptor's declared option keys - a dropped
|
|
476
|
+
* option would otherwise convince the user a tuning applied when it did not. Rules without declared
|
|
477
|
+
* options reject every entry. Throws ConfigLoadError naming the rule and its accepted keys for
|
|
478
|
+
* unknown keys, and the offending value for non-numeric declared options.
|
|
479
|
+
*/
|
|
480
|
+
function validatedRuleOptions(ruleId: string, optionsValue: unknown): Map<string, number> {
|
|
448
481
|
const options = new Map<string, number>();
|
|
449
482
|
const rawOptions = objectValue(optionsValue);
|
|
450
483
|
if (!rawOptions) {
|
|
451
484
|
return options;
|
|
452
485
|
}
|
|
486
|
+
const acceptedKeys = ruleOptionKeys(ruleId);
|
|
453
487
|
for (const [name, option] of Object.entries(rawOptions)) {
|
|
454
|
-
|
|
455
|
-
|
|
488
|
+
// Reject unknown keys first so a typo is reported as the typo, not as a type error.
|
|
489
|
+
if (!acceptedKeys.includes(name)) {
|
|
490
|
+
const accepted = acceptedKeys.length > 0 ? `accepts options: ${acceptedKeys.join(", ")}` : "accepts no options";
|
|
491
|
+
throw new ConfigLoadError(`Unknown option ${JSON.stringify(name)} for rule ${ruleId}; the rule ${accepted}.`, SUGGEST_EDIT_CONFIG);
|
|
492
|
+
}
|
|
493
|
+
if (typeof option !== "number") {
|
|
494
|
+
throw new ConfigLoadError(`Rule config option ${JSON.stringify(name)} for ${ruleId} must be numeric; got ${JSON.stringify(option)}.`, SUGGEST_EDIT_CONFIG);
|
|
456
495
|
}
|
|
496
|
+
options.set(name, option);
|
|
457
497
|
}
|
|
458
498
|
return options;
|
|
459
499
|
}
|
package/src/constants.ts
CHANGED
package/src/context-doc-rules.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
// Context-doc rules: emit findings when a function or interface comment exists but does not
|
|
2
2
|
// describe the WHY (complex control flow), side effects, error behavior, or public-contract
|
|
3
3
|
// invariants the implementation carries. Each rule reports a stable, deterministic finding.
|
|
4
|
-
import { type FunctionBlock
|
|
4
|
+
import { type FunctionBlock } from "./blocks.ts";
|
|
5
5
|
import { type CommentRecord } from "./comment-scanner.ts";
|
|
6
|
+
import { baseComplexityMetrics } from "./complexity-metrics.ts";
|
|
6
7
|
import { threshold } from "./config.ts";
|
|
7
8
|
import { type SourceFile } from "./discovery.ts";
|
|
8
9
|
import { makeFinding } from "./findings.ts";
|
|
9
|
-
import { countMatches } from "./text-scans.ts";
|
|
10
10
|
import type { Config, Finding } from "./types.ts";
|
|
11
11
|
|
|
12
12
|
// Generic declaration shape used by both function and interface comment-quality rules so they can
|
|
@@ -147,23 +147,22 @@ function contextDocFinding(input: ContextDocFindingInput): Finding {
|
|
|
147
147
|
});
|
|
148
148
|
}
|
|
149
149
|
|
|
150
|
-
//
|
|
151
|
-
// configured stable threshold qualifies a callable as "complex enough to need WHY context".
|
|
150
|
+
// Uses the same syntax measurement as complexity findings so a reviewer sees one consistent gate.
|
|
152
151
|
function isComplexContextCandidate(block: FunctionBlock, config: Config): boolean {
|
|
153
|
-
|
|
154
|
-
const
|
|
152
|
+
// A legacy span-only caller cannot reparse here, so it receives the same neutral fallback as block rules.
|
|
153
|
+
const sharedComplexityMetrics = block.complexityMetrics ?? baseComplexityMetrics();
|
|
155
154
|
return (
|
|
156
155
|
block.lineCount > threshold(config, "size.function-length", 200) ||
|
|
157
|
-
cyclomatic > threshold(config, "complexity.cyclomatic", 15) ||
|
|
158
|
-
cognitive > threshold(config, "complexity.cognitive", 15) ||
|
|
159
|
-
|
|
156
|
+
sharedComplexityMetrics.cyclomatic > threshold(config, "complexity.cyclomatic", 15) ||
|
|
157
|
+
sharedComplexityMetrics.cognitive > threshold(config, "complexity.cognitive", 15) ||
|
|
158
|
+
sharedComplexityMetrics.maximumControlFlowNesting > 3
|
|
160
159
|
);
|
|
161
160
|
}
|
|
162
161
|
|
|
163
162
|
// Vocabulary list signalling "the comment explains why" - the missing-why rule passes when any
|
|
164
163
|
// listed word appears. Adding entries here loosens the rule; removing them tightens it.
|
|
165
164
|
function hasComplexWhyMarker(text: string): boolean {
|
|
166
|
-
return /\b(?:because|why|intentional|
|
|
165
|
+
return /\b(?:because|why|intentional|trade-?off|compat(?:ibility|ible)?|avoid|preserve)\b|\b(?:due to|so that|in order to|required by)\b/i.test(text);
|
|
167
166
|
}
|
|
168
167
|
|
|
169
168
|
// Vocabulary for "comment names a side effect". Pairs with `SIDE_EFFECT_BODY_PATTERNS` - if the
|