@blundergoat/gruff-ts 0.4.0 → 0.6.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 +123 -1
- package/CONTRIBUTING.md +32 -25
- package/README.md +55 -46
- package/SECURITY.md +18 -30
- package/UPGRADING.md +101 -0
- package/bin/gruff-ts +3 -0
- package/docs/README.md +11 -13
- package/docs/agent-hook.md +33 -24
- package/docs/ci-integration.md +38 -24
- package/docs/configuration.md +173 -71
- package/docs/dashboard.md +12 -13
- package/docs/output-formats.md +100 -25
- package/docs/philosophy.md +2 -2
- package/docs/reports-and-ci.md +14 -157
- package/docs/rules.md +140 -106
- package/package.json +10 -8
- package/src/analyser.ts +886 -282
- package/src/baseline-file.ts +867 -0
- package/src/baseline-identity.ts +463 -0
- package/src/baseline-options.ts +139 -34
- package/src/baseline.ts +85 -55
- package/src/blocks.ts +579 -364
- package/src/changed-regions.ts +414 -65
- package/src/check-ignore.ts +28 -13
- package/src/class-rules.ts +461 -302
- package/src/cli-program.ts +956 -166
- package/src/cli.ts +9 -2
- package/src/comment-rules.ts +277 -414
- package/src/comment-scanner.ts +363 -44
- package/src/complexity-metrics.ts +320 -0
- package/src/config-load-error.ts +17 -8
- package/src/config-parse.ts +291 -98
- package/src/config-preservation.ts +81 -26
- package/src/config.ts +778 -210
- package/src/constants.ts +7 -6
- package/src/context-doc-rules.ts +188 -61
- package/src/dashboard.ts +88 -23
- package/src/dead-code-rules.ts +153 -74
- package/src/discovery.ts +521 -148
- package/src/doc-rules.ts +592 -147
- package/src/duplicate-test-group-rules.ts +359 -0
- package/src/findings-helpers.ts +240 -89
- package/src/findings.ts +48 -24
- package/src/fixture-purpose-rules.ts +226 -48
- package/src/github-actions-event-guards.ts +331 -0
- package/src/github-actions-rules.ts +336 -106
- package/src/hook-contract.ts +708 -211
- package/src/init-config.ts +169 -114
- package/src/inline-suppressions.ts +340 -0
- package/src/limit-band.ts +56 -0
- package/src/line-rules.ts +331 -419
- package/src/migrate-config.ts +670 -0
- package/src/naming-pushers.ts +33 -107
- package/src/parsed-script.ts +1206 -0
- package/src/pillar-summary.ts +56 -40
- package/src/profiles.ts +97 -71
- package/src/project-config-rules.ts +335 -146
- package/src/project-rules.ts +237 -115
- package/src/public-exports.ts +284 -0
- package/src/report-html.ts +217 -85
- package/src/report-renderers.ts +864 -195
- package/src/rule-list.ts +166 -46
- package/src/rules.ts +100 -104
- package/src/safety-rules.ts +191 -132
- package/src/scoring.ts +255 -52
- package/src/security-flow-rules.ts +930 -109
- package/src/selectors.ts +169 -0
- package/src/sensitive-data-rules.ts +502 -375
- package/src/sensitive-exclusions.ts +435 -0
- package/src/source-text.ts +380 -148
- package/src/static-analysis-redundant-rules.ts +298 -41
- package/src/test-block-rules.ts +422 -228
- package/src/text-scans.ts +67 -9
- package/src/types.ts +222 -71
- package/tsconfig.json +2 -1
- package/src/process-exec-metadata.ts +0 -153
- package/src/test-fixtures.ts +0 -668
package/src/cli-program.ts
CHANGED
|
@@ -1,21 +1,30 @@
|
|
|
1
|
-
//
|
|
1
|
+
// Connects the user's command and flags to analysis, output, and exit status.
|
|
2
|
+
//
|
|
3
|
+
// Use analyse for individual findings, summary for overall patterns, and report for an artifact to share.
|
|
4
|
+
// Machine-readable output carries the same run status that automation receives from the process.
|
|
2
5
|
import { Command, Help, InvalidArgumentError } from "commander";
|
|
3
6
|
import { readFileSync, writeFileSync } from "node:fs";
|
|
4
|
-
import { resolve } from "node:path";
|
|
7
|
+
import { dirname, extname, resolve } from "node:path";
|
|
5
8
|
import { performance } from "node:perf_hooks";
|
|
6
9
|
import { cwd } from "node:process";
|
|
10
|
+
import { CONFIG_ERROR_DIAGNOSTIC_TYPE, failedRunReport, projectRootFromTargets, TARGET_ERROR_DIAGNOSTIC_TYPE, targetOutsideLaunchDirectory } from "./analyser.ts";
|
|
7
11
|
import { DEFAULT_BASELINE } from "./baseline.ts";
|
|
12
|
+
import { BaselineFileError } from "./baseline-file.ts";
|
|
13
|
+
import { BaselineIdentityError } from "./baseline-identity.ts";
|
|
8
14
|
import { checkIgnore, checkIgnoreExitCode, renderCheckIgnore, type CheckIgnoreFormat } from "./check-ignore.ts";
|
|
15
|
+
import { CHANGED_REGION_DIAGNOSTIC_TYPE, ChangedRegionError } from "./changed-regions.ts";
|
|
9
16
|
import { ConfigLoadError } from "./config-load-error.ts";
|
|
10
17
|
import { loadConfig, minimumSeverityFor } from "./config.ts";
|
|
11
18
|
import { VERSION } from "./constants.ts";
|
|
12
19
|
import { startDashboard } from "./dashboard.ts";
|
|
13
|
-
import { renderHookCapabilities, renderHookConfigError, renderHookReport } from "./hook-contract.ts";
|
|
20
|
+
import { hookExitCode, renderHookCapabilities, renderHookConfigError, renderHookFatal, renderHookReport, type HookExitGate } from "./hook-contract.ts";
|
|
14
21
|
import { promptYesNo, shouldPromptForInit, writeDefaultConfig } from "./init-config.ts";
|
|
22
|
+
import { migrateConfigText } from "./migrate-config.ts";
|
|
15
23
|
import { renderReport, renderSummary, renderSummaryJson } from "./report-renderers.ts";
|
|
16
24
|
import { completionShell, getRuleDescriptor, renderCompletionScript, renderConsoleList, renderProfileList, renderRuleDetail, renderRuleList, type RuleListFormat } from "./rule-list.ts";
|
|
17
|
-
import { exitFor } from "./scoring.ts";
|
|
18
|
-
import
|
|
25
|
+
import { exitFor, summarize } from "./scoring.ts";
|
|
26
|
+
import { applyDisplaySelectors, isExecutionRequested, validateDisplaySelectors, type DisplaySelectors } from "./selectors.ts";
|
|
27
|
+
import type { AnalysisOptions, AnalysisReport, Confidence, DeepScanBudgetOverride, ExecutionSelectors, MinimumSeverityCommand, Severity } from "./types.ts";
|
|
19
28
|
|
|
20
29
|
type HookAnalysisViews = { currentReport: AnalysisReport; scopedReport: AnalysisReport };
|
|
21
30
|
type AnalyseRunner = ((options: AnalysisOptions) => AnalysisReport) & {
|
|
@@ -28,12 +37,26 @@ interface NormalizeContext {
|
|
|
28
37
|
shouldAllowBaselineFlag: boolean;
|
|
29
38
|
}
|
|
30
39
|
|
|
40
|
+
/*
|
|
41
|
+
* What a command reports when the user's invocation could not be understood: an unknown flag, a stray operand, a
|
|
42
|
+
* value outside a documented set. Distinct from 1, which means the scan ran and something reached the gate.
|
|
43
|
+
*/
|
|
44
|
+
const USAGE_EXIT_CODE = 2;
|
|
45
|
+
|
|
46
|
+
// Help for the flag every port accepts and no port implements, so `--help` says so rather than implying it works.
|
|
47
|
+
const SCAN_TIMEOUT_DESCRIPTION = "Parsed and accepted for cross-port compatibility; gruff-ts enforces no scan deadline on analyse.";
|
|
48
|
+
|
|
31
49
|
// Shared `--profile` flag help for analyse/report/summary/dashboard. The value is a built-in profile
|
|
32
50
|
// name or a profile file path; it overrides any config-file `profile:` block (CLI wins, per ADR-010).
|
|
33
51
|
const PROFILE_OPTION_DESCRIPTION = "Apply a built-in profile (gruff.minimal, gruff.recommended, gruff.strict) or a profile file path. Overrides a config-file profile:.";
|
|
34
52
|
|
|
35
|
-
|
|
36
|
-
|
|
53
|
+
/**
|
|
54
|
+
* Writes output to stdout unless suppressed by the program's flags, ensuring a trailing newline.
|
|
55
|
+
*
|
|
56
|
+
* @param program - root command whose silent and quiet flags govern whether stdout is written
|
|
57
|
+
* @param output - text to write to stdout with a trailing newline appended when missing
|
|
58
|
+
* @returns Nothing. Writes to stdout when output is enabled.
|
|
59
|
+
*/
|
|
37
60
|
function writeCommandOutput(program: Command, output: string): void {
|
|
38
61
|
if (outputSuppressed(program)) {
|
|
39
62
|
return;
|
|
@@ -41,31 +64,44 @@ function writeCommandOutput(program: Command, output: string): void {
|
|
|
41
64
|
process.stdout.write(output.endsWith("\n") ? output : `${output}\n`);
|
|
42
65
|
}
|
|
43
66
|
|
|
44
|
-
|
|
45
|
-
|
|
67
|
+
/**
|
|
68
|
+
* Checks whether non-error stdout is suppressed. `--silent` and `--quiet` are intentionally treated
|
|
69
|
+
* the same here because Commander exposes them as independent flags but the CLI's contract is uniform.
|
|
70
|
+
*
|
|
71
|
+
* @param program - root command providing the parsed quiet and silent flags
|
|
72
|
+
* @returns True when either quiet or silent is enabled; otherwise false.
|
|
73
|
+
*/
|
|
46
74
|
function outputSuppressed(program: Command): boolean {
|
|
47
75
|
const options = program.opts() as { quiet?: boolean; silent?: boolean };
|
|
48
76
|
return options.quiet === true || options.silent === true;
|
|
49
77
|
}
|
|
50
78
|
|
|
51
79
|
// Per-command config-loading state passed into maybePromptInitConfig. analyse/summary/report
|
|
52
|
-
// take
|
|
80
|
+
// take these flags from normalizeOptions; dashboard has no equivalent flags so it passes
|
|
53
81
|
// `{ shouldSkipConfig: false, hasExplicitConfig: false }`.
|
|
54
82
|
interface InitPromptOptions {
|
|
55
83
|
shouldSkipConfig: boolean;
|
|
56
84
|
hasExplicitConfig: boolean;
|
|
85
|
+
isMachineFormat?: boolean;
|
|
57
86
|
}
|
|
58
87
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
88
|
+
/**
|
|
89
|
+
* Offers to create a missing default config at the target root when interaction flags, config flags, and TTYs permit.
|
|
90
|
+
* On acceptance, attempts a filesystem write with overwrite disabled and reports a newly written file on stderr;
|
|
91
|
+
* call before analysis so loadConfig can use the new file during the same invocation.
|
|
92
|
+
*
|
|
93
|
+
* @param program - root command supplying interaction and output-suppression flags
|
|
94
|
+
* @param projectRoot - directory checked for an existing config and used as the write target
|
|
95
|
+
* @param options - per-command config-loading flags controlling whether prompting is skipped
|
|
96
|
+
* @returns A promise that resolves without a value after checking, prompting, or writing the config.
|
|
97
|
+
*/
|
|
63
98
|
async function maybePromptInitConfig(program: Command, projectRoot: string, options: InitPromptOptions): Promise<void> {
|
|
64
99
|
const programOptions = program.opts() as { interaction?: boolean };
|
|
65
100
|
const context = {
|
|
66
101
|
projectRoot,
|
|
67
102
|
shouldSkipConfig: options.shouldSkipConfig,
|
|
68
103
|
hasExplicitConfig: options.hasExplicitConfig,
|
|
104
|
+
...(options.isMachineFormat === undefined ? {} : { isMachineFormat: options.isMachineFormat }),
|
|
69
105
|
isInteractionAllowed: programOptions.interaction !== false,
|
|
70
106
|
isOutputSuppressed: outputSuppressed(program),
|
|
71
107
|
isStdinTty: process.stdin.isTTY === true,
|
|
@@ -85,14 +121,24 @@ async function maybePromptInitConfig(program: Command, projectRoot: string, opti
|
|
|
85
121
|
}
|
|
86
122
|
}
|
|
87
123
|
|
|
88
|
-
|
|
89
|
-
|
|
124
|
+
/**
|
|
125
|
+
* Works out whether a scan may offer to create a missing config: never with --no-config, --config, or machine-readable output.
|
|
126
|
+
*
|
|
127
|
+
* @param options - normalized analysis options carrying config opt-out, path selection, and output format
|
|
128
|
+
* @returns Prompt settings: config skipped, config path given explicitly, and machine-readable output (JSON, SARIF, GitHub or hotspot).
|
|
129
|
+
*/
|
|
90
130
|
function promptOptionsFromAnalysis(options: AnalysisOptions): InitPromptOptions {
|
|
91
|
-
|
|
131
|
+
const isMachineFormat = options.format === "json" || options.format === "sarif" || options.format === "github" || options.format === "hotspot";
|
|
132
|
+
return { shouldSkipConfig: options.shouldSkipConfig, hasExplicitConfig: typeof options.config === "string", isMachineFormat };
|
|
92
133
|
}
|
|
93
134
|
|
|
94
|
-
|
|
95
|
-
|
|
135
|
+
/**
|
|
136
|
+
* Determines whether ANSI colour output is enabled, favouring explicit flags over TTY detection.
|
|
137
|
+
* Disabling automatic colour for redirected output keeps escape codes out of files and CI logs.
|
|
138
|
+
*
|
|
139
|
+
* @param program - root command providing explicit `--ansi` or `--no-ansi` flag state
|
|
140
|
+
* @returns True when ANSI is explicitly enabled or stdout is a TTY without `--no-ansi`; otherwise false.
|
|
141
|
+
*/
|
|
96
142
|
function ansiEnabled(program: Command): boolean {
|
|
97
143
|
const options = program.opts() as { ansi?: boolean };
|
|
98
144
|
if (options.ansi === true) {
|
|
@@ -104,8 +150,13 @@ function ansiEnabled(program: Command): boolean {
|
|
|
104
150
|
return process.stdout.isTTY === true;
|
|
105
151
|
}
|
|
106
152
|
|
|
107
|
-
|
|
108
|
-
|
|
153
|
+
/**
|
|
154
|
+
* Builds the root CLI program and registers every gruff-ts subcommand. The runner is injected rather than
|
|
155
|
+
* imported to keep `cli-program.ts` off the analyser's dependency graph (see `.goat-flow/learning-loop/lessons/verification.md`).
|
|
156
|
+
*
|
|
157
|
+
* @param runAnalyse - analysis runner callback invoked by commands that execute scans or serve the dashboard
|
|
158
|
+
* @returns The configured root Commander program with all subcommands registered.
|
|
159
|
+
*/
|
|
109
160
|
export function buildProgram(runAnalyse: AnalyseRunner): Command {
|
|
110
161
|
const program = new Command();
|
|
111
162
|
configureRootProgram(program);
|
|
@@ -115,6 +166,7 @@ export function buildProgram(runAnalyse: AnalyseRunner): Command {
|
|
|
115
166
|
registerDashboardCommand(program, runAnalyse);
|
|
116
167
|
registerHookCommand(program, runAnalyse);
|
|
117
168
|
registerInitCommand(program);
|
|
169
|
+
registerMigrateConfigCommand(program);
|
|
118
170
|
registerListCommand(program);
|
|
119
171
|
registerListProfilesCommand(program);
|
|
120
172
|
registerListRulesCommand(program);
|
|
@@ -123,9 +175,13 @@ export function buildProgram(runAnalyse: AnalyseRunner): Command {
|
|
|
123
175
|
return program;
|
|
124
176
|
}
|
|
125
177
|
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
178
|
+
/**
|
|
179
|
+
* Configures global CLI flags, help formatting, and the bare-invocation command catalogue action.
|
|
180
|
+
* The exit override preserves successful help and version exits and maps nonzero Commander exit codes to status 2.
|
|
181
|
+
*
|
|
182
|
+
* @param program - root Commander instance to configure with global options and exit behaviour
|
|
183
|
+
* @returns Nothing. Mutates the root program in place before subcommands are registered.
|
|
184
|
+
*/
|
|
129
185
|
function configureRootProgram(program: Command): void {
|
|
130
186
|
program
|
|
131
187
|
.name("gruff-ts")
|
|
@@ -140,10 +196,21 @@ function configureRootProgram(program: Command): void {
|
|
|
140
196
|
.option("-v, --verbose", "Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug", (_value, previous: number) => previous + 1, 0)
|
|
141
197
|
.addHelpCommand("help [command]", "Display help for a command")
|
|
142
198
|
.showHelpAfterError()
|
|
199
|
+
// Set before the subcommands are registered, because each one copies the root's exit behaviour as it is built.
|
|
200
|
+
.exitOverride((error) => {
|
|
201
|
+
// Help and version are successful output, so they keep the zero commander already chose for them.
|
|
202
|
+
process.exit(error.exitCode === 0 ? 0 : USAGE_EXIT_CODE);
|
|
203
|
+
})
|
|
143
204
|
.configureHelp({
|
|
144
205
|
|
|
145
|
-
|
|
146
|
-
|
|
206
|
+
/**
|
|
207
|
+
* Formats help text using the helper's layout settings and the captured root program.
|
|
208
|
+
* Root help lists the command catalogue; subcommands use Commander's formatter with global options visible.
|
|
209
|
+
*
|
|
210
|
+
* @param command - command whose help text is being rendered
|
|
211
|
+
* @param helper - Commander help formatter supplying wrap width settings
|
|
212
|
+
* @returns The formatted help output for either the root catalogue or a subcommand.
|
|
213
|
+
*/
|
|
147
214
|
formatHelp(command, helper) {
|
|
148
215
|
return rootHelpText(program, command, helper);
|
|
149
216
|
},
|
|
@@ -153,8 +220,14 @@ function configureRootProgram(program: Command): void {
|
|
|
153
220
|
});
|
|
154
221
|
}
|
|
155
222
|
|
|
156
|
-
|
|
157
|
-
|
|
223
|
+
/**
|
|
224
|
+
* Returns the command catalogue for root help, or Commander's subcommand help with global options visible.
|
|
225
|
+
*
|
|
226
|
+
* @param program - root command used to detect root help and supply ANSI colour settings
|
|
227
|
+
* @param command - help target command being formatted
|
|
228
|
+
* @param helper - Commander help instance supplying optional wrap width settings
|
|
229
|
+
* @returns Rendered command catalogue for the root command, or formatted help text for a subcommand.
|
|
230
|
+
*/
|
|
158
231
|
function rootHelpText(program: Command, command: Command, helper: Help): string {
|
|
159
232
|
if (command === program) {
|
|
160
233
|
return renderConsoleList(ansiEnabled(program));
|
|
@@ -170,11 +243,105 @@ function rootHelpText(program: Command, command: Command, helper: Help): string
|
|
|
170
243
|
return defaultHelp.formatHelp(command, defaultHelp);
|
|
171
244
|
}
|
|
172
245
|
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
246
|
+
/**
|
|
247
|
+
* Register the CLI command that upgrades a 0.5 configuration to the current schema.
|
|
248
|
+
*
|
|
249
|
+
* @param program - parent CLI command that receives the migration subcommand
|
|
250
|
+
* @returns Nothing. Adds the subcommand, its input, output and dry-run options, and the migration action to the program.
|
|
251
|
+
*/
|
|
252
|
+
function registerMigrateConfigCommand(program: Command): void {
|
|
253
|
+
program
|
|
254
|
+
.command("migrate-config")
|
|
255
|
+
.description("Rewrite a 0.5 config for the current schema, writing the result to a different file.")
|
|
256
|
+
.requiredOption("--config <path>", "The 0.5 config to read. It is never modified.")
|
|
257
|
+
.option("--output <path>", "New file for the migrated config. Required unless --dry-run.")
|
|
258
|
+
.option("--dry-run", "Print what would change and write nothing.")
|
|
259
|
+
.action((rawOptions: Record<string, unknown>) => runWithConfigErrorHandling(() => runMigrateConfig(program, rawOptions)));
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Previews or writes the migrated config requested by `migrate-config`.
|
|
264
|
+
* Side effects: reads the input config, writes stdout, and writes one new file on the filesystem when `--output` is supplied.
|
|
265
|
+
*
|
|
266
|
+
* @param program - root command whose output flags govern stdout printing
|
|
267
|
+
* @param rawOptions - parsed flags providing `--config`, `--output`, and `--dry-run`
|
|
268
|
+
* @returns Nothing. Prints migration details, sets exit code 2 when `--output` is missing without `--dry-run`, or writes the migrated file.
|
|
269
|
+
* @throws {ConfigLoadError} when the input, format, or destination prevents migration.
|
|
270
|
+
*/
|
|
271
|
+
function runMigrateConfig(program: Command, rawOptions: Record<string, unknown>): void {
|
|
272
|
+
const inputPath = resolve(String(rawOptions.config));
|
|
273
|
+
const inputFormat = migrationConfigFormat(inputPath);
|
|
274
|
+
let source: string;
|
|
275
|
+
try {
|
|
276
|
+
source = readFileSync(inputPath, "utf8");
|
|
277
|
+
} catch (error) {
|
|
278
|
+
// A user may pass `--config old.yaml` from a directory that has no such file.
|
|
279
|
+
throw new ConfigLoadError(`Cannot read migration input ${inputPath}: ${(error as NodeJS.ErrnoException).code ?? "read failed"}.`, "Pass a readable config file to --config.");
|
|
280
|
+
}
|
|
281
|
+
const migration = migrateConfigText(source, inputFormat, dirname(inputPath));
|
|
282
|
+
// An empty change list tells the user their configuration settings are already current.
|
|
283
|
+
const summary = migration.changes.length === 0
|
|
284
|
+
? `${inputPath} is already current; no changes.`
|
|
285
|
+
: ["Migration changes:", ...migration.changes.map((change) => ` - line ${change.line}: ${change.description}`)].join("\n");
|
|
286
|
+
|
|
287
|
+
// A dry run shows what to expect before the user chooses a destination.
|
|
288
|
+
if (rawOptions.dryRun === true) {
|
|
289
|
+
writeCommandOutput(program, summary);
|
|
290
|
+
writeCommandOutput(program, `Dry run: nothing written.`);
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
const outputPath = typeof rawOptions.output === "string" ? resolve(rawOptions.output) : "";
|
|
295
|
+
|
|
296
|
+
// With no destination, show how to supply a path or preview the changes.
|
|
297
|
+
if (outputPath.length === 0) {
|
|
298
|
+
process.stderr.write("gruff-ts: migrate-config needs --output <path>, or --dry-run to print the changes.\n");
|
|
299
|
+
process.exitCode = USAGE_EXIT_CODE;
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
// A user upgrading old.yaml needs a YAML destination so its existing syntax still loads.
|
|
303
|
+
if (migrationConfigFormat(outputPath) !== inputFormat) {
|
|
304
|
+
throw new ConfigLoadError("The migration output must use the input config's format.", "Choose a new output path with a matching YAML or JSON extension.");
|
|
305
|
+
}
|
|
306
|
+
try {
|
|
307
|
+
// Exclusive creation refuses every existing directory entry, including aliases of the input.
|
|
308
|
+
writeFileSync(outputPath, migration.text, { flag: "wx" });
|
|
309
|
+
} catch (error) {
|
|
310
|
+
// For example, a user may select the same destination twice or choose a read-only directory.
|
|
311
|
+
throw new ConfigLoadError(`Cannot create migration output ${outputPath}: ${(error as NodeJS.ErrnoException).code ?? "write failed"}.`, "Choose a new output file in a writable directory.");
|
|
312
|
+
}
|
|
313
|
+
writeCommandOutput(program, summary);
|
|
314
|
+
writeCommandOutput(program, `Wrote ${outputPath}.`);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Selects the migration encoding from a supported config extension.
|
|
319
|
+
*
|
|
320
|
+
* @param path - filesystem path to the source or destination configuration file
|
|
321
|
+
* @returns `"yaml"` for `.yaml`/`.yml` paths or `"json"` for `.json` paths.
|
|
322
|
+
* @throws {ConfigLoadError} for an unsupported extension.
|
|
323
|
+
*/
|
|
324
|
+
function migrationConfigFormat(path: string): "yaml" | "json" {
|
|
325
|
+
const extension = extname(path).toLowerCase();
|
|
326
|
+
// Both common YAML suffixes are valid when the user names a source or destination.
|
|
327
|
+
if (extension === ".yaml" || extension === ".yml") {
|
|
328
|
+
return "yaml";
|
|
329
|
+
}
|
|
330
|
+
// A project with a JSON config can review the migration in the same format.
|
|
331
|
+
if (extension === ".json") {
|
|
332
|
+
return "json";
|
|
333
|
+
}
|
|
334
|
+
throw new ConfigLoadError(`Unsupported migration config extension: ${extension || "(none)"}.`, "Use a .yaml, .yml, or .json config file.");
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Registers the `analyse` subcommand for users who want individual findings in the terminal or a machine-readable report.
|
|
339
|
+
* The default gate fails on advisory or higher; users can set `--fail-on=error` or configure `failOn.analyse`.
|
|
340
|
+
*
|
|
341
|
+
* @param program - root command that receives the `analyse` subcommand
|
|
342
|
+
* @param runAnalyse - analysis runner invoked to scan the requested targets
|
|
343
|
+
* @returns Nothing. Registers options and the action handler on the root program.
|
|
344
|
+
*/
|
|
178
345
|
function registerAnalyseCommand(program: Command, runAnalyse: AnalyseRunner): void {
|
|
179
346
|
program
|
|
180
347
|
.command("analyse")
|
|
@@ -183,34 +350,67 @@ function registerAnalyseCommand(program: Command, runAnalyse: AnalyseRunner): vo
|
|
|
183
350
|
.option("--config <path>", "Path to a gruff YAML config file.")
|
|
184
351
|
.option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
|
|
185
352
|
.option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
|
|
186
|
-
.option("--
|
|
187
|
-
.option("--
|
|
353
|
+
.option("--deep-scan-budget <lines:bytes|off>", "Override both deep-scan bounds as LINES:BYTES, or disable the budget with off.", parseDeepScanBudget)
|
|
354
|
+
.option("--format <format>", "Output format: text, json, html, markdown, github, hotspot, or sarif.", parseAnalyseFormat, "text")
|
|
355
|
+
.option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", parseFailOn, "advisory")
|
|
356
|
+
.option("--min-confidence <confidence>", "Lowest analyser confidence that may fail the run: low, medium, or high. Filters nothing.", parseConfidence, "low")
|
|
357
|
+
.option("--min-severity <severity>", "Hide findings below this severity from the report. The score and the exit code are unchanged.", parseMinSeverity)
|
|
358
|
+
.option("--include-rule <ids>", "Run only these rules, so the score reflects them alone. Repeatable, or comma-separated.", collectSelectorList, [])
|
|
359
|
+
.option("--exclude-rule <ids>", "Do not run these rules, so they cannot affect the score. Repeatable, or comma-separated.", collectSelectorList, [])
|
|
360
|
+
.option("--include-pillar <names>", "Run only these pillars, so the score reflects them alone. Repeatable, or comma-separated.", collectSelectorList, [])
|
|
361
|
+
.option("--exclude-pillar <names>", "Do not run these pillars, so they cannot affect the score. Repeatable, or comma-separated.", collectSelectorList, [])
|
|
362
|
+
.option("--show-rule <ids>", "Show only these rules in the report. Every rule still runs and still scores. Repeatable, or comma-separated.", collectSelectorList, [])
|
|
363
|
+
.option("--hide-rule <ids>", "Hide these rules from the report. They still run and still score. Repeatable, or comma-separated.", collectSelectorList, [])
|
|
364
|
+
.option("--show-pillar <names>", "Show only these pillars in the report. Every pillar still runs and still scores. Repeatable, or comma-separated.", collectSelectorList, [])
|
|
365
|
+
.option("--hide-pillar <names>", "Hide these pillars from the report. They still run and still score. Repeatable, or comma-separated.", collectSelectorList, [])
|
|
366
|
+
.option("--scan-timeout <duration>", SCAN_TIMEOUT_DESCRIPTION)
|
|
188
367
|
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
189
368
|
.option("--changed-ranges <ranges>", "Filter findings to changed regions, for example 3-3,8-10.")
|
|
190
369
|
.option("--since <ref>", "Filter findings to regions changed against a git base ref.")
|
|
191
370
|
.option("--diff [mode]", "Filter findings to changed regions. Use working-tree, staged, unstaged, a base ref, or - for unified diff on stdin.")
|
|
192
|
-
.option("--
|
|
193
|
-
.option("--
|
|
371
|
+
.option("--diff-base <ref>", "The ref a diff is taken against. Equivalent to passing the ref to --diff, and it wins when both are given.")
|
|
372
|
+
.option("--changed-scope <scope>", "Changed-region scope: hunk, symbol, or file.", parseChangedScope, "symbol")
|
|
373
|
+
.option("--history-file <path>", "Append score trend history to this JSON file (full scans only; incompatible with --diff, --since, and --changed-ranges, or rule/pillar execution selectors).")
|
|
194
374
|
.option("--baseline [path]", "Suppress findings that match a gruff baseline JSON file.")
|
|
195
375
|
.option("--generate-baseline [path]", "Write current findings to a gruff baseline JSON file.")
|
|
376
|
+
.option("--migrate-baseline <path>", "Carry a 0.5 baseline's reviews into --generate-baseline; the original file is left untouched.")
|
|
377
|
+
.option("--force", "Overwrite a 0.5 baseline at the default path; without it a generate that would destroy the retreat path is refused.")
|
|
196
378
|
.option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
|
|
379
|
+
.option("--fail-on-new", "Exit 1 when the applied baseline leaves any finding the user has not reviewed, whatever its severity.")
|
|
197
380
|
.action(async (paths: string[], rawOptions: Record<string, unknown>, command: Command) => {
|
|
381
|
+
const outsideTarget = targetOutsideLaunchDirectory(paths);
|
|
382
|
+
// A multi-target run with any outside target exits 2 before scanning. JSON and SARIF callers get a refusal envelope when stdout is enabled.
|
|
383
|
+
if (outsideTarget !== null) {
|
|
384
|
+
refuseTargetsOutsideLaunchDirectory(program, rawOptions.format, outsideTarget);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
198
387
|
await runWithConfigErrorHandling(async () => {
|
|
388
|
+
// Validate display selector names before scanning so a typo exits 2 without writing a baseline or running analysis.
|
|
389
|
+
validateDisplaySelectors(displaySelectorsFrom(rawOptions));
|
|
199
390
|
const baseOptions = normalizeOptions(paths, rawOptions, { shouldAllowBaselineFlag: true });
|
|
200
|
-
const
|
|
201
|
-
|
|
391
|
+
const configured = configuredSeverities(baseOptions, "analyse", command);
|
|
392
|
+
const options = configured.options;
|
|
393
|
+
await maybePromptInitConfig(program, projectRootFromTargets(options.paths), promptOptionsFromAnalysis(options));
|
|
202
394
|
const report = runAnalyse(options);
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
395
|
+
const findingExit = exitFor(report, options.failOn, confidenceFloor(rawOptions));
|
|
396
|
+
// A failed scan keeps exit 2. A successful scan can still fail either the severity gate or the new-finding gate.
|
|
397
|
+
const status = findingExit === 2 ? findingExit : Math.max(findingExit, newDebtExitCode(report, rawOptions));
|
|
398
|
+
process.exitCode = status;
|
|
399
|
+
writeChangedRegionFailure(report, options.format);
|
|
400
|
+
// A user can narrow the visible findings while CI keeps the exit status calculated from the full evaluated set.
|
|
401
|
+
filterReportForDisplay(report, rawOptions, configured.displayFloor);
|
|
402
|
+
writeCommandOutput(program, renderReport(report, options.format, status));
|
|
403
|
+
}, (error) => writeFailedRunEnvelope(program, rawOptions.format, error));
|
|
206
404
|
});
|
|
207
405
|
}
|
|
208
406
|
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
407
|
+
/**
|
|
408
|
+
* Registers `check-ignore` to classify paths with `analyse`'s ignore rules and set exit status 0, 1, or 2.
|
|
409
|
+
* When output is enabled, JSON reports every path and text lists only ignored paths with their match details.
|
|
410
|
+
*
|
|
411
|
+
* @param program - root command that receives the `check-ignore` subcommand
|
|
412
|
+
* @returns Nothing. Attaches the subcommand, its config/format flags, and the ignore-check action to the program.
|
|
413
|
+
*/
|
|
214
414
|
function registerCheckIgnoreCommand(program: Command): void {
|
|
215
415
|
program
|
|
216
416
|
.command("check-ignore")
|
|
@@ -229,24 +429,37 @@ function registerCheckIgnoreCommand(program: Command): void {
|
|
|
229
429
|
});
|
|
230
430
|
}
|
|
231
431
|
|
|
232
|
-
|
|
233
|
-
|
|
432
|
+
/**
|
|
433
|
+
* Registers `hook` for coding agents to review an edit and apply a project gate using the JSON response.
|
|
434
|
+
* Invariant: a refused input or missing required baseline produces an envelope and exit 2; config failures include a suggested next step.
|
|
435
|
+
*
|
|
436
|
+
* @param program - root command that receives the `hook` subcommand
|
|
437
|
+
* @param runAnalyse - analysis runner used to evaluate current and scoped views for the hook payload
|
|
438
|
+
* @returns Nothing. Registers the hook subcommand and its action handler.
|
|
439
|
+
* @throws {unknown} - from the registered action when the caught failure is not an Error.
|
|
440
|
+
*/
|
|
234
441
|
function registerHookCommand(program: Command, runAnalyse: AnalyseRunner): void {
|
|
235
442
|
program
|
|
236
443
|
.command("hook")
|
|
237
|
-
.description("Run the gruff agent-hook contract and emit gruff.hook.
|
|
444
|
+
.description("Run the gruff agent-hook contract and emit gruff.hook.v2 JSON.")
|
|
238
445
|
.argument("[paths...]", "Files or directories to analyse.")
|
|
239
446
|
.option("--format <format>", "Output format: json.", parseHookFormat, "json")
|
|
240
|
-
.option("--capabilities", "Print gruff.hook.
|
|
447
|
+
.option("--capabilities", "Print gruff.hook.v2 capability metadata and exit.")
|
|
448
|
+
.option("--fail-on <severity>", "Finding severity that blocks the edit: advisory, warning, error, or none. The hook default of none keeps findings advisory.", parseFailOn, "none")
|
|
449
|
+
.option("--min-confidence <confidence>", "Lowest analyser confidence that may block the edit: low, medium, or high.", parseConfidence, "low")
|
|
450
|
+
.option("--fail-on-new", "Block the edit when a finding the applied baseline calls new is published.")
|
|
241
451
|
.option("--config <path>", "Path to a gruff YAML config file.")
|
|
242
452
|
.option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
|
|
243
453
|
.option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
|
|
454
|
+
.option("--deep-scan-budget <lines:bytes|off>", "Override both deep-scan bounds as LINES:BYTES, or disable the budget with off.", parseDeepScanBudget)
|
|
244
455
|
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
245
456
|
.option("--changed-ranges <ranges>", "Filter hook findings to changed regions, for example 3-3,8-10.")
|
|
246
457
|
.option("--since <ref>", "Filter hook findings to regions changed against a git base ref and compare against that ref.")
|
|
247
458
|
.option("--diff [mode]", "Filter hook findings to changed regions. Use working-tree, staged, unstaged, a base ref, or - for unified diff on stdin.")
|
|
248
459
|
.option("--baseline <path>", "Compare hook findings against a gruff baseline JSON file using stableIdentity.")
|
|
460
|
+
.option("--fail-on-diagnostics", "Exit 1 when parse diagnostics affect the analysed change; the default reports them in-band with exit 0. An unreadable input always exits 2.")
|
|
249
461
|
.action((paths: string[], rawOptions: Record<string, unknown>) => {
|
|
462
|
+
// An integration can discover supported options before sending any files to scan.
|
|
250
463
|
if (rawOptions.capabilities === true) {
|
|
251
464
|
writeCommandOutput(program, renderHookCapabilities());
|
|
252
465
|
process.exitCode = 0;
|
|
@@ -254,27 +467,44 @@ function registerHookCommand(program: Command, runAnalyse: AnalyseRunner): void
|
|
|
254
467
|
}
|
|
255
468
|
try {
|
|
256
469
|
const scopedOptions = hookScopedOptions(paths, rawOptions);
|
|
470
|
+
const outsideTarget = targetOutsideLaunchDirectory(scopedOptions.paths);
|
|
471
|
+
// A request naming several files must be launched from a directory containing them all.
|
|
472
|
+
if (outsideTarget !== null) {
|
|
473
|
+
writeCommandOutput(program, renderHookFatal(TARGET_ERROR_DIAGNOSTIC_TYPE, outsideTargetMessage(outsideTarget)));
|
|
474
|
+
process.exitCode = USAGE_EXIT_CODE;
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
const baseline = hookBaselinePath(rawOptions);
|
|
478
|
+
// A user needs to choose a review file before the hook can gate on findings they have yet to review.
|
|
479
|
+
if (rawOptions.failOnNew === true && baseline.baselinePath === undefined) {
|
|
480
|
+
writeCommandOutput(program, renderHookFatal("baseline-error", "--fail-on-new requires --baseline <path>."));
|
|
481
|
+
process.exitCode = USAGE_EXIT_CODE;
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
257
484
|
const currentOptions = hookCurrentOptions(scopedOptions);
|
|
258
|
-
|
|
485
|
+
const rendered = renderHookReport(runAnalyse, {
|
|
259
486
|
currentOptions,
|
|
260
487
|
scopedOptions,
|
|
261
|
-
...
|
|
488
|
+
...baseline,
|
|
262
489
|
...hookDiffBase(scopedOptions),
|
|
263
490
|
hasChangedRegion: hasHookChangedRegion(scopedOptions),
|
|
264
|
-
})
|
|
265
|
-
|
|
491
|
+
});
|
|
492
|
+
writeCommandOutput(program, rendered);
|
|
493
|
+
// Read findings and diagnostics from the rendered payload so the gate uses the same results as the report.
|
|
494
|
+
process.exitCode = hookExitCode(rendered, hookGateFrom(rawOptions));
|
|
266
495
|
} catch (error) {
|
|
496
|
+
// A project may still use an older config schema. Give the integration the loader's instructions.
|
|
267
497
|
if (error instanceof ConfigLoadError) {
|
|
268
498
|
writeCommandOutput(program, renderHookConfigError(error.message, error.suggestion));
|
|
269
|
-
process.exitCode =
|
|
499
|
+
process.exitCode = USAGE_EXIT_CODE;
|
|
270
500
|
return;
|
|
271
501
|
}
|
|
502
|
+
// A missing review file, for example, is a fatal diagnostic in the hook's standard response.
|
|
272
503
|
if (error instanceof Error) {
|
|
273
|
-
//
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
process.exitCode = 2;
|
|
504
|
+
// Render a fatal diagnostic under the gruff.hook.v2 schema so consumers can read the failure when stdout is enabled.
|
|
505
|
+
writeCommandOutput(program, renderHookFatal(hookFatalType(error), error.message));
|
|
506
|
+
process.stderr.write(`gruff-ts: ${error.message}\n`);
|
|
507
|
+
process.exitCode = USAGE_EXIT_CODE;
|
|
278
508
|
return;
|
|
279
509
|
}
|
|
280
510
|
throw error;
|
|
@@ -282,9 +512,14 @@ function registerHookCommand(program: Command, runAnalyse: AnalyseRunner): void
|
|
|
282
512
|
});
|
|
283
513
|
}
|
|
284
514
|
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
515
|
+
/**
|
|
516
|
+
* Builds analysis options for checking paths against ignore rules, matching `analyse` config selection and skipping baselines.
|
|
517
|
+
* Git and fallback ignore checks stay enabled for eligible paths while existing explicit files bypass them.
|
|
518
|
+
*
|
|
519
|
+
* @param paths - target paths supplied to `check-ignore`
|
|
520
|
+
* @param rawOptions - parsed CLI flags used to select or skip configuration loading
|
|
521
|
+
* @returns Analysis options configured for the ignore-check contract with baselines disabled.
|
|
522
|
+
*/
|
|
288
523
|
function checkIgnoreOptions(paths: string[], rawOptions: Record<string, unknown>): AnalysisOptions {
|
|
289
524
|
return {
|
|
290
525
|
paths,
|
|
@@ -298,8 +533,12 @@ function checkIgnoreOptions(paths: string[], rawOptions: Record<string, unknown>
|
|
|
298
533
|
};
|
|
299
534
|
}
|
|
300
535
|
|
|
301
|
-
|
|
302
|
-
|
|
536
|
+
/**
|
|
537
|
+
* Registers `completion` to emit the selected shell's completion script to stdout, defaulting to bash.
|
|
538
|
+
*
|
|
539
|
+
* @param program - root command that receives the `completion` subcommand
|
|
540
|
+
* @returns Nothing. Adds the subcommand whose action writes the completion script when stdout is enabled.
|
|
541
|
+
*/
|
|
303
542
|
function registerCompletionCommand(program: Command): void {
|
|
304
543
|
program
|
|
305
544
|
.command("completion")
|
|
@@ -310,8 +549,14 @@ function registerCompletionCommand(program: Command): void {
|
|
|
310
549
|
});
|
|
311
550
|
}
|
|
312
551
|
|
|
313
|
-
|
|
314
|
-
|
|
552
|
+
/**
|
|
553
|
+
* Registers `dashboard`, defaulting to `127.0.0.1:8767` because the unauthenticated dashboard accepts a caller-selected projectRoot.
|
|
554
|
+
* The action may write config after an interactive prompt before starting the server.
|
|
555
|
+
*
|
|
556
|
+
* @param program - root command that receives the `dashboard` subcommand
|
|
557
|
+
* @param runAnalyse - analysis runner passed to the dashboard server for requested scans
|
|
558
|
+
* @returns Nothing. Registers the dashboard subcommand and its startup action.
|
|
559
|
+
*/
|
|
315
560
|
function registerDashboardCommand(program: Command, runAnalyse: AnalyseRunner): void {
|
|
316
561
|
program
|
|
317
562
|
.command("dashboard")
|
|
@@ -320,17 +565,24 @@ function registerDashboardCommand(program: Command, runAnalyse: AnalyseRunner):
|
|
|
320
565
|
.option("--port <port>", "Port to bind.", "8767")
|
|
321
566
|
.option("--project-root <path>", "Default project root.", ".")
|
|
322
567
|
.option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
|
|
568
|
+
.option("--deep-scan-budget <lines:bytes|off>", "Override both deep-scan bounds as LINES:BYTES, or disable the budget with off.", parseDeepScanBudget)
|
|
569
|
+
.option("--scan-timeout <seconds>", "Accepted for cross-port compatibility; not implemented in gruff-ts.")
|
|
323
570
|
.action(async (rawOptions: Record<string, unknown>) => {
|
|
324
571
|
const projectRoot = resolve(String(rawOptions.projectRoot ?? "."));
|
|
325
572
|
await maybePromptInitConfig(program, projectRoot, { shouldSkipConfig: false, hasExplicitConfig: false });
|
|
326
573
|
const profile = typeof rawOptions.profile === "string" ? rawOptions.profile : undefined;
|
|
327
|
-
|
|
574
|
+
const deepScanBudget = deepScanBudgetOption(rawOptions).deepScanBudget;
|
|
575
|
+
startDashboard(String(rawOptions.host ?? "127.0.0.1"), Number(rawOptions.port ?? 8767), projectRoot, runAnalyse, !outputSuppressed(program), profile, deepScanBudget);
|
|
328
576
|
});
|
|
329
577
|
}
|
|
330
578
|
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
579
|
+
/**
|
|
580
|
+
* Registers `init` to write the default config in the current directory and print adoption guidance when stdout is enabled.
|
|
581
|
+
* Without `--force`, an existing supported config is preserved, a refusal is written to stderr, and `process.exitCode` is set to 1.
|
|
582
|
+
*
|
|
583
|
+
* @param program - root command that receives the `init` subcommand
|
|
584
|
+
* @returns Nothing. Adds the subcommand and its config-initialization action.
|
|
585
|
+
*/
|
|
334
586
|
function registerInitCommand(program: Command): void {
|
|
335
587
|
program
|
|
336
588
|
.command("init")
|
|
@@ -348,7 +600,13 @@ function registerInitCommand(program: Command): void {
|
|
|
348
600
|
});
|
|
349
601
|
}
|
|
350
602
|
|
|
351
|
-
|
|
603
|
+
/**
|
|
604
|
+
* Builds the `init` success message and adoption guidance; the gate command must use the same baseline file that generation creates.
|
|
605
|
+
*
|
|
606
|
+
* @param verb - action label distinguishing newly created (`Wrote`) from replaced (`Overwrote`) config files
|
|
607
|
+
* @param configPath - path to the written configuration file shown in the message
|
|
608
|
+
* @returns Multi-line guidance naming the written config path and matching baseline generation and gating commands.
|
|
609
|
+
*/
|
|
352
610
|
function initSuccessMessage(verb: "Wrote" | "Overwrote", configPath: string): string {
|
|
353
611
|
return [
|
|
354
612
|
`${verb} ${configPath}`,
|
|
@@ -360,8 +618,12 @@ function initSuccessMessage(verb: "Wrote" | "Overwrote", configPath: string): st
|
|
|
360
618
|
].join("\n");
|
|
361
619
|
}
|
|
362
620
|
|
|
363
|
-
|
|
364
|
-
|
|
621
|
+
/**
|
|
622
|
+
* Registers `list` to mirror bare-root help so users following Symfony console conventions can request the command catalogue explicitly.
|
|
623
|
+
*
|
|
624
|
+
* @param program - root command that receives the `list` subcommand and supplies ANSI settings
|
|
625
|
+
* @returns Nothing. Adds the `list` subcommand to the program.
|
|
626
|
+
*/
|
|
365
627
|
function registerListCommand(program: Command): void {
|
|
366
628
|
program
|
|
367
629
|
.command("list")
|
|
@@ -371,9 +633,13 @@ function registerListCommand(program: Command): void {
|
|
|
371
633
|
});
|
|
372
634
|
}
|
|
373
635
|
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
636
|
+
/**
|
|
637
|
+
* Registers `list-profiles` to print the built-in profile catalogue as text or JSON when stdout is enabled.
|
|
638
|
+
* `parseSummaryFormat` rejects unsupported formats as usage errors (see `footguns/schema-and-cli.md` for the format validation contract).
|
|
639
|
+
*
|
|
640
|
+
* @param program - root command that receives the `list-profiles` subcommand
|
|
641
|
+
* @returns Nothing. Adds the subcommand and format option to the program.
|
|
642
|
+
*/
|
|
377
643
|
function registerListProfilesCommand(program: Command): void {
|
|
378
644
|
program
|
|
379
645
|
.command("list-profiles")
|
|
@@ -385,10 +651,13 @@ function registerListProfilesCommand(program: Command): void {
|
|
|
385
651
|
});
|
|
386
652
|
}
|
|
387
653
|
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
654
|
+
/**
|
|
655
|
+
* Registers `list-rules` to print either the rule catalogue or one rule's details as text or JSON through the program's output flags.
|
|
656
|
+
* Unknown rules or unsupported formats are reported as usage errors.
|
|
657
|
+
*
|
|
658
|
+
* @param program - root command that receives the `list-rules` subcommand
|
|
659
|
+
* @returns Nothing. Adds the subcommand, optional rule argument, and output action.
|
|
660
|
+
*/
|
|
392
661
|
function registerListRulesCommand(program: Command): void {
|
|
393
662
|
program
|
|
394
663
|
.command("list-rules")
|
|
@@ -410,41 +679,62 @@ function registerListRulesCommand(program: Command): void {
|
|
|
410
679
|
});
|
|
411
680
|
}
|
|
412
681
|
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
682
|
+
/**
|
|
683
|
+
* Registers `report` for users who want an HTML or JSON artifact of all findings, including reviewed baseline debt.
|
|
684
|
+
* Side effects: the action writes to `--output` or stdout, and can write project config on the filesystem after user approval.
|
|
685
|
+
*
|
|
686
|
+
* @param program - root command that receives the `report` subcommand
|
|
687
|
+
* @param runAnalyse - analysis runner invoked to produce the report findings
|
|
688
|
+
* @returns Nothing. Registers the subcommand, its report options, and its action handler.
|
|
689
|
+
*/
|
|
416
690
|
function registerReportCommand(program: Command, runAnalyse: AnalyseRunner): void {
|
|
417
691
|
program
|
|
418
692
|
.command("report")
|
|
419
693
|
.description("Render a gruff report to stdout or a file.")
|
|
420
694
|
.argument("[paths...]", "Files or directories to analyse.")
|
|
421
|
-
.option("--format <format>", "Report format: html or json.", "html")
|
|
695
|
+
.option("--format <format>", "Report format: html or json.", parseReportFormat, "html")
|
|
422
696
|
.option("--output <path>", "Write report to a file.")
|
|
423
697
|
.option("--config <path>", "Path to a gruff YAML config file.")
|
|
424
698
|
.option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
|
|
425
699
|
.option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
|
|
426
|
-
.option("--
|
|
700
|
+
.option("--deep-scan-budget <lines:bytes|off>", "Override both deep-scan bounds as LINES:BYTES, or disable the budget with off.", parseDeepScanBudget)
|
|
701
|
+
.option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", parseFailOn, "none")
|
|
427
702
|
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
428
|
-
.option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
|
|
429
703
|
.action(async (paths: string[], rawOptions: Record<string, unknown>, command: Command) => {
|
|
704
|
+
const outsideTarget = targetOutsideLaunchDirectory(paths);
|
|
705
|
+
// Refuse a mixed-project target list before trying to render or write a report.
|
|
706
|
+
if (outsideTarget !== null) {
|
|
707
|
+
refuseTargetsOutsideLaunchDirectory(program, rawOptions.format, outsideTarget);
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
430
710
|
await runWithConfigErrorHandling(async () => {
|
|
431
711
|
const format = rawOptions.format === "json" ? "json" : "html";
|
|
432
712
|
const baseOptions = normalizeOptions(paths, { ...rawOptions, format }, { shouldAllowBaselineFlag: false });
|
|
433
|
-
const options =
|
|
434
|
-
await maybePromptInitConfig(program,
|
|
713
|
+
const { options, displayFloor } = configuredSeverities(baseOptions, "report", command);
|
|
714
|
+
await maybePromptInitConfig(program, projectRootFromTargets(options.paths), promptOptionsFromAnalysis(options));
|
|
435
715
|
const report = runAnalyse(options);
|
|
436
|
-
const
|
|
716
|
+
const status = exitFor(report, options.failOn);
|
|
717
|
+
filterReportForDisplay(report, rawOptions, displayFloor);
|
|
718
|
+
const rendered = renderReport(report, format, status);
|
|
719
|
+
// A user can save report.html for a browser. With no file selected, use stdout.
|
|
437
720
|
if (typeof rawOptions.output === "string") {
|
|
438
721
|
writeFileSync(rawOptions.output, rendered);
|
|
439
722
|
} else {
|
|
440
723
|
writeCommandOutput(program, rendered);
|
|
441
724
|
}
|
|
442
|
-
process.exitCode =
|
|
443
|
-
});
|
|
725
|
+
process.exitCode = status;
|
|
726
|
+
}, (error) => writeFailedRunEnvelope(program, rawOptions.format, error));
|
|
444
727
|
});
|
|
445
728
|
}
|
|
446
729
|
|
|
447
|
-
|
|
730
|
+
/**
|
|
731
|
+
* Registers `summary` for users who want pillar counts and top rules or files without opening a per-finding report.
|
|
732
|
+
* Side effects: the action writes the digest to stdout and can save config, a baseline, or score history when requested.
|
|
733
|
+
*
|
|
734
|
+
* @param program - root command that receives the `summary` subcommand
|
|
735
|
+
* @param runAnalyse - analysis runner invoked to scan the target paths
|
|
736
|
+
* @returns Nothing. Registers the summary subcommand and its action handler.
|
|
737
|
+
*/
|
|
448
738
|
function registerSummaryCommand(program: Command, runAnalyse: AnalyseRunner): void {
|
|
449
739
|
program
|
|
450
740
|
.command("summary")
|
|
@@ -455,39 +745,54 @@ function registerSummaryCommand(program: Command, runAnalyse: AnalyseRunner): vo
|
|
|
455
745
|
.option("--config <path>", "Path to a gruff YAML config file.")
|
|
456
746
|
.option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
|
|
457
747
|
.option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
|
|
748
|
+
.option("--deep-scan-budget <lines:bytes|off>", "Override both deep-scan bounds as LINES:BYTES, or disable the budget with off.", parseDeepScanBudget)
|
|
458
749
|
.option("--format <format>", "Output format: text or json.", parseSummaryFormat, "text")
|
|
459
750
|
.option("--top <n>", "How many top rules and file offenders to list.", parseNonNegativeInteger, 10)
|
|
460
|
-
|
|
751
|
+
// The default gate lets findings pass unless config supplies a threshold. Run-invalidating diagnostics still give exit code 2.
|
|
752
|
+
.option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", parseFailOn, "none")
|
|
461
753
|
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
462
754
|
.option("--diff [mode]", "Filter findings to changed files. Use working-tree, staged, unstaged, or a base ref.")
|
|
463
|
-
.option("--history-file <path>", "Append score trend history to this JSON file.")
|
|
755
|
+
.option("--history-file <path>", "Append score trend history to this JSON file (full scans only; incompatible with --diff).")
|
|
464
756
|
.option("--baseline [path]", "Suppress findings that match a gruff baseline JSON file.")
|
|
465
757
|
.option("--generate-baseline [path]", "Write current findings to a gruff baseline JSON file.")
|
|
758
|
+
.option("--migrate-baseline <path>", "Carry a 0.5 baseline's reviews into --generate-baseline; the original file is left untouched.")
|
|
759
|
+
.option("--force", "Overwrite a 0.5 baseline at the default path; without it a generate that would destroy the retreat path is refused.")
|
|
466
760
|
.option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
|
|
467
761
|
.action(async (paths: string[], rawOptions: Record<string, unknown>, command: Command) => {
|
|
762
|
+
const outsideTarget = targetOutsideLaunchDirectory(paths);
|
|
763
|
+
// Use one launch directory to keep paths and totals comparable within the digest.
|
|
764
|
+
if (outsideTarget !== null) {
|
|
765
|
+
refuseTargetsOutsideLaunchDirectory(program, rawOptions.format, outsideTarget, true);
|
|
766
|
+
return;
|
|
767
|
+
}
|
|
468
768
|
await runWithConfigErrorHandling(async () => {
|
|
469
|
-
const baseOptions = normalizeOptions(paths, { ...rawOptions, format: "text" }, { shouldAllowBaselineFlag: true });
|
|
470
|
-
const options = applyMinimumSeverityPrecedence(baseOptions, "summary", command);
|
|
471
769
|
const summaryFormat = rawOptions.format === "json" ? "json" : "text";
|
|
770
|
+
const baseOptions = normalizeOptions(paths, { ...rawOptions, format: summaryFormat }, { shouldAllowBaselineFlag: true });
|
|
771
|
+
const { options, displayFloor } = configuredSeverities(baseOptions, "summary", command);
|
|
472
772
|
const top = typeof rawOptions.top === "number" ? rawOptions.top : 10;
|
|
473
|
-
await maybePromptInitConfig(program,
|
|
773
|
+
await maybePromptInitConfig(program, projectRootFromTargets(options.paths), promptOptionsFromAnalysis(options));
|
|
474
774
|
const startedAt = performance.now();
|
|
475
775
|
const report = runAnalyse(options);
|
|
476
776
|
const elapsedMs = performance.now() - startedAt;
|
|
477
777
|
const pathLabel = summaryPathLabel(options.paths, report.run.projectRoot);
|
|
778
|
+
const status = exitFor(report, options.failOn);
|
|
779
|
+
// Keep the decision from the full scan when the user hides lower-severity entries from the digest.
|
|
780
|
+
filterReportForDisplay(report, rawOptions, displayFloor);
|
|
478
781
|
const rendered = summaryFormat === "json"
|
|
479
|
-
? renderSummaryJson(report,
|
|
782
|
+
? renderSummaryJson(report, status)
|
|
480
783
|
: renderSummary(report, elapsedMs, pathLabel, top);
|
|
481
784
|
writeCommandOutput(program, rendered);
|
|
482
|
-
process.exitCode =
|
|
483
|
-
});
|
|
785
|
+
process.exitCode = status;
|
|
786
|
+
}, (error) => writeFailedRunEnvelope(program, rawOptions.format, error, true));
|
|
484
787
|
});
|
|
485
788
|
}
|
|
486
789
|
|
|
487
|
-
|
|
488
|
-
*
|
|
489
|
-
*
|
|
490
|
-
*
|
|
790
|
+
/**
|
|
791
|
+
* Validate the requested output encoding before Commander runs the command.
|
|
792
|
+
*
|
|
793
|
+
* @param rawFormat - format value supplied on the command line
|
|
794
|
+
* @returns the accepted encoding, text or json
|
|
795
|
+
* @throws {InvalidArgumentError} - when the format is neither text nor json, so Commander reports a usage error
|
|
491
796
|
*/
|
|
492
797
|
function parseSummaryFormat(rawFormat: string): "text" | "json" {
|
|
493
798
|
if (rawFormat === "text" || rawFormat === "json") {
|
|
@@ -496,8 +801,13 @@ function parseSummaryFormat(rawFormat: string): "text" | "json" {
|
|
|
496
801
|
throw new InvalidArgumentError("must be text or json");
|
|
497
802
|
}
|
|
498
803
|
|
|
499
|
-
|
|
500
|
-
|
|
804
|
+
/**
|
|
805
|
+
* Validates the requested hook output format against the hook's JSON-only output contract.
|
|
806
|
+
*
|
|
807
|
+
* @param rawFormat - format string supplied to `--format` on the `hook` command
|
|
808
|
+
* @returns `"json"` when accepted.
|
|
809
|
+
* @throws {InvalidArgumentError} when `rawFormat` is anything other than `json`.
|
|
810
|
+
*/
|
|
501
811
|
function parseHookFormat(rawFormat: string): "json" {
|
|
502
812
|
if (rawFormat === "json") {
|
|
503
813
|
return rawFormat;
|
|
@@ -505,9 +815,192 @@ function parseHookFormat(rawFormat: string): "json" {
|
|
|
505
815
|
throw new InvalidArgumentError("must be json");
|
|
506
816
|
}
|
|
507
817
|
|
|
508
|
-
|
|
509
|
-
* Commander
|
|
510
|
-
*
|
|
818
|
+
/**
|
|
819
|
+
* Build a Commander argument parser that rejects unsupported values before analysis because a silent fallback could change a CI gate.
|
|
820
|
+
*
|
|
821
|
+
* @param choices - allowed CLI values. An empty list makes the parser reject every value.
|
|
822
|
+
* @returns a parser that returns an allowed input unchanged
|
|
823
|
+
* @throws {InvalidArgumentError} - the returned parser throws for values outside choices
|
|
824
|
+
*/
|
|
825
|
+
function parseChoiceOf(choices: readonly string[]): (rawValue: string) => string {
|
|
826
|
+
return (rawValue: string): string => {
|
|
827
|
+
if (choices.includes(rawValue)) {
|
|
828
|
+
return rawValue;
|
|
829
|
+
}
|
|
830
|
+
throw new InvalidArgumentError(`must be one of: ${choices.join(", ")}`);
|
|
831
|
+
};
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
const parseAnalyseFormat = parseChoiceOf(["text", "json", "html", "markdown", "github", "hotspot", "sarif"]);
|
|
835
|
+
const parseReportFormat = parseChoiceOf(["html", "json"]);
|
|
836
|
+
const parseFailOn = parseChoiceOf(["none", "advisory", "warning", "error"]);
|
|
837
|
+
const parseChangedScope = parseChoiceOf(["symbol", "hunk", "file"]);
|
|
838
|
+
const parseConfidence = parseChoiceOf(["low", "medium", "high"]);
|
|
839
|
+
const parseMinSeverity = parseChoiceOf(["advisory", "warning", "error"]);
|
|
840
|
+
|
|
841
|
+
/**
|
|
842
|
+
* Accumulate selectors across repeated CLI flags without changing the earlier list.
|
|
843
|
+
*
|
|
844
|
+
* @param rawValue - comma-separated selectors from the next flag value. Blank entries add nothing.
|
|
845
|
+
* @param previous - selectors already collected, carried forward unchanged
|
|
846
|
+
* @returns a new list with the trimmed nonempty entries appended to the earlier selectors
|
|
847
|
+
*/
|
|
848
|
+
function collectSelectorList(rawValue: string, previous: string[]): string[] {
|
|
849
|
+
return [...previous, ...rawValue.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0)];
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
/**
|
|
853
|
+
* Builds execution selectors that determine which rules run and which findings contribute to scores.
|
|
854
|
+
* Keeps only string entries from selector arrays; absent or non-array selectors become empty lists.
|
|
855
|
+
*
|
|
856
|
+
* @param rawOptions - parsed CLI options containing include and exclude rule or pillar lists
|
|
857
|
+
* @returns Execution selector lists for rules and pillars.
|
|
858
|
+
*/
|
|
859
|
+
function executionSelectorsFrom(rawOptions: Record<string, unknown>): ExecutionSelectors {
|
|
860
|
+
return {
|
|
861
|
+
includeRules: selectorList(rawOptions.includeRule),
|
|
862
|
+
excludeRules: selectorList(rawOptions.excludeRule),
|
|
863
|
+
includePillars: selectorList(rawOptions.includePillar),
|
|
864
|
+
excludePillars: selectorList(rawOptions.excludePillar),
|
|
865
|
+
};
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
/**
|
|
869
|
+
* Builds report-only display selectors that affect visibility without changing execution, scores, or exit status.
|
|
870
|
+
* Keeps only string list entries; absent or non-array selectors become empty lists and invalid `minSeverity` is omitted.
|
|
871
|
+
*
|
|
872
|
+
* @param rawOptions - parsed CLI options containing show/hide selectors and optional minimum display severity
|
|
873
|
+
* @returns Display selector filters for post-analysis report rendering.
|
|
874
|
+
*/
|
|
875
|
+
function displaySelectorsFrom(rawOptions: Record<string, unknown>): DisplaySelectors {
|
|
876
|
+
const minSeverity = rawOptions.minSeverity;
|
|
877
|
+
return {
|
|
878
|
+
...(minSeverity === "advisory" || minSeverity === "warning" || minSeverity === "error" ? { minSeverity } : {}),
|
|
879
|
+
showRules: selectorList(rawOptions.showRule),
|
|
880
|
+
hideRules: selectorList(rawOptions.hideRule),
|
|
881
|
+
showPillars: selectorList(rawOptions.showPillar),
|
|
882
|
+
hidePillars: selectorList(rawOptions.hidePillar),
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
/**
|
|
887
|
+
* Filters displayed findings and SARIF suppressed findings, updating summary counts while keeping the already computed exit status and score stable.
|
|
888
|
+
*
|
|
889
|
+
* @param report - analysis report whose `findings`, `suppressedFindings`, and `summary` are mutated for display
|
|
890
|
+
* @param rawOptions - parsed CLI options supplying show/hide rules, pillars, and `--min-severity`
|
|
891
|
+
* @param displayFloor - optional severity floor from configuration applied alongside CLI selectors
|
|
892
|
+
* @returns Nothing. Mutates `report.findings`, optional `report.suppressedFindings`, and `report.summary` in place.
|
|
893
|
+
*/
|
|
894
|
+
function filterReportForDisplay(report: AnalysisReport, rawOptions: Record<string, unknown>, displayFloor: Severity | undefined): void {
|
|
895
|
+
const selectors = displaySelectorsFrom(rawOptions);
|
|
896
|
+
report.findings = applyDisplaySelectors(report.findings, selectors, displayFloor);
|
|
897
|
+
// Keep SARIF suppressed results aligned with display selectors so hidden rules or pillars do not reappear in SARIF output.
|
|
898
|
+
if (report.suppressedFindings !== undefined && report.suppressedFindings.length > 0) {
|
|
899
|
+
const keptSuppressed = new Set(applyDisplaySelectors(report.suppressedFindings.map((entry) => entry.finding), selectors, displayFloor));
|
|
900
|
+
report.suppressedFindings = report.suppressedFindings.filter((entry) => keptSuppressed.has(entry.finding));
|
|
901
|
+
}
|
|
902
|
+
report.summary = summarize(report.findings);
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
/**
|
|
906
|
+
* Extracts string entries from a collected selector flag value.
|
|
907
|
+
*
|
|
908
|
+
* @param rawValue - candidate flag value expected to hold collected selector strings
|
|
909
|
+
* @returns String entries from `rawValue`, or an empty list for a non-array or an array without strings.
|
|
910
|
+
*/
|
|
911
|
+
function selectorList(rawValue: unknown): string[] {
|
|
912
|
+
return Array.isArray(rawValue) ? rawValue.filter((entry): entry is string => typeof entry === "string") : [];
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
/**
|
|
916
|
+
* Reads the confidence floor the gate applies; an unset flag admits every finding, which is the documented default.
|
|
917
|
+
*
|
|
918
|
+
* @param rawOptions - parsed CLI options providing an optional `minConfidence` setting
|
|
919
|
+
* @returns `"medium"` or `"high"` when explicitly configured, or `"low"` by default.
|
|
920
|
+
*/
|
|
921
|
+
function confidenceFloor(rawOptions: Record<string, unknown>): Confidence {
|
|
922
|
+
const configured = rawOptions.minConfidence;
|
|
923
|
+
return configured === "medium" || configured === "high" ? configured : "low";
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
/**
|
|
927
|
+
* Builds the hook blocking policy applied after handling payload output, including when output is suppressed.
|
|
928
|
+
*
|
|
929
|
+
* @param rawOptions - parsed hook CLI flags supplying severity, confidence, new-finding, and diagnostic gates
|
|
930
|
+
* @returns Hook gate policy with `failOn`, `minConfidence` (defaulting to `low`), and boolean blocking flags.
|
|
931
|
+
*/
|
|
932
|
+
function hookGateFrom(rawOptions: Record<string, unknown>): HookExitGate {
|
|
933
|
+
const failOn = rawOptions.failOn;
|
|
934
|
+
return {
|
|
935
|
+
// An unset severity threshold disables severity gating. The other blocking flags apply independently.
|
|
936
|
+
failOn: failOn === "advisory" || failOn === "warning" || failOn === "error" ? failOn : "none",
|
|
937
|
+
minConfidence: confidenceFloor(rawOptions),
|
|
938
|
+
shouldFailOnNew: rawOptions.failOnNew === true,
|
|
939
|
+
shouldFailOnDiagnostics: rawOptions.failOnDiagnostics === true,
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
/**
|
|
944
|
+
* Writes one `gruff-ts: <message>` line per changed-region diagnostic to stderr under the stable text-mode contract.
|
|
945
|
+
* Machine readers receive the same diagnostic inside the report payload instead.
|
|
946
|
+
*
|
|
947
|
+
* @param report - analysis report containing diagnostics from the run
|
|
948
|
+
* @param format - requested output format; only `"text"` writes diagnostics to stderr
|
|
949
|
+
* @returns Nothing. Writes matching changed-region diagnostic lines to stderr in text mode.
|
|
950
|
+
*/
|
|
951
|
+
function writeChangedRegionFailure(report: AnalysisReport, format: AnalysisOptions["format"]): void {
|
|
952
|
+
if (format !== "text") {
|
|
953
|
+
return;
|
|
954
|
+
}
|
|
955
|
+
for (const diagnostic of report.diagnostics) {
|
|
956
|
+
if (diagnostic.diagnosticType === CHANGED_REGION_DIAGNOSTIC_TYPE) {
|
|
957
|
+
process.stderr.write(`gruff-ts: ${diagnostic.message}\n`);
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
/**
|
|
963
|
+
* Maps a hook error to its diagnostic type under the hook's stable diagnostic contract without inspecting message wording.
|
|
964
|
+
*
|
|
965
|
+
* @param error - thrown error instance caught by the hook command
|
|
966
|
+
* @returns The changed-region diagnostic type for `ChangedRegionError`, `"baseline"` for baseline errors, or `"run"` for other runtime errors.
|
|
967
|
+
*/
|
|
968
|
+
function hookFatalType(error: Error): string {
|
|
969
|
+
if (error instanceof ChangedRegionError) {
|
|
970
|
+
return CHANGED_REGION_DIAGNOSTIC_TYPE;
|
|
971
|
+
}
|
|
972
|
+
if (error instanceof BaselineFileError || error instanceof BaselineIdentityError) {
|
|
973
|
+
return "baseline";
|
|
974
|
+
}
|
|
975
|
+
return "run";
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
/**
|
|
979
|
+
* Parses a deep-scan budget override, keeping both numeric limits in one value to prevent a half-updated budget.
|
|
980
|
+
*
|
|
981
|
+
* @param rawBudget - CLI argument string, either `"off"` or `"LINES:BYTES"`
|
|
982
|
+
* @returns An enabled override with positive `maxLines` and `maxBytes`, or `{ enabled: false }` for `"off"`.
|
|
983
|
+
* @throws {InvalidArgumentError} when the value is not `"off"` and not `LINES:BYTES` with two positive safe integers.
|
|
984
|
+
*/
|
|
985
|
+
function parseDeepScanBudget(rawBudget: string): DeepScanBudgetOverride {
|
|
986
|
+
if (rawBudget === "off") {
|
|
987
|
+
return { enabled: false };
|
|
988
|
+
}
|
|
989
|
+
const match = rawBudget.match(/^(\d+):(\d+)$/);
|
|
990
|
+
const maxLines = match ? Number(match[1]) : Number.NaN;
|
|
991
|
+
const maxBytes = match ? Number(match[2]) : Number.NaN;
|
|
992
|
+
if (!Number.isSafeInteger(maxLines) || maxLines <= 0 || !Number.isSafeInteger(maxBytes) || maxBytes <= 0) {
|
|
993
|
+
throw new InvalidArgumentError("must be two positive integers as LINES:BYTES, or off");
|
|
994
|
+
}
|
|
995
|
+
return { enabled: true, maxLines, maxBytes };
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
/**
|
|
999
|
+
* Validate a CLI count before the command runs, using Number conversion.
|
|
1000
|
+
*
|
|
1001
|
+
* @param rawCount - count supplied as a CLI value. Empty or whitespace-only input means zero.
|
|
1002
|
+
* @returns the converted non-negative integer
|
|
1003
|
+
* @throws {InvalidArgumentError} - when conversion produces a noninteger or negative value, so Commander reports a usage error
|
|
511
1004
|
*/
|
|
512
1005
|
function parseNonNegativeInteger(rawCount: string): number {
|
|
513
1006
|
const parsed = Number(rawCount);
|
|
@@ -517,7 +1010,13 @@ function parseNonNegativeInteger(rawCount: string): number {
|
|
|
517
1010
|
return parsed;
|
|
518
1011
|
}
|
|
519
1012
|
|
|
520
|
-
|
|
1013
|
+
/**
|
|
1014
|
+
* Formats the path label shown in the summary header by resolving target paths against the current directory.
|
|
1015
|
+
*
|
|
1016
|
+
* @param paths - target paths supplied to the summary command
|
|
1017
|
+
* @param projectRoot - fallback project root returned when `paths` is empty
|
|
1018
|
+
* @returns Comma-joined resolved paths, or `projectRoot` when no paths were provided.
|
|
1019
|
+
*/
|
|
521
1020
|
function summaryPathLabel(paths: string[], projectRoot: string): string {
|
|
522
1021
|
if (paths.length === 0) {
|
|
523
1022
|
return projectRoot;
|
|
@@ -525,11 +1024,27 @@ function summaryPathLabel(paths: string[], projectRoot: string): string {
|
|
|
525
1024
|
return paths.map((path) => resolve(path)).join(", ");
|
|
526
1025
|
}
|
|
527
1026
|
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
1027
|
+
/**
|
|
1028
|
+
* Converts a parsed CLI request into analysis options and enforces the baseline option contract for the command.
|
|
1029
|
+
* Reads the patch from stdin when selected so that analysis receives the patch text with its options.
|
|
1030
|
+
*
|
|
1031
|
+
* @param paths - positional scan targets, including the stdin marker for --diff. No targets defaults to the project.
|
|
1032
|
+
* @param rawOptions - parsed Commander flags used to select analysis settings and defaults
|
|
1033
|
+
* @param context - command policy that controls whether baseline input is allowed
|
|
1034
|
+
* @returns Normalized analysis options, including the resolved scan targets and diff, history and baseline settings.
|
|
1035
|
+
* @throws {ConfigLoadError} for incompatible history or baseline flags, or an invalid deep-scan budget override.
|
|
1036
|
+
*/
|
|
532
1037
|
function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>, context: NormalizeContext): AnalysisOptions {
|
|
1038
|
+
assertFullScanHistoryOptions(rawOptions);
|
|
1039
|
+
const generation = generateBaselineOption(rawOptions);
|
|
1040
|
+
// The source tells migration which reviews to keep. The generation flag tells it where to put them.
|
|
1041
|
+
if (typeof rawOptions.migrateBaseline === "string" && !generation.generateBaseline) {
|
|
1042
|
+
throw new ConfigLoadError("--migrate-baseline requires --generate-baseline.", "Pass --generate-baseline <output path>.", false);
|
|
1043
|
+
}
|
|
1044
|
+
// A generation starts a review. A new-debt gate needs a review that already exists.
|
|
1045
|
+
if (rawOptions.failOnNew === true && generation.generateBaseline) {
|
|
1046
|
+
throw new ConfigLoadError("--fail-on-new requires an applied baseline.", "Generate the baseline first, then run with --baseline <path>.", false);
|
|
1047
|
+
}
|
|
533
1048
|
const format = stringChoice(rawOptions.format, ["text", "json", "html", "markdown", "github", "hotspot", "sarif"], "text");
|
|
534
1049
|
const failOn = stringChoice(rawOptions.failOn, ["none", "advisory", "warning", "error"], "advisory");
|
|
535
1050
|
const diffInput = diffOption(paths, rawOptions);
|
|
@@ -542,6 +1057,7 @@ function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>,
|
|
|
542
1057
|
paths: diffInput.paths,
|
|
543
1058
|
...configOption(rawOptions),
|
|
544
1059
|
...profileOption(rawOptions),
|
|
1060
|
+
...deepScanBudgetOption(rawOptions),
|
|
545
1061
|
shouldSkipConfig:
|
|
546
1062
|
rawOptions.config === false ||
|
|
547
1063
|
rawOptions.noConfig === true,
|
|
@@ -554,13 +1070,58 @@ function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>,
|
|
|
554
1070
|
...sinceOption(rawOptions),
|
|
555
1071
|
...historyFileOption(rawOptions),
|
|
556
1072
|
...baselineOption(baselineValue, context),
|
|
557
|
-
...
|
|
1073
|
+
...generation,
|
|
1074
|
+
...migrateBaselineOption(rawOptions),
|
|
1075
|
+
...(rawOptions.force === true ? { shouldForceBaselineOverwrite: true } : {}),
|
|
558
1076
|
shouldSkipBaseline,
|
|
1077
|
+
execution: executionSelectorsFrom(rawOptions),
|
|
559
1078
|
};
|
|
560
1079
|
}
|
|
561
1080
|
|
|
562
|
-
|
|
563
|
-
|
|
1081
|
+
/**
|
|
1082
|
+
* Rejects a history write for a filtered or partial-catalogue scan so the user's score trend compares full scans.
|
|
1083
|
+
* The command reports the conflicting flags and exits 2 before rendering or writing history.
|
|
1084
|
+
*
|
|
1085
|
+
* @param rawOptions - parsed CLI options checked for a history path, changed-region flags, and execution selectors
|
|
1086
|
+
* @returns Nothing. Lets the command proceed when the supplied options are compatible.
|
|
1087
|
+
* @throws {ConfigLoadError} when --history-file is combined with changed-region options or rule/pillar execution selectors.
|
|
1088
|
+
*/
|
|
1089
|
+
function assertFullScanHistoryOptions(rawOptions: Record<string, unknown>): void {
|
|
1090
|
+
// Without --history-file there is no trend file to protect, so any scan shape is allowed.
|
|
1091
|
+
if (typeof rawOptions.historyFile !== "string") {
|
|
1092
|
+
return;
|
|
1093
|
+
}
|
|
1094
|
+
const hasChangedRegionSelector = rawOptions.diff === true
|
|
1095
|
+
|| typeof rawOptions.diff === "string"
|
|
1096
|
+
|| typeof rawOptions.diffBase === "string"
|
|
1097
|
+
|| typeof rawOptions.since === "string"
|
|
1098
|
+
|| typeof rawOptions.changedRanges === "string";
|
|
1099
|
+
// A filtered request would mix partial scores into the full-project trend users review.
|
|
1100
|
+
if (hasChangedRegionSelector) {
|
|
1101
|
+
throw new ConfigLoadError(
|
|
1102
|
+
"`--history-file` requires a full scan and cannot be combined with `--diff`, `--diff-base`, `--since`, or `--changed-ranges`.",
|
|
1103
|
+
"Remove the changed-region option, or omit `--history-file` for this filtered scan.",
|
|
1104
|
+
false,
|
|
1105
|
+
);
|
|
1106
|
+
}
|
|
1107
|
+
// Execution selectors score only a subset of the rule catalogue and cannot append to full-scan trend history.
|
|
1108
|
+
if (isExecutionRequested(executionSelectorsFrom(rawOptions))) {
|
|
1109
|
+
throw new ConfigLoadError(
|
|
1110
|
+
"`--history-file` requires a full scan and cannot be combined with `--include-rule`, `--exclude-rule`, `--include-pillar`, or `--exclude-pillar`.",
|
|
1111
|
+
"Remove the execution selector option, or omit `--history-file` for this partial-catalogue scan.",
|
|
1112
|
+
false,
|
|
1113
|
+
);
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
/**
|
|
1118
|
+
* Builds hook analysis options under the hook comparison contract (JSON, symbol scope, no severity gate or baseline suppression).
|
|
1119
|
+
* Without a region selector, the scan remains unscoped.
|
|
1120
|
+
*
|
|
1121
|
+
* @param paths - positional paths passed to the hook command
|
|
1122
|
+
* @param rawOptions - parsed CLI flags merged with hook contract defaults
|
|
1123
|
+
* @returns Normalized analysis options for the scoped hook pass.
|
|
1124
|
+
*/
|
|
564
1125
|
function hookScopedOptions(paths: string[], rawOptions: Record<string, unknown>): AnalysisOptions {
|
|
565
1126
|
return normalizeOptions(
|
|
566
1127
|
paths,
|
|
@@ -569,72 +1130,207 @@ function hookScopedOptions(paths: string[], rawOptions: Record<string, unknown>)
|
|
|
569
1130
|
);
|
|
570
1131
|
}
|
|
571
1132
|
|
|
572
|
-
|
|
573
|
-
|
|
1133
|
+
/**
|
|
1134
|
+
* Strips changed-region selectors from hook options so the current pass captures full-file and project findings.
|
|
1135
|
+
* Keeps baseline suppression off per the hook comparison contract so this pass sees the full set of findings.
|
|
1136
|
+
*
|
|
1137
|
+
* @param options - scoped hook analysis options to widen
|
|
1138
|
+
* @returns Copy of `options` with changed-region fields omitted and `shouldSkipBaseline` set to true.
|
|
1139
|
+
*/
|
|
574
1140
|
function hookCurrentOptions(options: AnalysisOptions): AnalysisOptions {
|
|
575
|
-
const { changedRanges: _changedRanges, diff: _diff, diffPatch: _diffPatch, since: _since, ...rest } = options;
|
|
1141
|
+
const { changedRanges: _changedRanges, diff: _diff, diffPatch: _diffPatch, isDiffExplicitRef: _isDiffExplicitRef, since: _since, ...rest } = options;
|
|
576
1142
|
return { ...rest, shouldSkipBaseline: true };
|
|
577
1143
|
}
|
|
578
1144
|
|
|
579
|
-
|
|
1145
|
+
/**
|
|
1146
|
+
* Reports whether any changed-region selector (ranges, diff, since, or stdin patch) is active for the run.
|
|
1147
|
+
* Both `changedRanges` and `diffPatch` test presence rather than truthiness, matching `changedRegionScope`.
|
|
1148
|
+
*
|
|
1149
|
+
* @param options - normalized analysis options to inspect for region selectors
|
|
1150
|
+
* @returns True when any changed-region selector is active; otherwise false.
|
|
1151
|
+
*/
|
|
580
1152
|
function hasHookChangedRegion(options: AnalysisOptions): boolean {
|
|
581
|
-
return
|
|
1153
|
+
return options.changedRanges !== undefined || options.diffPatch !== undefined || Boolean(options.diff || options.since);
|
|
582
1154
|
}
|
|
583
1155
|
|
|
584
|
-
|
|
1156
|
+
/**
|
|
1157
|
+
* Extracts `baselinePath` from `--baseline` to preserve the stable baseline contract for hook new-only filtering.
|
|
1158
|
+
*
|
|
1159
|
+
* @param rawOptions - parsed hook CLI flags
|
|
1160
|
+
* @returns `{ baselinePath }` when `--baseline` is a string, or an empty object when absent or non-string.
|
|
1161
|
+
*/
|
|
585
1162
|
function hookBaselinePath(rawOptions: Record<string, unknown>): Partial<{ baselinePath: string }> {
|
|
586
1163
|
return typeof rawOptions.baseline === "string" ? { baselinePath: rawOptions.baseline } : {};
|
|
587
1164
|
}
|
|
588
1165
|
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
1166
|
+
/**
|
|
1167
|
+
* Picks the Git base the hook replays to tell new findings from inherited ones.
|
|
1168
|
+
* Uses the same order as `changedRegionScope`: `changedRanges`, `diffPatch`, `since`, then `diff`.
|
|
1169
|
+
*
|
|
1170
|
+
* @param options - normalized hook analysis options
|
|
1171
|
+
* @returns `{ diffBase }`, plus `isDiffExplicitRef` for a named Git ref; empty when line ranges or a stdin patch leave no Git base to replay.
|
|
1172
|
+
*/
|
|
1173
|
+
function hookDiffBase(options: AnalysisOptions): Partial<{ diffBase: string; isDiffExplicitRef: boolean }> {
|
|
1174
|
+
// Explicit line ranges and stdin patches take precedence over Git selectors and have no Git revision to replay.
|
|
1175
|
+
if (options.changedRanges !== undefined || options.diffPatch !== undefined) {
|
|
1176
|
+
return {};
|
|
1177
|
+
}
|
|
1178
|
+
// `--since <ref>` always replays that Git ref directly, even for a branch literally named `staged` or `unstaged`.
|
|
1179
|
+
if (options.since) {
|
|
1180
|
+
return { diffBase: options.since, isDiffExplicitRef: true };
|
|
1181
|
+
}
|
|
1182
|
+
// A --diff or --diff-base value replays its Git base; only --diff-base marks the value as an explicit ref.
|
|
1183
|
+
if (options.diff) {
|
|
1184
|
+
return { diffBase: options.diff, ...(options.isDiffExplicitRef === true ? { isDiffExplicitRef: true } : {}) };
|
|
1185
|
+
}
|
|
1186
|
+
return {};
|
|
592
1187
|
}
|
|
593
1188
|
|
|
594
|
-
|
|
595
|
-
|
|
1189
|
+
/**
|
|
1190
|
+
* Extracts a string config path option while omitting the key to preserve `exactOptionalPropertyTypes` instead of assigning undefined.
|
|
1191
|
+
*
|
|
1192
|
+
* @param rawOptions - parsed CLI flags checked for a string `config` value
|
|
1193
|
+
* @returns `{ config }` when `rawOptions.config` is a string, or an empty object otherwise.
|
|
1194
|
+
*/
|
|
596
1195
|
function configOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "config">> {
|
|
597
1196
|
return typeof rawOptions.config === "string" ? { config: rawOptions.config } : {};
|
|
598
1197
|
}
|
|
599
1198
|
|
|
600
|
-
|
|
601
|
-
|
|
1199
|
+
/**
|
|
1200
|
+
* Extracts a string profile specifier, omitting the key when absent so config-file selection can supply it.
|
|
1201
|
+
*
|
|
1202
|
+
* @param rawOptions - parsed CLI flags checked for a string `profile` value
|
|
1203
|
+
* @returns `{ profile }` when `rawOptions.profile` is a string, or an empty object otherwise.
|
|
1204
|
+
*/
|
|
602
1205
|
function profileOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "profile">> {
|
|
603
1206
|
return typeof rawOptions.profile === "string" ? { profile: rawOptions.profile } : {};
|
|
604
1207
|
}
|
|
605
1208
|
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
1209
|
+
/**
|
|
1210
|
+
* Normalizes `rawOptions.deepScanBudget` into a disabled or bounded analysis override.
|
|
1211
|
+
*
|
|
1212
|
+
* @param rawOptions - parsed CLI flags containing an optional `deepScanBudget` override object
|
|
1213
|
+
* @returns `{ deepScanBudget }` for valid overrides, or an empty object for null, non-objects, or missing `enabled`.
|
|
1214
|
+
* @throws {ConfigLoadError} when an object has `enabled` but is neither disabled nor validly bounded.
|
|
1215
|
+
*/
|
|
1216
|
+
function deepScanBudgetOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "deepScanBudget">> {
|
|
1217
|
+
const budgetOverride = rawOptions.deepScanBudget;
|
|
1218
|
+
if (typeof budgetOverride !== "object" || budgetOverride === null || !("enabled" in budgetOverride)) {
|
|
1219
|
+
return {};
|
|
1220
|
+
}
|
|
1221
|
+
if (budgetOverride.enabled === false) {
|
|
1222
|
+
return { deepScanBudget: { enabled: false } };
|
|
1223
|
+
}
|
|
1224
|
+
if (budgetOverride.enabled === true && "maxLines" in budgetOverride && "maxBytes" in budgetOverride
|
|
1225
|
+
&& typeof budgetOverride.maxLines === "number" && Number.isSafeInteger(budgetOverride.maxLines) && budgetOverride.maxLines > 0
|
|
1226
|
+
&& typeof budgetOverride.maxBytes === "number" && Number.isSafeInteger(budgetOverride.maxBytes) && budgetOverride.maxBytes > 0) {
|
|
1227
|
+
return { deepScanBudget: { enabled: true, maxLines: budgetOverride.maxLines, maxBytes: budgetOverride.maxBytes } };
|
|
1228
|
+
}
|
|
1229
|
+
throw new ConfigLoadError("Invalid deep-scan budget override.", "Pass `--deep-scan-budget LINES:BYTES` with positive integers, or `--deep-scan-budget off`.", false);
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
/**
|
|
1233
|
+
* Decides whether --fail-on-new should block the run on findings an applied baseline leaves unreviewed.
|
|
1234
|
+
* The caller takes the maximum with the severity exit code to preserve the stable gate contract.
|
|
1235
|
+
*
|
|
1236
|
+
* @param report - analysis result carrying the baseline status and new finding count
|
|
1237
|
+
* @param rawOptions - parsed CLI options whose failOnNew flag enables the check
|
|
1238
|
+
* @returns 0 when disabled. With an applied baseline, returns 1 for a positive new finding count or 0 for an absent or nonpositive count.
|
|
1239
|
+
* @throws {ConfigLoadError} - when --fail-on-new is set but the run applied no baseline or only generated one.
|
|
1240
|
+
*/
|
|
1241
|
+
function newDebtExitCode(report: AnalysisReport, rawOptions: Record<string, unknown>): number {
|
|
1242
|
+
// When the new-debt gate is off, the command can proceed without applying a baseline.
|
|
1243
|
+
if (rawOptions.failOnNew !== true) {
|
|
1244
|
+
return 0;
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
const baseline = report.baseline;
|
|
1248
|
+
|
|
1249
|
+
// A generate run writes a baseline rather than applying one, so it has nothing to call new either.
|
|
1250
|
+
if (baseline === undefined || baseline.generated === true) {
|
|
1251
|
+
throw new ConfigLoadError(
|
|
1252
|
+
"`--fail-on-new` needs an applied baseline to compare against, and this run applied none.",
|
|
1253
|
+
"Pass `--baseline <path>`, or generate one first with `--generate-baseline <path>`.",
|
|
1254
|
+
false,
|
|
1255
|
+
);
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
return (baseline.newFindings ?? 0) > 0 ? 1 : 0;
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
/**
|
|
1262
|
+
* Resolves `--diff` and `--diff-base`, reading the patch from stdin for `-` unless `--changed-ranges` already supplied the lines.
|
|
1263
|
+
*
|
|
1264
|
+
* A nonempty `--diff-base` wins over `--diff`, and any value other than `-` is marked as an explicit Git ref.
|
|
1265
|
+
* Bare `--diff` means `working-tree`, and a leading `-` path after bare `--diff` is taken as the stdin marker.
|
|
1266
|
+
*
|
|
1267
|
+
* @param paths - positional scan targets, which may begin with `-` for a stdin patch
|
|
1268
|
+
* @param rawOptions - parsed CLI flags providing `diff`, `diffBase`, and optional `changedRanges`
|
|
1269
|
+
* @returns Updated `paths` and partial diff options, or unchanged `paths` with empty options when no selector applies.
|
|
1270
|
+
*/
|
|
1271
|
+
function diffOption(paths: string[], rawOptions: Record<string, unknown>): { paths: string[]; options: Partial<Pick<AnalysisOptions, "diff" | "diffPatch" | "isDiffExplicitRef">> } {
|
|
1272
|
+
const diffBase = rawOptions.diffBase;
|
|
1273
|
+
const shouldReadStdin = typeof rawOptions.changedRanges !== "string";
|
|
1274
|
+
|
|
1275
|
+
// The canonical spelling names the ref outright, so it wins over whatever mode --diff carried.
|
|
1276
|
+
if (typeof diffBase === "string" && diffBase.length > 0) {
|
|
1277
|
+
// `--diff-base -` reads the patch from stdin unless --changed-ranges already supplied the changed lines.
|
|
1278
|
+
if (diffBase === "-") {
|
|
1279
|
+
return { paths, options: shouldReadStdin ? { diff: "-", diffPatch: readFileSync(0, "utf8") } : { diff: "-" } };
|
|
1280
|
+
}
|
|
1281
|
+
return { paths, options: { diff: diffBase, isDiffExplicitRef: true } };
|
|
1282
|
+
}
|
|
1283
|
+
// A string value came from forms such as `analyse --diff staged`, `analyse --diff main`, or `analyse --diff -`.
|
|
609
1284
|
if (typeof rawOptions.diff === "string") {
|
|
610
1285
|
return rawOptions.diff === "-"
|
|
611
|
-
? { paths, options: { diff: "-", diffPatch: readFileSync(0, "utf8") } }
|
|
1286
|
+
? { paths, options: shouldReadStdin ? { diff: "-", diffPatch: readFileSync(0, "utf8") } : { diff: "-" } }
|
|
612
1287
|
: { paths, options: { diff: rawOptions.diff } };
|
|
613
1288
|
}
|
|
1289
|
+
// In `analyse --diff - src/app.ts`, Commander parses `--diff` as bare `true` and leaves `-` as the first positional path.
|
|
614
1290
|
if (rawOptions.diff === true && paths[0] === "-") {
|
|
615
|
-
return { paths: paths.slice(1), options: { diff: "-", diffPatch: readFileSync(0, "utf8") } };
|
|
1291
|
+
return { paths: paths.slice(1), options: shouldReadStdin ? { diff: "-", diffPatch: readFileSync(0, "utf8") } : { diff: "-" } };
|
|
616
1292
|
}
|
|
1293
|
+
// Bare `analyse --diff` with no mode compares uncommitted working-tree changes; omitting `--diff` runs a full scan.
|
|
617
1294
|
return rawOptions.diff === true ? { paths, options: { diff: "working-tree" } } : { paths, options: {} };
|
|
618
1295
|
}
|
|
619
1296
|
|
|
620
|
-
|
|
1297
|
+
/**
|
|
1298
|
+
* Extracts a string `changedRanges` option so analysis can enforce or reject an explicitly empty range string.
|
|
1299
|
+
*
|
|
1300
|
+
* @param rawOptions - parsed CLI flags checked for a string `changedRanges` value
|
|
1301
|
+
* @returns `{ changedRanges }` when a string is present, or an empty object so the filter stays unset.
|
|
1302
|
+
*/
|
|
621
1303
|
function changedRangesOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "changedRanges">> {
|
|
622
1304
|
return typeof rawOptions.changedRanges === "string" ? { changedRanges: rawOptions.changedRanges } : {};
|
|
623
1305
|
}
|
|
624
1306
|
|
|
625
|
-
|
|
1307
|
+
/**
|
|
1308
|
+
* Extracts a string `since` base ref option, preserving an empty string (which selects no comparison ref).
|
|
1309
|
+
*
|
|
1310
|
+
* @param rawOptions - parsed CLI flags checked for a string `since` value
|
|
1311
|
+
* @returns `{ since }` when `rawOptions.since` is a string, or an empty object otherwise.
|
|
1312
|
+
*/
|
|
626
1313
|
function sinceOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "since">> {
|
|
627
1314
|
return typeof rawOptions.since === "string" ? { since: rawOptions.since } : {};
|
|
628
1315
|
}
|
|
629
1316
|
|
|
630
|
-
|
|
1317
|
+
/**
|
|
1318
|
+
* Extracts a string `historyFile` path while omitting absent values to preserve `exactOptionalPropertyTypes`.
|
|
1319
|
+
*
|
|
1320
|
+
* @param rawOptions - parsed CLI flags checked for a string `historyFile` value
|
|
1321
|
+
* @returns `{ historyFile }` when `rawOptions.historyFile` is a string, or an empty object otherwise.
|
|
1322
|
+
*/
|
|
631
1323
|
function historyFileOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "historyFile">> {
|
|
632
1324
|
return typeof rawOptions.historyFile === "string" ? { historyFile: rawOptions.historyFile } : {};
|
|
633
1325
|
}
|
|
634
1326
|
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
1327
|
+
/**
|
|
1328
|
+
* Normalizes `--baseline` when the command policy permits baseline input; selection is stable for identical inputs.
|
|
1329
|
+
*
|
|
1330
|
+
* @param baselineValue - raw `--baseline` value (path string, `true` for a bare flag, or unset)
|
|
1331
|
+
* @param context - command policy controlling whether `--baseline` is permitted
|
|
1332
|
+
* @returns `{ baseline }` holding the path string (even if empty) or `DEFAULT_BASELINE` for `true`, or `{}` when disallowed.
|
|
1333
|
+
*/
|
|
638
1334
|
function baselineOption(baselineValue: unknown, context: NormalizeContext): Partial<Pick<AnalysisOptions, "baseline">> {
|
|
639
1335
|
if (!context.shouldAllowBaselineFlag) {
|
|
640
1336
|
return {};
|
|
@@ -645,8 +1341,12 @@ function baselineOption(baselineValue: unknown, context: NormalizeContext): Part
|
|
|
645
1341
|
return baselineValue === true ? { baseline: DEFAULT_BASELINE } : {};
|
|
646
1342
|
}
|
|
647
1343
|
|
|
648
|
-
|
|
649
|
-
|
|
1344
|
+
/**
|
|
1345
|
+
* Resolves `--generate-baseline` into an output path, returning `{}` otherwise because baseline generation must be requested.
|
|
1346
|
+
*
|
|
1347
|
+
* @param rawOptions - parsed CLI flags checked for a string path or boolean `true` on `generateBaseline`
|
|
1348
|
+
* @returns `{ generateBaseline }` with the given string path or `DEFAULT_BASELINE` for `true`, or an empty object otherwise.
|
|
1349
|
+
*/
|
|
650
1350
|
function generateBaselineOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "generateBaseline">> {
|
|
651
1351
|
if (typeof rawOptions.generateBaseline === "string") {
|
|
652
1352
|
return { generateBaseline: rawOptions.generateBaseline };
|
|
@@ -654,40 +1354,130 @@ function generateBaselineOption(rawOptions: Record<string, unknown>): Partial<Pi
|
|
|
654
1354
|
return rawOptions.generateBaseline === true ? { generateBaseline: DEFAULT_BASELINE } : {};
|
|
655
1355
|
}
|
|
656
1356
|
|
|
657
|
-
|
|
658
|
-
|
|
1357
|
+
/**
|
|
1358
|
+
* Extracts the 0.5 baseline path from parsed CLI flags to carry reviews into a new baseline.
|
|
1359
|
+
*
|
|
1360
|
+
* @param rawOptions - parsed CLI flags checked for a string `migrateBaseline` path
|
|
1361
|
+
* @returns `{ migrateBaseline }` when a string path is supplied, or an empty object for missing or non-string values.
|
|
1362
|
+
*/
|
|
1363
|
+
function migrateBaselineOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "migrateBaseline">> {
|
|
1364
|
+
return typeof rawOptions.migrateBaseline === "string" ? { migrateBaseline: rawOptions.migrateBaseline } : {};
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
/**
|
|
1368
|
+
* Normalizes a programmatic option against a list of allowed string values.
|
|
1369
|
+
*
|
|
1370
|
+
* @param rawValue - candidate option value to validate
|
|
1371
|
+
* @param choices - allowed string values accepted for the option
|
|
1372
|
+
* @param fallback - default value returned when `rawValue` is not a listed string
|
|
1373
|
+
* @returns `rawValue` when it is a string included in `choices`; otherwise `fallback`.
|
|
1374
|
+
*/
|
|
1375
|
+
function stringChoice<T extends string>(rawValue: unknown, choices: readonly T[], fallback: T): T {
|
|
1376
|
+
return typeof rawValue === "string" && choices.includes(rawValue as T) ? (rawValue as T) : fallback;
|
|
659
1377
|
}
|
|
660
1378
|
|
|
661
1379
|
/*
|
|
662
|
-
*
|
|
663
|
-
*
|
|
664
|
-
*
|
|
665
|
-
*
|
|
666
|
-
*
|
|
667
|
-
* cleanly via `runWithConfigErrorHandling`.
|
|
1380
|
+
* What the project's config file says about one run's gate and its display floor, read in one pass.
|
|
1381
|
+
*
|
|
1382
|
+
* The two are deliberately separate keys: `failOn:` decides the exit code, `minimumSeverity:` decides what the
|
|
1383
|
+
* report shows. Keeping them in one result means the command reads the config once and cannot apply a stale half
|
|
1384
|
+
* of it (FAMILY-CONTRACT.md, search: `## 7. CLI surface`).
|
|
668
1385
|
*/
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
1386
|
+
interface ConfiguredSeverities {
|
|
1387
|
+
options: AnalysisOptions;
|
|
1388
|
+
displayFloor?: Severity;
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
/**
|
|
1392
|
+
* Uses failOn.<cmd> from configuration when the caller leaves --fail-on at its default. An explicit CLI value takes precedence.
|
|
1393
|
+
*
|
|
1394
|
+
* @param options - normalized analysis options used to select configuration and supply the existing fail-on value
|
|
1395
|
+
* @param command - command key used to look up the configured severity threshold
|
|
1396
|
+
* @param commanderCommand - parsed command used to detect an explicit CLI value
|
|
1397
|
+
* @returns Analysis options with any configured threshold applied, and a display floor only when one is configured.
|
|
1398
|
+
* @throws {ConfigLoadError} - if configuration loading fails, for runWithConfigErrorHandling to report.
|
|
1399
|
+
*/
|
|
1400
|
+
function configuredSeverities(options: AnalysisOptions, command: MinimumSeverityCommand, commanderCommand: Command): ConfiguredSeverities {
|
|
1401
|
+
// A scan of a sibling project should use that project's settings even if launched elsewhere.
|
|
1402
|
+
const config = loadConfig(projectRootFromTargets(options.paths), options);
|
|
1403
|
+
// An explicit --fail-on wins. If neither source sets a gate, keep this command's default.
|
|
1404
|
+
const configuredFailOn = commanderCommand.getOptionValueSource("failOn") === "cli" ? undefined : minimumSeverityFor(config, command);
|
|
1405
|
+
return {
|
|
1406
|
+
options: configuredFailOn === undefined ? options : { ...options, failOn: configuredFailOn },
|
|
1407
|
+
...(config.displayFloor === undefined ? {} : { displayFloor: config.displayFloor }),
|
|
1408
|
+
};
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
/**
|
|
1412
|
+
* Writes a machine-readable failure envelope for a configuration load failure, preserving the summary schema when called from `summary`.
|
|
1413
|
+
*
|
|
1414
|
+
* @param program - command whose output flags govern stdout
|
|
1415
|
+
* @param requestedFormat - JSON or SARIF encoding. Other formats produce no envelope.
|
|
1416
|
+
* @param error - refusal to report when it represents a configuration load failure
|
|
1417
|
+
* @param isSummary - true when invoked from `summary` so JSON emits `gruff.summary.v3` instead of `gruff.analysis.v3`
|
|
1418
|
+
* @returns nothing. It publishes the envelope when the failure, format, and output flags allow it.
|
|
1419
|
+
*/
|
|
1420
|
+
function writeFailedRunEnvelope(program: Command, requestedFormat: unknown, error: ConfigLoadError, isSummary = false): void {
|
|
1421
|
+
// CLI flag errors (such as a mistyped `--include-rule`) and text/html output report on stderr only, without emitting a JSON/SARIF envelope.
|
|
1422
|
+
if (!error.isConfigLoadFailure || (requestedFormat !== "json" && requestedFormat !== "sarif")) {
|
|
1423
|
+
return;
|
|
672
1424
|
}
|
|
673
|
-
const
|
|
674
|
-
const
|
|
675
|
-
|
|
1425
|
+
const report = failedRunReport(cwd(), requestedFormat, CONFIG_ERROR_DIAGNOSTIC_TYPE, error.message);
|
|
1426
|
+
const rendered = isSummary && requestedFormat === "json"
|
|
1427
|
+
? renderSummaryJson(report, USAGE_EXIT_CODE)
|
|
1428
|
+
: renderReport(report, requestedFormat, USAGE_EXIT_CODE);
|
|
1429
|
+
writeCommandOutput(program, rendered);
|
|
676
1430
|
}
|
|
677
1431
|
|
|
678
|
-
|
|
679
|
-
*
|
|
680
|
-
*
|
|
681
|
-
*
|
|
682
|
-
*
|
|
683
|
-
*
|
|
1432
|
+
/**
|
|
1433
|
+
* Report a target outside the launch directory and publish the refusal in machine-readable form when requested.
|
|
1434
|
+
*
|
|
1435
|
+
* @param program - command whose output flags govern the stdout envelope
|
|
1436
|
+
* @param requestedFormat - JSON or SARIF selects a failure envelope. Other formats skip it.
|
|
1437
|
+
* @param target - path outside the launch directory to identify in the refusal
|
|
1438
|
+
* @param isSummary - true when invoked from `summary` so JSON emits `gruff.summary.v3` instead of `gruff.analysis.v3`
|
|
1439
|
+
* @returns nothing. It writes the reason to stderr and sets process.exitCode to 2.
|
|
1440
|
+
*/
|
|
1441
|
+
function refuseTargetsOutsideLaunchDirectory(program: Command, requestedFormat: unknown, target: string, isSummary = false): void {
|
|
1442
|
+
const message = outsideTargetMessage(target);
|
|
1443
|
+
process.stderr.write(`gruff-ts: ${message}\n`);
|
|
1444
|
+
// Automation reading JSON or SARIF receives the same refusal in its chosen format.
|
|
1445
|
+
if (requestedFormat === "json" || requestedFormat === "sarif") {
|
|
1446
|
+
const report = failedRunReport(cwd(), requestedFormat, TARGET_ERROR_DIAGNOSTIC_TYPE, message);
|
|
1447
|
+
const rendered = isSummary && requestedFormat === "json"
|
|
1448
|
+
? renderSummaryJson(report, USAGE_EXIT_CODE)
|
|
1449
|
+
: renderReport(report, requestedFormat, USAGE_EXIT_CODE);
|
|
1450
|
+
writeCommandOutput(program, rendered);
|
|
1451
|
+
}
|
|
1452
|
+
process.exitCode = 2;
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
/**
|
|
1456
|
+
* Formats the refusal reason explaining why a multi-target scan cannot be anchored at its launch directory.
|
|
1457
|
+
*
|
|
1458
|
+
* @param target - target path located outside the current launch directory
|
|
1459
|
+
* @returns Human-readable refusal message naming `target`.
|
|
1460
|
+
*/
|
|
1461
|
+
function outsideTargetMessage(target: string): string {
|
|
1462
|
+
return `target "${target}" is outside the launch directory; gruff-ts analyses several targets only from a directory that contains them all`;
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
/**
|
|
1466
|
+
* Awaits action; a ConfigLoadError writes stderr, optionally calls publishRefusal and sets process.exitCode to 2.
|
|
1467
|
+
* Other errors propagate unchanged; publisher errors propagate before the exit code is assigned.
|
|
1468
|
+
*
|
|
1469
|
+
* @param action - command work to run and await
|
|
1470
|
+
* @param publishRefusal - optional publisher for a handled refusal; omission leaves only stderr reporting
|
|
1471
|
+
* @returns a promise that resolves without a value after successful work or a handled refusal
|
|
1472
|
+
* @throws {unknown} - errors from action other than ConfigLoadError, or errors thrown by publishRefusal
|
|
684
1473
|
*/
|
|
685
|
-
async function runWithConfigErrorHandling(action: () => Promise<void> | void): Promise<void> {
|
|
1474
|
+
async function runWithConfigErrorHandling(action: () => Promise<void> | void, publishRefusal?: (error: ConfigLoadError) => void): Promise<void> {
|
|
686
1475
|
try {
|
|
687
1476
|
await action();
|
|
688
1477
|
} catch (error) {
|
|
689
1478
|
if (error instanceof ConfigLoadError) {
|
|
690
1479
|
process.stderr.write(`gruff-ts: config error\n ${error.message}\n\nSuggested fix:\n ${error.suggestion}\n`);
|
|
1480
|
+
publishRefusal?.(error);
|
|
691
1481
|
process.exitCode = 2;
|
|
692
1482
|
return;
|
|
693
1483
|
}
|