@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/CHANGELOG.md +31 -19
- package/README.md +26 -26
- package/docs/configuration.md +39 -1
- package/docs/dashboard.md +7 -0
- package/docs/output-formats.md +1 -1
- package/docs/releasing.md +11 -10
- package/docs/reports-and-ci.md +5 -2
- package/package.json +1 -1
- package/scripts/bump-version.sh +19 -3
- package/scripts/preflight-checks.sh +4 -41
- package/src/analyser.ts +4 -4
- package/src/blocks.ts +62 -8
- package/src/cli-program.ts +106 -42
- package/src/config-load-error.ts +18 -0
- package/src/config-preservation.ts +64 -0
- package/src/config.ts +154 -26
- package/src/constants.ts +10 -2
- package/src/dashboard.ts +1 -1
- package/src/dead-code-rules.ts +60 -14
- package/src/doc-rules.ts +3 -3
- package/src/findings-helpers.ts +17 -0
- package/src/init-config.ts +91 -31
- package/src/line-rules.ts +58 -4
- package/src/naming-pushers.ts +7 -1
- package/src/pillar-summary.ts +129 -0
- package/src/report-html.ts +404 -0
- package/src/report-renderers.ts +163 -408
- package/src/rule-list.ts +64 -1
- package/src/rules.ts +22 -21
- package/src/safety-rules.ts +6 -1
- package/src/scoring.ts +38 -6
- package/src/test-block-rules.ts +43 -1
- package/src/test-fixtures.ts +13 -5
- package/src/types.ts +31 -4
package/src/blocks.ts
CHANGED
|
@@ -22,17 +22,27 @@ export interface FunctionBlock {
|
|
|
22
22
|
body: string;
|
|
23
23
|
codeBody: string;
|
|
24
24
|
isPublic: boolean;
|
|
25
|
+
// True when the function declaration line itself starts with `export`. Distinct from `isPublic`,
|
|
26
|
+
// which also matches class `public` modifiers - exports are the top-level API surface, while a
|
|
27
|
+
// public class method is internal to an exported (or unexported) class. The doc rule splits
|
|
28
|
+
// severity on this distinction: exported functions warrant warning-tier doc requirements,
|
|
29
|
+
// internal helpers stay advisory.
|
|
30
|
+
isExported: boolean;
|
|
25
31
|
isTest: boolean;
|
|
26
32
|
hasLeadingComment: boolean;
|
|
27
33
|
declarationLine: number;
|
|
28
34
|
}
|
|
29
35
|
|
|
30
36
|
// Working state for the function-block parser. Patterns are precompiled once per file so each
|
|
31
|
-
// callable detection doesn't re-instantiate the same RegExp objects.
|
|
37
|
+
// callable detection doesn't re-instantiate the same RegExp objects. `reExportedNames` carries
|
|
38
|
+
// the file-level scan of `export { foo }` / `export default foo` so a declaration like
|
|
39
|
+
// `function foo() {}` later re-exported via `export { foo }` is still classified as exported
|
|
40
|
+
// (the line-local `^export` check alone would miss this common pattern).
|
|
32
41
|
interface FunctionBlockScan {
|
|
33
42
|
lines: string[];
|
|
34
43
|
codeLines: string[];
|
|
35
44
|
patterns: RegExp[];
|
|
45
|
+
reExportedNames: ReadonlySet<string>;
|
|
36
46
|
}
|
|
37
47
|
|
|
38
48
|
const FUNCTION_BLOCK_PATTERNS = functionBlockPatterns();
|
|
@@ -208,12 +218,20 @@ function pushGenericFunctionFinding(context: BlockRuleContext): void {
|
|
|
208
218
|
}
|
|
209
219
|
}
|
|
210
220
|
|
|
211
|
-
|
|
212
|
-
|
|
221
|
+
/*
|
|
222
|
+
* Every non-test function must carry a leading comment. Test blocks are exempted because their
|
|
223
|
+
* `test("name", …)` description already documents intent. Reports
|
|
224
|
+
* `docs.missing-exported-function-doc` (warning, higher cost of omission on the public API
|
|
225
|
+
* surface) when `isExported` is true, `docs.missing-internal-function-doc` (advisory) otherwise.
|
|
226
|
+
*/
|
|
213
227
|
function pushMissingFunctionDocFinding(context: BlockRuleContext): void {
|
|
214
|
-
if (
|
|
215
|
-
|
|
228
|
+
if (context.block.isTest || context.block.hasLeadingComment) {
|
|
229
|
+
return;
|
|
216
230
|
}
|
|
231
|
+
const ruleId = context.block.isExported ? "docs.missing-exported-function-doc" : "docs.missing-internal-function-doc";
|
|
232
|
+
const severity = context.block.isExported ? "warning" : "advisory";
|
|
233
|
+
const audience = context.block.isExported ? "exported" : "internal";
|
|
234
|
+
context.findings.push(blockFinding({ ruleId, message: `${audience === "exported" ? "Exported" : "Internal"} function \`${context.block.name}\` is missing a leading maintainer comment.`, file: context.file, block: context.block, severity, pillar: "documentation" }));
|
|
217
235
|
}
|
|
218
236
|
|
|
219
237
|
// Empty bodies are sometimes intentional placeholders, hence the advisory severity rather than
|
|
@@ -453,6 +471,7 @@ export function functionBlocks(source: string, codeSource = source): FunctionBlo
|
|
|
453
471
|
lines: source.split(/\r?\n/),
|
|
454
472
|
codeLines: codeSource.split(/\r?\n/),
|
|
455
473
|
patterns: FUNCTION_BLOCK_PATTERNS,
|
|
474
|
+
reExportedNames: collectReExportedNames(codeSource),
|
|
456
475
|
};
|
|
457
476
|
const blocks: FunctionBlock[] = [];
|
|
458
477
|
scan.codeLines.forEach((line, index) => {
|
|
@@ -465,15 +484,49 @@ export function functionBlocks(source: string, codeSource = source): FunctionBlo
|
|
|
465
484
|
return blocks;
|
|
466
485
|
}
|
|
467
486
|
|
|
487
|
+
/*
|
|
488
|
+
* File-level scan for re-exported local declarations. Matches `export { foo }`, `export { foo as
|
|
489
|
+
* bar }` (the local name `foo` is recorded, not the renamed `bar`), and `export default foo`
|
|
490
|
+
* (bare-identifier form - `export default function ...` is matched via pattern 2 in
|
|
491
|
+
* functionBlockPatterns instead, then classified exported because the line itself starts with
|
|
492
|
+
* `export`). Re-export-from clauses (`export { foo } from "./other"`) are intentionally skipped
|
|
493
|
+
* via the negative lookahead: those names are not local declarations of this file, so promoting
|
|
494
|
+
* a same-named local to "exported" would emit a false missing-public-doc finding.
|
|
495
|
+
*
|
|
496
|
+
* Operates on the masked codeSource so `export { foo }` inside a string literal or comment is
|
|
497
|
+
* skipped. Multi-line export blocks work because `[^}]+` spans newlines, and the lookahead
|
|
498
|
+
* spans whitespace and blanked-comment runs that the masker collapses to spaces.
|
|
499
|
+
*/
|
|
500
|
+
function collectReExportedNames(codeSource: string): ReadonlySet<string> {
|
|
501
|
+
const names = new Set<string>();
|
|
502
|
+
for (const match of codeSource.matchAll(/export\s*\{([^}]+)\}(?!\s*from\b)/g)) {
|
|
503
|
+
for (const entry of (match[1] ?? "").split(",")) {
|
|
504
|
+
const local = entry.trim().split(/\s+as\s+/)[0]?.trim();
|
|
505
|
+
if (local && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(local)) {
|
|
506
|
+
names.add(local);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
for (const match of codeSource.matchAll(/^\s*export\s+default\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*;?\s*$/gm)) {
|
|
511
|
+
if (match[1]) {
|
|
512
|
+
names.add(match[1]);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
return names;
|
|
516
|
+
}
|
|
517
|
+
|
|
468
518
|
// Four callable shapes in the order `functionBlockMatch` tries them: `test()` / `it()` bodies,
|
|
469
519
|
// `function` declarations, class methods, and arrow assignments. Pattern[0] is intentionally
|
|
470
|
-
// first because test bodies must match before the generic arrow pattern claims them.
|
|
520
|
+
// first because test bodies must match before the generic arrow pattern claims them. Pattern[1]
|
|
521
|
+
// accepts an optional `default` after `export` so `export default function foo() {}` parses into
|
|
522
|
+
// a FunctionBlock - the CHANGELOG's exported-doc-rule contract advertises that shape and the
|
|
523
|
+
// missing `default` token previously made those declarations invisible to every block-level rule.
|
|
471
524
|
function functionBlockPatterns(): RegExp[] {
|
|
472
525
|
return [
|
|
473
526
|
/^\s*(?:test|it)\s*\(\s*["'`]([^"'`]+)["'`]\s*,\s*(?:async\s*)?\(([^)]*)\)\s*=>/,
|
|
474
|
-
/^\s*(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(([^)]*)\)/,
|
|
527
|
+
/^\s*(?:export\s+(?:default\s+)?)?(?:async\s+)?function\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(([^)]*)\)/,
|
|
475
528
|
/^\s*(?:public|private|protected)?\s*(?:async\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\s*\(([^)]*)\)\s*[:{]/,
|
|
476
|
-
/^\s*(?:const|let)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s*)?\(([^)]*)\)\s*=>/,
|
|
529
|
+
/^\s*(?:export\s+)?(?:const|let)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s*)?\(([^)]*)\)\s*=>/,
|
|
477
530
|
];
|
|
478
531
|
}
|
|
479
532
|
|
|
@@ -523,6 +576,7 @@ function functionBlockFromMatch(scan: FunctionBlockScan, match: RegExpMatchArray
|
|
|
523
576
|
body,
|
|
524
577
|
codeBody,
|
|
525
578
|
isPublic: /\bexport\b|\bpublic\b/.test(scan.codeLines.slice(start, index + 1).join("\n")),
|
|
579
|
+
isExported: /^\s*export\b/.test(scan.codeLines[index] ?? "") || scan.reExportedNames.has(match[1] ?? ""),
|
|
526
580
|
isTest: isTestInvocationLine(scan.codeLines[index] ?? ""),
|
|
527
581
|
hasLeadingComment: hasLeadingCommentBeforeLines(scan.lines, index + 1),
|
|
528
582
|
declarationLine: index + 1,
|
package/src/cli-program.ts
CHANGED
|
@@ -3,14 +3,17 @@ import { Command, Help, InvalidArgumentError } from "commander";
|
|
|
3
3
|
import { writeFileSync } from "node:fs";
|
|
4
4
|
import { resolve } from "node:path";
|
|
5
5
|
import { performance } from "node:perf_hooks";
|
|
6
|
+
import { cwd } from "node:process";
|
|
6
7
|
import { DEFAULT_BASELINE } from "./baseline.ts";
|
|
8
|
+
import { ConfigLoadError } from "./config-load-error.ts";
|
|
9
|
+
import { loadConfig, minimumSeverityFor } from "./config.ts";
|
|
7
10
|
import { VERSION } from "./constants.ts";
|
|
8
11
|
import { startDashboard } from "./dashboard.ts";
|
|
9
12
|
import { promptYesNo, shouldPromptForInit, writeDefaultConfig } from "./init-config.ts";
|
|
10
13
|
import { renderReport, renderSummary, renderSummaryJson } from "./report-renderers.ts";
|
|
11
|
-
import { completionShell, renderCompletionScript, renderConsoleList, renderRuleList, type RuleListFormat } from "./rule-list.ts";
|
|
14
|
+
import { completionShell, getRuleDescriptor, renderCompletionScript, renderConsoleList, renderRuleDetail, renderRuleList, type RuleListFormat } from "./rule-list.ts";
|
|
12
15
|
import { exitFor } from "./scoring.ts";
|
|
13
|
-
import type { AnalysisOptions, AnalysisReport } from "./types.ts";
|
|
16
|
+
import type { AnalysisOptions, AnalysisReport, MinimumSeverityCommand } from "./types.ts";
|
|
14
17
|
|
|
15
18
|
type AnalyseRunner = (options: AnalysisOptions) => AnalysisReport;
|
|
16
19
|
|
|
@@ -156,7 +159,10 @@ function rootHelpText(program: Command, command: Command, helper: Help): string
|
|
|
156
159
|
}
|
|
157
160
|
|
|
158
161
|
// The primary entry point. Sets `process.exitCode` (not `process.exit`) so async writers in the
|
|
159
|
-
// renderer get a chance to flush before Node tears down.
|
|
162
|
+
// renderer get a chance to flush before Node tears down. The default fail-on is `advisory` because
|
|
163
|
+
// the project's gating philosophy is "show everything, fail on anything"; CI flows that want the
|
|
164
|
+
// old `error`-only behaviour pass `--fail-on=error` explicitly or pin `minimumSeverity.analyse:
|
|
165
|
+
// error` in `.gruff-ts.yaml`. See ADR-004.
|
|
160
166
|
function registerAnalyseCommand(program: Command, runAnalyse: AnalyseRunner): void {
|
|
161
167
|
program
|
|
162
168
|
.command("analyse")
|
|
@@ -165,19 +171,22 @@ function registerAnalyseCommand(program: Command, runAnalyse: AnalyseRunner): vo
|
|
|
165
171
|
.option("--config <path>", "Path to a gruff YAML config file.")
|
|
166
172
|
.option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
|
|
167
173
|
.option("--format <format>", "Output format: text, json, html, markdown, github, hotspot, or sarif.", "text")
|
|
168
|
-
.option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", "
|
|
174
|
+
.option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", "advisory")
|
|
169
175
|
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
170
176
|
.option("--diff [mode]", "Filter findings to changed files. Use working-tree, staged, unstaged, or a base ref.")
|
|
171
177
|
.option("--history-file <path>", "Append score trend history to this JSON file.")
|
|
172
178
|
.option("--baseline [path]", "Suppress findings that match a gruff baseline JSON file.")
|
|
173
179
|
.option("--generate-baseline [path]", "Write current findings to a gruff baseline JSON file.")
|
|
174
180
|
.option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
|
|
175
|
-
.action(async (paths: string[], rawOptions: Record<string, unknown
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
+
.action(async (paths: string[], rawOptions: Record<string, unknown>, command: Command) => {
|
|
182
|
+
await runWithConfigErrorHandling(async () => {
|
|
183
|
+
const baseOptions = normalizeOptions(paths, rawOptions, { shouldAllowBaselineFlag: true });
|
|
184
|
+
const options = applyMinimumSeverityPrecedence(baseOptions, "analyse", command);
|
|
185
|
+
await maybePromptInitConfig(program, process.cwd(), promptOptionsFromAnalysis(options));
|
|
186
|
+
const report = runAnalyse(options);
|
|
187
|
+
writeCommandOutput(program, renderReport(report, options.format));
|
|
188
|
+
process.exitCode = exitFor(report, options.failOn);
|
|
189
|
+
});
|
|
181
190
|
});
|
|
182
191
|
}
|
|
183
192
|
|
|
@@ -237,7 +246,7 @@ function initSuccessMessage(verb: "Wrote" | "Overwrote", configPath: string): st
|
|
|
237
246
|
"Next: generate an adoption baseline with:",
|
|
238
247
|
" gruff-ts analyse . --generate-baseline gruff-baseline.json --fail-on=none",
|
|
239
248
|
"Then gate new findings with:",
|
|
240
|
-
" gruff-ts analyse . --baseline gruff-baseline.json --fail-on=
|
|
249
|
+
" gruff-ts analyse . --baseline gruff-baseline.json --fail-on=advisory",
|
|
241
250
|
].join("\n");
|
|
242
251
|
}
|
|
243
252
|
|
|
@@ -254,14 +263,26 @@ function registerListCommand(program: Command): void {
|
|
|
254
263
|
|
|
255
264
|
// Read-only catalogue dump. JSON is the canonical form consumed by docs builds; text is for humans.
|
|
256
265
|
// `--format` is validated by `parseSummaryFormat`; unsupported values fail fast as a usage error.
|
|
266
|
+
// Optional `<ruleId>` positional switches to single-rule detail mode (M08): no-arg behaviour stays
|
|
267
|
+
// byte-identical to the prior version.
|
|
257
268
|
function registerListRulesCommand(program: Command): void {
|
|
258
269
|
program
|
|
259
270
|
.command("list-rules")
|
|
260
|
-
.description("List gruff rule metadata.")
|
|
271
|
+
.description("List gruff rule metadata. Pass a rule id to print details for one rule.")
|
|
272
|
+
.argument("[ruleId]", "Optional rule id to print details for.")
|
|
261
273
|
.option("--format <format>", "Output format: text or json.", parseSummaryFormat, "text")
|
|
262
|
-
.action((rawOptions: Record<string, unknown>) => {
|
|
274
|
+
.action((ruleId: string | undefined, rawOptions: Record<string, unknown>) => {
|
|
263
275
|
const format: RuleListFormat = rawOptions.format === "json" ? "json" : "text";
|
|
264
|
-
|
|
276
|
+
if (ruleId === undefined) {
|
|
277
|
+
writeCommandOutput(program, renderRuleList(format));
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
const descriptor = getRuleDescriptor(ruleId);
|
|
281
|
+
if (!descriptor) {
|
|
282
|
+
program.error(`unknown rule "${ruleId}". Run \`gruff-ts list-rules\` to see all rules.`, { exitCode: 2 });
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
writeCommandOutput(program, renderRuleDetail(descriptor, format));
|
|
265
286
|
});
|
|
266
287
|
}
|
|
267
288
|
|
|
@@ -280,18 +301,21 @@ function registerReportCommand(program: Command, runAnalyse: AnalyseRunner): voi
|
|
|
280
301
|
.option("--fail-on <severity>", "Finding severity that fails the run.", "none")
|
|
281
302
|
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
282
303
|
.option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
|
|
283
|
-
.action(async (paths: string[], rawOptions: Record<string, unknown
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
304
|
+
.action(async (paths: string[], rawOptions: Record<string, unknown>, command: Command) => {
|
|
305
|
+
await runWithConfigErrorHandling(async () => {
|
|
306
|
+
const format = rawOptions.format === "json" ? "json" : "html";
|
|
307
|
+
const baseOptions = normalizeOptions(paths, { ...rawOptions, format }, { shouldAllowBaselineFlag: false });
|
|
308
|
+
const options = applyMinimumSeverityPrecedence(baseOptions, "report", command);
|
|
309
|
+
await maybePromptInitConfig(program, process.cwd(), promptOptionsFromAnalysis(options));
|
|
310
|
+
const report = runAnalyse(options);
|
|
311
|
+
const rendered = renderReport(report, format);
|
|
312
|
+
if (typeof rawOptions.output === "string") {
|
|
313
|
+
writeFileSync(rawOptions.output, rendered);
|
|
314
|
+
} else {
|
|
315
|
+
writeCommandOutput(program, rendered);
|
|
316
|
+
}
|
|
317
|
+
process.exitCode = exitFor(report, options.failOn);
|
|
318
|
+
});
|
|
295
319
|
});
|
|
296
320
|
}
|
|
297
321
|
|
|
@@ -307,27 +331,30 @@ function registerSummaryCommand(program: Command, runAnalyse: AnalyseRunner): vo
|
|
|
307
331
|
.option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
|
|
308
332
|
.option("--format <format>", "Output format: text or json.", parseSummaryFormat, "text")
|
|
309
333
|
.option("--top <n>", "How many top rules and file offenders to list.", parseNonNegativeInteger, 10)
|
|
310
|
-
.option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", "
|
|
334
|
+
.option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", "advisory")
|
|
311
335
|
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
312
336
|
.option("--diff [mode]", "Filter findings to changed files. Use working-tree, staged, unstaged, or a base ref.")
|
|
313
337
|
.option("--history-file <path>", "Append score trend history to this JSON file.")
|
|
314
338
|
.option("--baseline [path]", "Suppress findings that match a gruff baseline JSON file.")
|
|
315
339
|
.option("--generate-baseline [path]", "Write current findings to a gruff baseline JSON file.")
|
|
316
340
|
.option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
|
|
317
|
-
.action(async (paths: string[], rawOptions: Record<string, unknown
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
341
|
+
.action(async (paths: string[], rawOptions: Record<string, unknown>, command: Command) => {
|
|
342
|
+
await runWithConfigErrorHandling(async () => {
|
|
343
|
+
const baseOptions = normalizeOptions(paths, { ...rawOptions, format: "text" }, { shouldAllowBaselineFlag: true });
|
|
344
|
+
const options = applyMinimumSeverityPrecedence(baseOptions, "summary", command);
|
|
345
|
+
const summaryFormat = rawOptions.format === "json" ? "json" : "text";
|
|
346
|
+
const top = typeof rawOptions.top === "number" ? rawOptions.top : 10;
|
|
347
|
+
await maybePromptInitConfig(program, process.cwd(), promptOptionsFromAnalysis(options));
|
|
348
|
+
const startedAt = performance.now();
|
|
349
|
+
const report = runAnalyse(options);
|
|
350
|
+
const elapsedMs = performance.now() - startedAt;
|
|
351
|
+
const pathLabel = summaryPathLabel(options.paths, report.run.projectRoot);
|
|
352
|
+
const rendered = summaryFormat === "json"
|
|
353
|
+
? renderSummaryJson(report, elapsedMs, pathLabel, top)
|
|
354
|
+
: renderSummary(report, elapsedMs, pathLabel, top);
|
|
355
|
+
writeCommandOutput(program, rendered);
|
|
356
|
+
process.exitCode = exitFor(report, options.failOn);
|
|
357
|
+
});
|
|
331
358
|
});
|
|
332
359
|
}
|
|
333
360
|
|
|
@@ -369,7 +396,7 @@ function summaryPathLabel(paths: string[], projectRoot: string): string {
|
|
|
369
396
|
// adding new fields here without folding them into that hash is a deterministic-output regression.
|
|
370
397
|
function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>, context: NormalizeContext): AnalysisOptions {
|
|
371
398
|
const format = stringChoice(rawOptions.format, ["text", "json", "html", "markdown", "github", "hotspot", "sarif"], "text");
|
|
372
|
-
const failOn = stringChoice(rawOptions.failOn, ["none", "advisory", "warning", "error"], "
|
|
399
|
+
const failOn = stringChoice(rawOptions.failOn, ["none", "advisory", "warning", "error"], "advisory");
|
|
373
400
|
const baselineValue = rawOptions.baseline;
|
|
374
401
|
const shouldSkipBaseline =
|
|
375
402
|
!context.shouldAllowBaselineFlag ||
|
|
@@ -437,3 +464,40 @@ function generateBaselineOption(rawOptions: Record<string, unknown>): Partial<Pi
|
|
|
437
464
|
function stringChoice<T extends string>(value: unknown, choices: readonly T[], fallback: T): T {
|
|
438
465
|
return typeof value === "string" && choices.includes(value as T) ? (value as T) : fallback;
|
|
439
466
|
}
|
|
467
|
+
|
|
468
|
+
/*
|
|
469
|
+
* Precedence wiring for `--fail-on`: when the user did NOT pass `--fail-on` explicitly, the
|
|
470
|
+
* `.gruff-ts.yaml` `minimumSeverity.<cmd>` value wins over the binary default. CLI flag always
|
|
471
|
+
* wins when explicitly set. Commander's `getOptionValueSource("failOn")` returns `"cli"` for
|
|
472
|
+
* explicit invocations and `"default"` otherwise, so the source check drives the precedence
|
|
473
|
+
* chain. Throws `ConfigLoadError` on malformed config; CLI action handlers catch and format that
|
|
474
|
+
* cleanly via `runWithConfigErrorHandling`.
|
|
475
|
+
*/
|
|
476
|
+
function applyMinimumSeverityPrecedence(options: AnalysisOptions, command: MinimumSeverityCommand, commanderCommand: Command): AnalysisOptions {
|
|
477
|
+
if (commanderCommand.getOptionValueSource("failOn") === "cli") {
|
|
478
|
+
return options;
|
|
479
|
+
}
|
|
480
|
+
const config = loadConfig(cwd(), options);
|
|
481
|
+
const configuredFailOn = minimumSeverityFor(config, command);
|
|
482
|
+
return configuredFailOn === undefined ? options : { ...options, failOn: configuredFailOn };
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/*
|
|
486
|
+
* Wraps an async command action so a malformed `.gruff-ts.yaml` surfaces as a clean stderr message
|
|
487
|
+
* and exit code 2, not a raw Node stack trace. Catches `ConfigLoadError` (user-actionable config
|
|
488
|
+
* bug) and reports it via formatted stderr; rethrows every other exception so an analyser/code
|
|
489
|
+
* bug still surfaces its stack for debugging. The exit code matches the existing diagnostic
|
|
490
|
+
* convention in `exitFor` so CI scripts that already handle exit 2 keep working.
|
|
491
|
+
*/
|
|
492
|
+
async function runWithConfigErrorHandling(action: () => Promise<void> | void): Promise<void> {
|
|
493
|
+
try {
|
|
494
|
+
await action();
|
|
495
|
+
} catch (error) {
|
|
496
|
+
if (error instanceof ConfigLoadError) {
|
|
497
|
+
process.stderr.write(`gruff-ts: config error\n ${error.message}\n\nSuggested fix:\n ${error.suggestion}\n`);
|
|
498
|
+
process.exitCode = 2;
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
throw error;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Error class for user-facing config-load failures. CLI action handlers catch this specifically so
|
|
3
|
+
* a malformed `.gruff-ts.yaml` produces a clean stderr message and exit code 2, instead of a raw
|
|
4
|
+
* Node stack trace. The `suggestion` field carries the user-actionable next step (run init --force,
|
|
5
|
+
* edit a specific value, etc.) so the CLI layer can format it consistently across all throw sites.
|
|
6
|
+
* Reports a tagged error that the CLI layer recognises via `instanceof`.
|
|
7
|
+
*/
|
|
8
|
+
export class ConfigLoadError extends Error {
|
|
9
|
+
readonly suggestion: string;
|
|
10
|
+
|
|
11
|
+
// Stores the suggested fix alongside the message so the CLI formatter can render both without
|
|
12
|
+
// re-deriving the suggestion from the error text. Throws nothing; this is a plain data wrapper.
|
|
13
|
+
constructor(message: string, suggestion: string) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.name = "ConfigLoadError";
|
|
16
|
+
this.suggestion = suggestion;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// Best-effort field extraction for `gruff-ts init --force`. The strict loader in `config.ts`
|
|
2
|
+
// throws on schemaVersion mismatch (deliberate: pre-1.0 break, no migration shim), but the init
|
|
3
|
+
// migration path needs to lift `paths.ignore` and `minimumSeverity` off whatever the user has on
|
|
4
|
+
// disk so regeneration does not silently clobber curated entries. This module exists because the
|
|
5
|
+
// strict validator is the wrong tool for that handoff - the next analyser load will run it.
|
|
6
|
+
import { objectValue, parseConfigFile } from "./config.ts";
|
|
7
|
+
import type { FailThreshold, MinimumSeverityCommand } from "./types.ts";
|
|
8
|
+
|
|
9
|
+
// Carry-over bundle returned to `gruff-ts init --force`. Both fields are best-effort: empty
|
|
10
|
+
// values mean nothing was preserved, not that the existing config was empty.
|
|
11
|
+
interface PreservedConfigFields {
|
|
12
|
+
ignoredPaths: string[];
|
|
13
|
+
minimumSeverity: Map<MinimumSeverityCommand, FailThreshold>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/*
|
|
17
|
+
* Reads the existing config and returns its `paths.ignore` and `minimumSeverity` blocks. Pre-0.2.0
|
|
18
|
+
* configs without `schemaVersion` succeed here (the strict gate is skipped) so the user's entries
|
|
19
|
+
* survive `init --force`. Individual malformed entries inside the preserved blocks are dropped
|
|
20
|
+
* rather than thrown - the strict validator runs at the next analyser load and surfaces errors
|
|
21
|
+
* in the right place. Throws `ConfigLoadError` only on IO/parse failure of the file itself; the
|
|
22
|
+
* caller handles that fallback to "preserve nothing" instead of blocking regeneration.
|
|
23
|
+
*/
|
|
24
|
+
export function extractPreservedConfigFields(configPath: string): PreservedConfigFields {
|
|
25
|
+
const raw = parseConfigFile(configPath);
|
|
26
|
+
return {
|
|
27
|
+
ignoredPaths: extractIgnoredPaths(raw),
|
|
28
|
+
minimumSeverity: extractMinimumSeverity(raw),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// `paths.ignore` is a free-form list of glob strings. Non-string entries are dropped silently -
|
|
33
|
+
// the strict path enforces the same shape at the next analyser load.
|
|
34
|
+
function extractIgnoredPaths(raw: Record<string, unknown>): string[] {
|
|
35
|
+
const ignore = objectValue(raw.paths)?.ignore;
|
|
36
|
+
return Array.isArray(ignore) ? ignore.filter((entry): entry is string => typeof entry === "string") : [];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Permissive minimumSeverity reader: each entry is filtered through the same vocabulary the strict
|
|
40
|
+
// validator checks (commands × thresholds). Anything off-vocabulary is dropped. The reason we
|
|
41
|
+
// don't throw here is so a typo in one entry does not nuke preservation of the other entries.
|
|
42
|
+
function extractMinimumSeverity(raw: Record<string, unknown>): Map<MinimumSeverityCommand, FailThreshold> {
|
|
43
|
+
const result = new Map<MinimumSeverityCommand, FailThreshold>();
|
|
44
|
+
const block = objectValue(raw.minimumSeverity);
|
|
45
|
+
if (!block) {
|
|
46
|
+
return result;
|
|
47
|
+
}
|
|
48
|
+
for (const [commandName, value] of Object.entries(block)) {
|
|
49
|
+
addPreservedSeverityEntry(result, commandName, value);
|
|
50
|
+
}
|
|
51
|
+
return result;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Per-entry filter: extracted so the outer loop stays linear and the NPath budget for the file
|
|
55
|
+
// extractor stays small. Both gates must pass before the entry lands in the preserved map.
|
|
56
|
+
function addPreservedSeverityEntry(result: Map<MinimumSeverityCommand, FailThreshold>, commandName: string, rawThreshold: unknown): void {
|
|
57
|
+
if (commandName !== "analyse" && commandName !== "summary" && commandName !== "report") {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (rawThreshold !== "none" && rawThreshold !== "advisory" && rawThreshold !== "warning" && rawThreshold !== "error") {
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
result.set(commandName, rawThreshold);
|
|
64
|
+
}
|