@blundergoat/gruff-ts 0.1.0 → 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 +35 -11
- package/CONTRIBUTING.md +3 -3
- package/README.md +141 -183
- package/docs/README.md +23 -0
- package/docs/ci-integration.md +63 -0
- package/docs/{CONFIGURATION.md → configuration.md} +41 -20
- package/docs/dashboard.md +36 -0
- package/docs/output-formats.md +65 -0
- package/docs/{RELEASING.md → releasing.md} +17 -14
- package/docs/{REPORTS_AND_CI.md → reports-and-ci.md} +5 -2
- package/docs/rules.md +177 -0
- package/package.json +2 -2
- package/scripts/bump-version.sh +83 -18
- package/scripts/dependency-install.sh +96 -0
- package/scripts/dependency-update.sh +177 -0
- package/scripts/preflight-checks.sh +38 -0
- package/src/analyser.ts +9 -24
- package/src/blocks.ts +66 -12
- package/src/class-rules.ts +5 -6
- package/src/cli-program.ts +216 -39
- package/src/cli.ts +4 -1
- package/src/comment-rules.ts +2 -0
- package/src/config-load-error.ts +18 -0
- package/src/config-preservation.ts +64 -0
- package/src/config.ts +155 -29
- package/src/constants.ts +10 -2
- package/src/dashboard.ts +1 -1
- package/src/dead-code-rules.ts +62 -16
- package/src/doc-rules.ts +3 -3
- package/src/findings-helpers.ts +17 -0
- package/src/init-config.ts +308 -0
- package/src/line-rules.ts +64 -12
- package/src/naming-pushers.ts +7 -32
- package/src/pillar-summary.ts +129 -0
- package/src/project-config-rules.ts +1 -1
- package/src/report-html.ts +404 -0
- package/src/report-renderers.ts +210 -406
- package/src/rule-list.ts +65 -1
- package/src/rules.ts +36 -37
- package/src/safety-rules.ts +9 -4
- package/src/scoring.ts +41 -9
- package/src/test-block-rules.ts +43 -1
- package/src/test-fixtures.ts +13 -7
- package/src/text-scans.ts +1 -152
- package/src/types.ts +32 -6
package/src/cli-program.ts
CHANGED
|
@@ -1,15 +1,19 @@
|
|
|
1
1
|
// Commander CLI shell wiring that keeps option normalization and stdout behavior outside the analyzer.
|
|
2
|
-
import { Command, Help } from "commander";
|
|
2
|
+
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
|
-
import {
|
|
10
|
-
import {
|
|
12
|
+
import { promptYesNo, shouldPromptForInit, writeDefaultConfig } from "./init-config.ts";
|
|
13
|
+
import { renderReport, renderSummary, renderSummaryJson } from "./report-renderers.ts";
|
|
14
|
+
import { completionShell, getRuleDescriptor, renderCompletionScript, renderConsoleList, renderRuleDetail, renderRuleList, type RuleListFormat } from "./rule-list.ts";
|
|
11
15
|
import { exitFor } from "./scoring.ts";
|
|
12
|
-
import type { AnalysisOptions, AnalysisReport } from "./types.ts";
|
|
16
|
+
import type { AnalysisOptions, AnalysisReport, MinimumSeverityCommand } from "./types.ts";
|
|
13
17
|
|
|
14
18
|
type AnalyseRunner = (options: AnalysisOptions) => AnalysisReport;
|
|
15
19
|
|
|
@@ -35,6 +39,49 @@ function outputSuppressed(program: Command): boolean {
|
|
|
35
39
|
return options.quiet === true || options.silent === true;
|
|
36
40
|
}
|
|
37
41
|
|
|
42
|
+
// Per-command config-loading state passed into maybePromptInitConfig. analyse/summary/report
|
|
43
|
+
// take both flags from normalizeOptions; dashboard has no equivalent flags so it passes
|
|
44
|
+
// `{ shouldSkipConfig: false, hasExplicitConfig: false }`.
|
|
45
|
+
interface InitPromptOptions {
|
|
46
|
+
shouldSkipConfig: boolean;
|
|
47
|
+
hasExplicitConfig: boolean;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Asks the user whether to run `init` when no config exists, then writes the file if they agree.
|
|
51
|
+
// Called from analyse/summary/report/dashboard before kicking off their main work so the
|
|
52
|
+
// freshly-written file is picked up by loadConfig on the same invocation. Pure decision logic
|
|
53
|
+
// lives in shouldPromptForInit; this function only handles orchestration and side effects.
|
|
54
|
+
async function maybePromptInitConfig(program: Command, projectRoot: string, options: InitPromptOptions): Promise<void> {
|
|
55
|
+
const programOptions = program.opts() as { interaction?: boolean };
|
|
56
|
+
const context = {
|
|
57
|
+
projectRoot,
|
|
58
|
+
shouldSkipConfig: options.shouldSkipConfig,
|
|
59
|
+
hasExplicitConfig: options.hasExplicitConfig,
|
|
60
|
+
isInteractionAllowed: programOptions.interaction !== false,
|
|
61
|
+
isOutputSuppressed: outputSuppressed(program),
|
|
62
|
+
isStdinTty: process.stdin.isTTY === true,
|
|
63
|
+
isStdoutTty: process.stdout.isTTY === true,
|
|
64
|
+
isStderrTty: process.stderr.isTTY === true,
|
|
65
|
+
};
|
|
66
|
+
if (!shouldPromptForInit(context)) {
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
const accepted = await promptYesNo(`No gruff config found at ${projectRoot}. Run 'gruff-ts init' to create .gruff-ts.yaml? [y/N] `);
|
|
70
|
+
if (!accepted) {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const result = writeDefaultConfig(projectRoot, false);
|
|
74
|
+
if (result.status === "written") {
|
|
75
|
+
process.stderr.write(`Wrote ${result.path}\n`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// AnalysisOptions → InitPromptOptions shim used by analyse/summary/report so they share one
|
|
80
|
+
// branch and shouldSkipConfig stays the single source of truth for opt-out behaviour.
|
|
81
|
+
function promptOptionsFromAnalysis(options: AnalysisOptions): InitPromptOptions {
|
|
82
|
+
return { shouldSkipConfig: options.shouldSkipConfig, hasExplicitConfig: typeof options.config === "string" };
|
|
83
|
+
}
|
|
84
|
+
|
|
38
85
|
// Three-state ANSI resolution: explicit `--ansi` forces colour, explicit `--no-ansi` forbids it,
|
|
39
86
|
// otherwise autodetect from TTY. Required because pipelines and CI logs would otherwise eat colour codes.
|
|
40
87
|
function ansiEnabled(program: Command): boolean {
|
|
@@ -56,6 +103,7 @@ export function buildProgram(runAnalyse: AnalyseRunner): Command {
|
|
|
56
103
|
registerAnalyseCommand(program, runAnalyse);
|
|
57
104
|
registerCompletionCommand(program);
|
|
58
105
|
registerDashboardCommand(program, runAnalyse);
|
|
106
|
+
registerInitCommand(program);
|
|
59
107
|
registerListCommand(program);
|
|
60
108
|
registerListRulesCommand(program);
|
|
61
109
|
registerReportCommand(program, runAnalyse);
|
|
@@ -111,7 +159,10 @@ function rootHelpText(program: Command, command: Command, helper: Help): string
|
|
|
111
159
|
}
|
|
112
160
|
|
|
113
161
|
// The primary entry point. Sets `process.exitCode` (not `process.exit`) so async writers in the
|
|
114
|
-
// 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.
|
|
115
166
|
function registerAnalyseCommand(program: Command, runAnalyse: AnalyseRunner): void {
|
|
116
167
|
program
|
|
117
168
|
.command("analyse")
|
|
@@ -120,18 +171,22 @@ function registerAnalyseCommand(program: Command, runAnalyse: AnalyseRunner): vo
|
|
|
120
171
|
.option("--config <path>", "Path to a gruff YAML config file.")
|
|
121
172
|
.option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
|
|
122
173
|
.option("--format <format>", "Output format: text, json, html, markdown, github, hotspot, or sarif.", "text")
|
|
123
|
-
.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")
|
|
124
175
|
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
125
176
|
.option("--diff [mode]", "Filter findings to changed files. Use working-tree, staged, unstaged, or a base ref.")
|
|
126
177
|
.option("--history-file <path>", "Append score trend history to this JSON file.")
|
|
127
178
|
.option("--baseline [path]", "Suppress findings that match a gruff baseline JSON file.")
|
|
128
179
|
.option("--generate-baseline [path]", "Write current findings to a gruff baseline JSON file.")
|
|
129
180
|
.option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
|
|
130
|
-
.action((paths: string[], rawOptions: Record<string, unknown
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
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
|
+
});
|
|
135
190
|
});
|
|
136
191
|
}
|
|
137
192
|
|
|
@@ -156,11 +211,45 @@ function registerDashboardCommand(program: Command, runAnalyse: AnalyseRunner):
|
|
|
156
211
|
.option("--host <host>", "Host to bind.", "127.0.0.1")
|
|
157
212
|
.option("--port <port>", "Port to bind.", "8767")
|
|
158
213
|
.option("--project-root <path>", "Default project root.", ".")
|
|
214
|
+
.action(async (rawOptions: Record<string, unknown>) => {
|
|
215
|
+
const projectRoot = resolve(String(rawOptions.projectRoot ?? "."));
|
|
216
|
+
await maybePromptInitConfig(program, projectRoot, { shouldSkipConfig: false, hasExplicitConfig: false });
|
|
217
|
+
startDashboard(String(rawOptions.host ?? "127.0.0.1"), Number(rawOptions.port ?? 8767), projectRoot, runAnalyse, !outputSuppressed(program));
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Writes the default `.gruff-ts.yaml` to the current working directory. Refuses to clobber an
|
|
222
|
+
// existing config unless `--force` is passed; sets process.exitCode=1 in that case so scripted
|
|
223
|
+
// callers can detect the refusal without parsing stdout.
|
|
224
|
+
function registerInitCommand(program: Command): void {
|
|
225
|
+
program
|
|
226
|
+
.command("init")
|
|
227
|
+
.description("Write the default .gruff-ts.yaml to the current directory.")
|
|
228
|
+
.option("--force", "Write .gruff-ts.yaml even when another supported config (.gruff.yaml/.yml/.json) is present; overwrites .gruff-ts.yaml if it exists.")
|
|
159
229
|
.action((rawOptions: Record<string, unknown>) => {
|
|
160
|
-
|
|
230
|
+
const result = writeDefaultConfig(process.cwd(), rawOptions.force === true);
|
|
231
|
+
if (result.status === "exists") {
|
|
232
|
+
process.stderr.write(`Refusing to overwrite existing config: ${result.path}. Re-run with --force to replace it.\n`);
|
|
233
|
+
process.exitCode = 1;
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
const verb = result.status === "overwritten" ? "Overwrote" : "Wrote";
|
|
237
|
+
writeCommandOutput(program, initSuccessMessage(verb, result.path));
|
|
161
238
|
});
|
|
162
239
|
}
|
|
163
240
|
|
|
241
|
+
// Keeps `init` as a config-only write while pointing existing projects at the adoption flow.
|
|
242
|
+
function initSuccessMessage(verb: "Wrote" | "Overwrote", configPath: string): string {
|
|
243
|
+
return [
|
|
244
|
+
`${verb} ${configPath}`,
|
|
245
|
+
"",
|
|
246
|
+
"Next: generate an adoption baseline with:",
|
|
247
|
+
" gruff-ts analyse . --generate-baseline gruff-baseline.json --fail-on=none",
|
|
248
|
+
"Then gate new findings with:",
|
|
249
|
+
" gruff-ts analyse . --baseline gruff-baseline.json --fail-on=advisory",
|
|
250
|
+
].join("\n");
|
|
251
|
+
}
|
|
252
|
+
|
|
164
253
|
// Mirrors the bare-root help output. Exists so users coming from Symfony's console conventions
|
|
165
254
|
// can run `gruff-ts list` the way they expect.
|
|
166
255
|
function registerListCommand(program: Command): void {
|
|
@@ -173,15 +262,27 @@ function registerListCommand(program: Command): void {
|
|
|
173
262
|
}
|
|
174
263
|
|
|
175
264
|
// Read-only catalogue dump. JSON is the canonical form consumed by docs builds; text is for humans.
|
|
176
|
-
//
|
|
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.
|
|
177
268
|
function registerListRulesCommand(program: Command): void {
|
|
178
269
|
program
|
|
179
270
|
.command("list-rules")
|
|
180
|
-
.description("List gruff rule metadata.")
|
|
181
|
-
.
|
|
182
|
-
.
|
|
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.")
|
|
273
|
+
.option("--format <format>", "Output format: text or json.", parseSummaryFormat, "text")
|
|
274
|
+
.action((ruleId: string | undefined, rawOptions: Record<string, unknown>) => {
|
|
183
275
|
const format: RuleListFormat = rawOptions.format === "json" ? "json" : "text";
|
|
184
|
-
|
|
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));
|
|
185
286
|
});
|
|
186
287
|
}
|
|
187
288
|
|
|
@@ -200,22 +301,25 @@ function registerReportCommand(program: Command, runAnalyse: AnalyseRunner): voi
|
|
|
200
301
|
.option("--fail-on <severity>", "Finding severity that fails the run.", "none")
|
|
201
302
|
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
202
303
|
.option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
|
|
203
|
-
.action((paths: string[], rawOptions: Record<string, unknown
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
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
|
+
});
|
|
214
319
|
});
|
|
215
320
|
}
|
|
216
321
|
|
|
217
|
-
// Same analyser run as `analyse` but renders only the pillar/rule/offender digest.
|
|
218
|
-
// to `text` because the summary shape is intentionally not part of the JSON report contract.
|
|
322
|
+
// Same analyser run as `analyse` but renders only the pillar/rule/offender digest.
|
|
219
323
|
function registerSummaryCommand(program: Command, runAnalyse: AnalyseRunner): void {
|
|
220
324
|
program
|
|
221
325
|
.command("summary")
|
|
@@ -225,23 +329,59 @@ function registerSummaryCommand(program: Command, runAnalyse: AnalyseRunner): vo
|
|
|
225
329
|
.argument("[paths...]", "Files or directories to analyse.")
|
|
226
330
|
.option("--config <path>", "Path to a gruff YAML config file.")
|
|
227
331
|
.option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
|
|
228
|
-
.option("--
|
|
332
|
+
.option("--format <format>", "Output format: text or json.", parseSummaryFormat, "text")
|
|
333
|
+
.option("--top <n>", "How many top rules and file offenders to list.", parseNonNegativeInteger, 10)
|
|
334
|
+
.option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", "advisory")
|
|
229
335
|
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
230
336
|
.option("--diff [mode]", "Filter findings to changed files. Use working-tree, staged, unstaged, or a base ref.")
|
|
231
337
|
.option("--history-file <path>", "Append score trend history to this JSON file.")
|
|
232
338
|
.option("--baseline [path]", "Suppress findings that match a gruff baseline JSON file.")
|
|
233
339
|
.option("--generate-baseline [path]", "Write current findings to a gruff baseline JSON file.")
|
|
234
340
|
.option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
|
|
235
|
-
.action((paths: string[], rawOptions: Record<string, unknown
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
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
|
+
});
|
|
242
358
|
});
|
|
243
359
|
}
|
|
244
360
|
|
|
361
|
+
/*
|
|
362
|
+
* Commander `--format` argParser for the summary command. Throws `InvalidArgumentError` when the
|
|
363
|
+
* input is neither `text` nor `json`; commander reports that as a usage error and exits non-zero
|
|
364
|
+
* before the command body runs.
|
|
365
|
+
*/
|
|
366
|
+
function parseSummaryFormat(rawFormat: string): "text" | "json" {
|
|
367
|
+
if (rawFormat === "text" || rawFormat === "json") {
|
|
368
|
+
return rawFormat;
|
|
369
|
+
}
|
|
370
|
+
throw new InvalidArgumentError("must be text or json");
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/*
|
|
374
|
+
* Commander argParser for `--top`-style numeric flags. Throws `InvalidArgumentError` on non-integer
|
|
375
|
+
* or negative input so commander reports a usage error and exits non-zero before the command runs.
|
|
376
|
+
*/
|
|
377
|
+
function parseNonNegativeInteger(rawCount: string): number {
|
|
378
|
+
const parsed = Number(rawCount);
|
|
379
|
+
if (!Number.isInteger(parsed) || parsed < 0) {
|
|
380
|
+
throw new InvalidArgumentError("must be a non-negative integer");
|
|
381
|
+
}
|
|
382
|
+
return parsed;
|
|
383
|
+
}
|
|
384
|
+
|
|
245
385
|
// Summary output should name the scanned operand, not merely the process cwd used to run gruff-ts.
|
|
246
386
|
function summaryPathLabel(paths: string[], projectRoot: string): string {
|
|
247
387
|
if (paths.length === 0) {
|
|
@@ -256,7 +396,7 @@ function summaryPathLabel(paths: string[], projectRoot: string): string {
|
|
|
256
396
|
// adding new fields here without folding them into that hash is a deterministic-output regression.
|
|
257
397
|
function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>, context: NormalizeContext): AnalysisOptions {
|
|
258
398
|
const format = stringChoice(rawOptions.format, ["text", "json", "html", "markdown", "github", "hotspot", "sarif"], "text");
|
|
259
|
-
const failOn = stringChoice(rawOptions.failOn, ["none", "advisory", "warning", "error"], "
|
|
399
|
+
const failOn = stringChoice(rawOptions.failOn, ["none", "advisory", "warning", "error"], "advisory");
|
|
260
400
|
const baselineValue = rawOptions.baseline;
|
|
261
401
|
const shouldSkipBaseline =
|
|
262
402
|
!context.shouldAllowBaselineFlag ||
|
|
@@ -324,3 +464,40 @@ function generateBaselineOption(rawOptions: Record<string, unknown>): Partial<Pi
|
|
|
324
464
|
function stringChoice<T extends string>(value: unknown, choices: readonly T[], fallback: T): T {
|
|
325
465
|
return typeof value === "string" && choices.includes(value as T) ? (value as T) : fallback;
|
|
326
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
|
+
}
|
package/src/cli.ts
CHANGED
|
@@ -13,7 +13,10 @@ export type { AnalysisReport, Finding, OutputFormat, Pillar, RuleDescriptor, Sev
|
|
|
13
13
|
const buildProgram = (): ReturnType<typeof buildCliProgram> => buildCliProgram(analyse);
|
|
14
14
|
|
|
15
15
|
if (import.meta.url === pathToFileURL(argv[1] ?? "").href) {
|
|
16
|
-
|
|
16
|
+
// Action handlers in cli-program.ts are async (await maybePromptInitConfig). parseAsync is
|
|
17
|
+
// required so rejections after the first await surface through Commander's error path instead
|
|
18
|
+
// of escaping as unhandled promise rejections.
|
|
19
|
+
await buildProgram().parseAsync(argv);
|
|
17
20
|
}
|
|
18
21
|
|
|
19
22
|
export { absolutize, analyse, buildProgram, displayPath, renderReport, ruleDescriptors };
|
package/src/comment-rules.ts
CHANGED
|
@@ -294,6 +294,7 @@ function knownCliFlags(): Set<string> {
|
|
|
294
294
|
"--config",
|
|
295
295
|
"--diff",
|
|
296
296
|
"--fail-on",
|
|
297
|
+
"--force",
|
|
297
298
|
"--format",
|
|
298
299
|
"--generate-baseline",
|
|
299
300
|
"--help",
|
|
@@ -309,6 +310,7 @@ function knownCliFlags(): Set<string> {
|
|
|
309
310
|
"--project-root",
|
|
310
311
|
"--quiet",
|
|
311
312
|
"--silent",
|
|
313
|
+
"--top",
|
|
312
314
|
"--verbose",
|
|
313
315
|
"--version",
|
|
314
316
|
]);
|
|
@@ -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
|
+
}
|