@blundergoat/gruff-ts 0.5.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 +82 -0
- package/CONTRIBUTING.md +32 -25
- package/README.md +49 -50
- package/SECURITY.md +18 -31
- package/UPGRADING.md +101 -0
- package/bin/gruff-ts +3 -0
- package/docs/README.md +11 -10
- package/docs/agent-hook.md +32 -35
- package/docs/ci-integration.md +38 -24
- package/docs/configuration.md +160 -89
- 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 -172
- package/docs/rules.md +126 -98
- package/package.json +10 -8
- package/src/analyser.ts +817 -323
- 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 +62 -68
- package/src/blocks.ts +512 -336
- package/src/changed-regions.ts +380 -79
- package/src/check-ignore.ts +28 -13
- package/src/class-rules.ts +445 -436
- package/src/cli-program.ts +915 -172
- package/src/cli.ts +9 -3
- package/src/comment-rules.ts +236 -418
- package/src/comment-scanner.ts +339 -47
- package/src/complexity-metrics.ts +111 -35
- 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 +751 -223
- package/src/constants.ts +7 -6
- package/src/context-doc-rules.ts +182 -54
- package/src/dashboard.ts +88 -23
- package/src/dead-code-rules.ts +153 -74
- package/src/discovery.ts +493 -140
- package/src/doc-rules.ts +602 -126
- package/src/duplicate-test-group-rules.ts +359 -0
- package/src/findings-helpers.ts +134 -109
- package/src/findings.ts +47 -27
- package/src/fixture-purpose-rules.ts +194 -50
- package/src/github-actions-event-guards.ts +331 -0
- package/src/github-actions-rules.ts +328 -121
- package/src/hook-contract.ts +681 -255
- package/src/init-config.ts +163 -118
- package/src/inline-suppressions.ts +340 -0
- package/src/limit-band.ts +56 -0
- package/src/line-rules.ts +331 -468
- package/src/migrate-config.ts +670 -0
- package/src/naming-pushers.ts +32 -127
- package/src/parsed-script.ts +868 -314
- package/src/pillar-summary.ts +56 -40
- package/src/profiles.ts +86 -74
- package/src/project-config-rules.ts +324 -140
- package/src/project-rules.ts +237 -115
- package/src/public-exports.ts +102 -38
- package/src/report-html.ts +217 -85
- package/src/report-renderers.ts +821 -203
- package/src/rule-list.ts +166 -46
- package/src/rules.ts +100 -104
- package/src/safety-rules.ts +191 -132
- package/src/scoring.ts +249 -55
- package/src/security-flow-rules.ts +791 -115
- package/src/selectors.ts +169 -0
- package/src/sensitive-data-rules.ts +460 -387
- package/src/sensitive-exclusions.ts +435 -0
- package/src/source-text.ts +378 -104
- package/src/static-analysis-redundant-rules.ts +298 -41
- package/src/test-block-rules.ts +343 -253
- package/src/text-scans.ts +62 -11
- package/src/types.ts +220 -71
- package/tsconfig.json +2 -1
- package/src/process-exec-metadata.ts +0 -163
- package/src/test-fixtures.ts +0 -671
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 {
|
|
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)
|
|
353
|
+
.option("--deep-scan-budget <lines:bytes|off>", "Override both deep-scan bounds as LINES:BYTES, or disable the budget with off.", parseDeepScanBudget)
|
|
186
354
|
.option("--format <format>", "Output format: text, json, html, markdown, github, hotspot, or sarif.", parseAnalyseFormat, "text")
|
|
187
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.")
|
|
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.")
|
|
192
372
|
.option("--changed-scope <scope>", "Changed-region scope: hunk, symbol, or file.", parseChangedScope, "symbol")
|
|
193
|
-
.option("--history-file <path>", "Append score trend history to this JSON file (full scans only; incompatible with --diff, --since, and --changed-ranges).")
|
|
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,25 +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.")
|
|
249
|
-
.option("--fail-on-diagnostics", "Exit
|
|
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.")
|
|
250
461
|
.action((paths: string[], rawOptions: Record<string, unknown>) => {
|
|
462
|
+
// An integration can discover supported options before sending any files to scan.
|
|
251
463
|
if (rawOptions.capabilities === true) {
|
|
252
464
|
writeCommandOutput(program, renderHookCapabilities());
|
|
253
465
|
process.exitCode = 0;
|
|
@@ -255,30 +467,44 @@ function registerHookCommand(program: Command, runAnalyse: AnalyseRunner): void
|
|
|
255
467
|
}
|
|
256
468
|
try {
|
|
257
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
|
+
}
|
|
258
484
|
const currentOptions = hookCurrentOptions(scopedOptions);
|
|
259
485
|
const rendered = renderHookReport(runAnalyse, {
|
|
260
486
|
currentOptions,
|
|
261
487
|
scopedOptions,
|
|
262
|
-
...
|
|
488
|
+
...baseline,
|
|
263
489
|
...hookDiffBase(scopedOptions),
|
|
264
490
|
hasChangedRegion: hasHookChangedRegion(scopedOptions),
|
|
265
491
|
});
|
|
266
492
|
writeCommandOutput(program, rendered);
|
|
267
|
-
//
|
|
268
|
-
|
|
269
|
-
process.exitCode = rawOptions.failOnDiagnostics === true && hookRenderedDiagnosticsCount(rendered) > 0 ? 2 : 0;
|
|
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));
|
|
270
495
|
} catch (error) {
|
|
496
|
+
// A project may still use an older config schema. Give the integration the loader's instructions.
|
|
271
497
|
if (error instanceof ConfigLoadError) {
|
|
272
498
|
writeCommandOutput(program, renderHookConfigError(error.message, error.suggestion));
|
|
273
|
-
process.exitCode =
|
|
499
|
+
process.exitCode = USAGE_EXIT_CODE;
|
|
274
500
|
return;
|
|
275
501
|
}
|
|
502
|
+
// A missing review file, for example, is a fatal diagnostic in the hook's standard response.
|
|
276
503
|
if (error instanceof Error) {
|
|
277
|
-
//
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
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;
|
|
282
508
|
return;
|
|
283
509
|
}
|
|
284
510
|
throw error;
|
|
@@ -286,9 +512,14 @@ function registerHookCommand(program: Command, runAnalyse: AnalyseRunner): void
|
|
|
286
512
|
});
|
|
287
513
|
}
|
|
288
514
|
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
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
|
+
*/
|
|
292
523
|
function checkIgnoreOptions(paths: string[], rawOptions: Record<string, unknown>): AnalysisOptions {
|
|
293
524
|
return {
|
|
294
525
|
paths,
|
|
@@ -302,8 +533,12 @@ function checkIgnoreOptions(paths: string[], rawOptions: Record<string, unknown>
|
|
|
302
533
|
};
|
|
303
534
|
}
|
|
304
535
|
|
|
305
|
-
|
|
306
|
-
|
|
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
|
+
*/
|
|
307
542
|
function registerCompletionCommand(program: Command): void {
|
|
308
543
|
program
|
|
309
544
|
.command("completion")
|
|
@@ -314,8 +549,14 @@ function registerCompletionCommand(program: Command): void {
|
|
|
314
549
|
});
|
|
315
550
|
}
|
|
316
551
|
|
|
317
|
-
|
|
318
|
-
|
|
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
|
+
*/
|
|
319
560
|
function registerDashboardCommand(program: Command, runAnalyse: AnalyseRunner): void {
|
|
320
561
|
program
|
|
321
562
|
.command("dashboard")
|
|
@@ -324,18 +565,24 @@ function registerDashboardCommand(program: Command, runAnalyse: AnalyseRunner):
|
|
|
324
565
|
.option("--port <port>", "Port to bind.", "8767")
|
|
325
566
|
.option("--project-root <path>", "Default project root.", ".")
|
|
326
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)
|
|
327
569
|
.option("--scan-timeout <seconds>", "Accepted for cross-port compatibility; not implemented in gruff-ts.")
|
|
328
570
|
.action(async (rawOptions: Record<string, unknown>) => {
|
|
329
571
|
const projectRoot = resolve(String(rawOptions.projectRoot ?? "."));
|
|
330
572
|
await maybePromptInitConfig(program, projectRoot, { shouldSkipConfig: false, hasExplicitConfig: false });
|
|
331
573
|
const profile = typeof rawOptions.profile === "string" ? rawOptions.profile : undefined;
|
|
332
|
-
|
|
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);
|
|
333
576
|
});
|
|
334
577
|
}
|
|
335
578
|
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
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
|
+
*/
|
|
339
586
|
function registerInitCommand(program: Command): void {
|
|
340
587
|
program
|
|
341
588
|
.command("init")
|
|
@@ -353,7 +600,13 @@ function registerInitCommand(program: Command): void {
|
|
|
353
600
|
});
|
|
354
601
|
}
|
|
355
602
|
|
|
356
|
-
|
|
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
|
+
*/
|
|
357
610
|
function initSuccessMessage(verb: "Wrote" | "Overwrote", configPath: string): string {
|
|
358
611
|
return [
|
|
359
612
|
`${verb} ${configPath}`,
|
|
@@ -365,8 +618,12 @@ function initSuccessMessage(verb: "Wrote" | "Overwrote", configPath: string): st
|
|
|
365
618
|
].join("\n");
|
|
366
619
|
}
|
|
367
620
|
|
|
368
|
-
|
|
369
|
-
|
|
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
|
+
*/
|
|
370
627
|
function registerListCommand(program: Command): void {
|
|
371
628
|
program
|
|
372
629
|
.command("list")
|
|
@@ -376,9 +633,13 @@ function registerListCommand(program: Command): void {
|
|
|
376
633
|
});
|
|
377
634
|
}
|
|
378
635
|
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
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
|
+
*/
|
|
382
643
|
function registerListProfilesCommand(program: Command): void {
|
|
383
644
|
program
|
|
384
645
|
.command("list-profiles")
|
|
@@ -390,10 +651,13 @@ function registerListProfilesCommand(program: Command): void {
|
|
|
390
651
|
});
|
|
391
652
|
}
|
|
392
653
|
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
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
|
+
*/
|
|
397
661
|
function registerListRulesCommand(program: Command): void {
|
|
398
662
|
program
|
|
399
663
|
.command("list-rules")
|
|
@@ -415,9 +679,14 @@ function registerListRulesCommand(program: Command): void {
|
|
|
415
679
|
});
|
|
416
680
|
}
|
|
417
681
|
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
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
|
+
*/
|
|
421
690
|
function registerReportCommand(program: Command, runAnalyse: AnalyseRunner): void {
|
|
422
691
|
program
|
|
423
692
|
.command("report")
|
|
@@ -428,28 +697,44 @@ function registerReportCommand(program: Command, runAnalyse: AnalyseRunner): voi
|
|
|
428
697
|
.option("--config <path>", "Path to a gruff YAML config file.")
|
|
429
698
|
.option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
|
|
430
699
|
.option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
|
|
700
|
+
.option("--deep-scan-budget <lines:bytes|off>", "Override both deep-scan bounds as LINES:BYTES, or disable the budget with off.", parseDeepScanBudget)
|
|
431
701
|
.option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", parseFailOn, "none")
|
|
432
702
|
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
433
|
-
.option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
|
|
434
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
|
+
}
|
|
435
710
|
await runWithConfigErrorHandling(async () => {
|
|
436
711
|
const format = rawOptions.format === "json" ? "json" : "html";
|
|
437
712
|
const baseOptions = normalizeOptions(paths, { ...rawOptions, format }, { shouldAllowBaselineFlag: false });
|
|
438
|
-
const options =
|
|
439
|
-
await maybePromptInitConfig(program,
|
|
713
|
+
const { options, displayFloor } = configuredSeverities(baseOptions, "report", command);
|
|
714
|
+
await maybePromptInitConfig(program, projectRootFromTargets(options.paths), promptOptionsFromAnalysis(options));
|
|
440
715
|
const report = runAnalyse(options);
|
|
441
|
-
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.
|
|
442
720
|
if (typeof rawOptions.output === "string") {
|
|
443
721
|
writeFileSync(rawOptions.output, rendered);
|
|
444
722
|
} else {
|
|
445
723
|
writeCommandOutput(program, rendered);
|
|
446
724
|
}
|
|
447
|
-
process.exitCode =
|
|
448
|
-
});
|
|
725
|
+
process.exitCode = status;
|
|
726
|
+
}, (error) => writeFailedRunEnvelope(program, rawOptions.format, error));
|
|
449
727
|
});
|
|
450
728
|
}
|
|
451
729
|
|
|
452
|
-
|
|
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
|
+
*/
|
|
453
738
|
function registerSummaryCommand(program: Command, runAnalyse: AnalyseRunner): void {
|
|
454
739
|
program
|
|
455
740
|
.command("summary")
|
|
@@ -460,39 +745,54 @@ function registerSummaryCommand(program: Command, runAnalyse: AnalyseRunner): vo
|
|
|
460
745
|
.option("--config <path>", "Path to a gruff YAML config file.")
|
|
461
746
|
.option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
|
|
462
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)
|
|
463
749
|
.option("--format <format>", "Output format: text or json.", parseSummaryFormat, "text")
|
|
464
750
|
.option("--top <n>", "How many top rules and file offenders to list.", parseNonNegativeInteger, 10)
|
|
465
|
-
|
|
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")
|
|
466
753
|
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
467
754
|
.option("--diff [mode]", "Filter findings to changed files. Use working-tree, staged, unstaged, or a base ref.")
|
|
468
755
|
.option("--history-file <path>", "Append score trend history to this JSON file (full scans only; incompatible with --diff).")
|
|
469
756
|
.option("--baseline [path]", "Suppress findings that match a gruff baseline JSON file.")
|
|
470
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.")
|
|
471
760
|
.option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
|
|
472
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
|
+
}
|
|
473
768
|
await runWithConfigErrorHandling(async () => {
|
|
474
|
-
const baseOptions = normalizeOptions(paths, { ...rawOptions, format: "text" }, { shouldAllowBaselineFlag: true });
|
|
475
|
-
const options = applyMinimumSeverityPrecedence(baseOptions, "summary", command);
|
|
476
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);
|
|
477
772
|
const top = typeof rawOptions.top === "number" ? rawOptions.top : 10;
|
|
478
|
-
await maybePromptInitConfig(program,
|
|
773
|
+
await maybePromptInitConfig(program, projectRootFromTargets(options.paths), promptOptionsFromAnalysis(options));
|
|
479
774
|
const startedAt = performance.now();
|
|
480
775
|
const report = runAnalyse(options);
|
|
481
776
|
const elapsedMs = performance.now() - startedAt;
|
|
482
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);
|
|
483
781
|
const rendered = summaryFormat === "json"
|
|
484
|
-
? renderSummaryJson(report,
|
|
782
|
+
? renderSummaryJson(report, status)
|
|
485
783
|
: renderSummary(report, elapsedMs, pathLabel, top);
|
|
486
784
|
writeCommandOutput(program, rendered);
|
|
487
|
-
process.exitCode =
|
|
488
|
-
});
|
|
785
|
+
process.exitCode = status;
|
|
786
|
+
}, (error) => writeFailedRunEnvelope(program, rawOptions.format, error, true));
|
|
489
787
|
});
|
|
490
788
|
}
|
|
491
789
|
|
|
492
|
-
|
|
493
|
-
*
|
|
494
|
-
*
|
|
495
|
-
*
|
|
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
|
|
496
796
|
*/
|
|
497
797
|
function parseSummaryFormat(rawFormat: string): "text" | "json" {
|
|
498
798
|
if (rawFormat === "text" || rawFormat === "json") {
|
|
@@ -501,8 +801,13 @@ function parseSummaryFormat(rawFormat: string): "text" | "json" {
|
|
|
501
801
|
throw new InvalidArgumentError("must be text or json");
|
|
502
802
|
}
|
|
503
803
|
|
|
504
|
-
|
|
505
|
-
|
|
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
|
+
*/
|
|
506
811
|
function parseHookFormat(rawFormat: string): "json" {
|
|
507
812
|
if (rawFormat === "json") {
|
|
508
813
|
return rawFormat;
|
|
@@ -510,15 +815,15 @@ function parseHookFormat(rawFormat: string): "json" {
|
|
|
510
815
|
throw new InvalidArgumentError("must be json");
|
|
511
816
|
}
|
|
512
817
|
|
|
513
|
-
|
|
514
|
-
*
|
|
515
|
-
*
|
|
516
|
-
*
|
|
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
|
|
517
824
|
*/
|
|
518
825
|
function parseChoiceOf(choices: readonly string[]): (rawValue: string) => string {
|
|
519
|
-
// Validates one raw CLI value against the documented set; throws InvalidArgumentError otherwise.
|
|
520
826
|
return (rawValue: string): string => {
|
|
521
|
-
// A value outside the documented set is a caller mistake, never a silent default.
|
|
522
827
|
if (choices.includes(rawValue)) {
|
|
523
828
|
return rawValue;
|
|
524
829
|
}
|
|
@@ -530,10 +835,172 @@ const parseAnalyseFormat = parseChoiceOf(["text", "json", "html", "markdown", "g
|
|
|
530
835
|
const parseReportFormat = parseChoiceOf(["html", "json"]);
|
|
531
836
|
const parseFailOn = parseChoiceOf(["none", "advisory", "warning", "error"]);
|
|
532
837
|
const parseChangedScope = parseChoiceOf(["symbol", "hunk", "file"]);
|
|
838
|
+
const parseConfidence = parseChoiceOf(["low", "medium", "high"]);
|
|
839
|
+
const parseMinSeverity = parseChoiceOf(["advisory", "warning", "error"]);
|
|
533
840
|
|
|
534
|
-
|
|
535
|
-
*
|
|
536
|
-
*
|
|
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
|
|
537
1004
|
*/
|
|
538
1005
|
function parseNonNegativeInteger(rawCount: string): number {
|
|
539
1006
|
const parsed = Number(rawCount);
|
|
@@ -543,7 +1010,13 @@ function parseNonNegativeInteger(rawCount: string): number {
|
|
|
543
1010
|
return parsed;
|
|
544
1011
|
}
|
|
545
1012
|
|
|
546
|
-
|
|
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
|
+
*/
|
|
547
1020
|
function summaryPathLabel(paths: string[], projectRoot: string): string {
|
|
548
1021
|
if (paths.length === 0) {
|
|
549
1022
|
return projectRoot;
|
|
@@ -551,12 +1024,27 @@ function summaryPathLabel(paths: string[], projectRoot: string): string {
|
|
|
551
1024
|
return paths.map((path) => resolve(path)).join(", ");
|
|
552
1025
|
}
|
|
553
1026
|
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
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
|
+
*/
|
|
558
1037
|
function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>, context: NormalizeContext): AnalysisOptions {
|
|
559
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
|
+
}
|
|
560
1048
|
const format = stringChoice(rawOptions.format, ["text", "json", "html", "markdown", "github", "hotspot", "sarif"], "text");
|
|
561
1049
|
const failOn = stringChoice(rawOptions.failOn, ["none", "advisory", "warning", "error"], "advisory");
|
|
562
1050
|
const diffInput = diffOption(paths, rawOptions);
|
|
@@ -569,6 +1057,7 @@ function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>,
|
|
|
569
1057
|
paths: diffInput.paths,
|
|
570
1058
|
...configOption(rawOptions),
|
|
571
1059
|
...profileOption(rawOptions),
|
|
1060
|
+
...deepScanBudgetOption(rawOptions),
|
|
572
1061
|
shouldSkipConfig:
|
|
573
1062
|
rawOptions.config === false ||
|
|
574
1063
|
rawOptions.noConfig === true,
|
|
@@ -581,31 +1070,58 @@ function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>,
|
|
|
581
1070
|
...sinceOption(rawOptions),
|
|
582
1071
|
...historyFileOption(rawOptions),
|
|
583
1072
|
...baselineOption(baselineValue, context),
|
|
584
|
-
...
|
|
1073
|
+
...generation,
|
|
1074
|
+
...migrateBaselineOption(rawOptions),
|
|
1075
|
+
...(rawOptions.force === true ? { shouldForceBaselineOverwrite: true } : {}),
|
|
585
1076
|
shouldSkipBaseline,
|
|
1077
|
+
execution: executionSelectorsFrom(rawOptions),
|
|
586
1078
|
};
|
|
587
1079
|
}
|
|
588
1080
|
|
|
589
|
-
|
|
590
|
-
* Rejects a history
|
|
591
|
-
*
|
|
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.
|
|
592
1088
|
*/
|
|
593
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
|
+
}
|
|
594
1094
|
const hasChangedRegionSelector = rawOptions.diff === true
|
|
595
1095
|
|| typeof rawOptions.diff === "string"
|
|
1096
|
+
|| typeof rawOptions.diffBase === "string"
|
|
596
1097
|
|| typeof rawOptions.since === "string"
|
|
597
1098
|
|| typeof rawOptions.changedRanges === "string";
|
|
598
1099
|
// A filtered request would mix partial scores into the full-project trend users review.
|
|
599
|
-
if (
|
|
1100
|
+
if (hasChangedRegionSelector) {
|
|
600
1101
|
throw new ConfigLoadError(
|
|
601
|
-
"`--history-file` requires a full scan and cannot be combined with `--diff`, `--since`, or `--changed-ranges`.",
|
|
1102
|
+
"`--history-file` requires a full scan and cannot be combined with `--diff`, `--diff-base`, `--since`, or `--changed-ranges`.",
|
|
602
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,
|
|
603
1113
|
);
|
|
604
1114
|
}
|
|
605
1115
|
}
|
|
606
1116
|
|
|
607
|
-
|
|
608
|
-
|
|
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
|
+
*/
|
|
609
1125
|
function hookScopedOptions(paths: string[], rawOptions: Record<string, unknown>): AnalysisOptions {
|
|
610
1126
|
return normalizeOptions(
|
|
611
1127
|
paths,
|
|
@@ -614,72 +1130,207 @@ function hookScopedOptions(paths: string[], rawOptions: Record<string, unknown>)
|
|
|
614
1130
|
);
|
|
615
1131
|
}
|
|
616
1132
|
|
|
617
|
-
|
|
618
|
-
|
|
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
|
+
*/
|
|
619
1140
|
function hookCurrentOptions(options: AnalysisOptions): AnalysisOptions {
|
|
620
|
-
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;
|
|
621
1142
|
return { ...rest, shouldSkipBaseline: true };
|
|
622
1143
|
}
|
|
623
1144
|
|
|
624
|
-
|
|
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
|
+
*/
|
|
625
1152
|
function hasHookChangedRegion(options: AnalysisOptions): boolean {
|
|
626
|
-
return
|
|
1153
|
+
return options.changedRanges !== undefined || options.diffPatch !== undefined || Boolean(options.diff || options.since);
|
|
627
1154
|
}
|
|
628
1155
|
|
|
629
|
-
|
|
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
|
+
*/
|
|
630
1162
|
function hookBaselinePath(rawOptions: Record<string, unknown>): Partial<{ baselinePath: string }> {
|
|
631
1163
|
return typeof rawOptions.baseline === "string" ? { baselinePath: rawOptions.baseline } : {};
|
|
632
1164
|
}
|
|
633
1165
|
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
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 {};
|
|
637
1187
|
}
|
|
638
1188
|
|
|
639
|
-
|
|
640
|
-
|
|
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
|
+
*/
|
|
641
1195
|
function configOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "config">> {
|
|
642
1196
|
return typeof rawOptions.config === "string" ? { config: rawOptions.config } : {};
|
|
643
1197
|
}
|
|
644
1198
|
|
|
645
|
-
|
|
646
|
-
|
|
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
|
+
*/
|
|
647
1205
|
function profileOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "profile">> {
|
|
648
1206
|
return typeof rawOptions.profile === "string" ? { profile: rawOptions.profile } : {};
|
|
649
1207
|
}
|
|
650
1208
|
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
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 -`.
|
|
654
1284
|
if (typeof rawOptions.diff === "string") {
|
|
655
1285
|
return rawOptions.diff === "-"
|
|
656
|
-
? { paths, options: { diff: "-", diffPatch: readFileSync(0, "utf8") } }
|
|
1286
|
+
? { paths, options: shouldReadStdin ? { diff: "-", diffPatch: readFileSync(0, "utf8") } : { diff: "-" } }
|
|
657
1287
|
: { paths, options: { diff: rawOptions.diff } };
|
|
658
1288
|
}
|
|
1289
|
+
// In `analyse --diff - src/app.ts`, Commander parses `--diff` as bare `true` and leaves `-` as the first positional path.
|
|
659
1290
|
if (rawOptions.diff === true && paths[0] === "-") {
|
|
660
|
-
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: "-" } };
|
|
661
1292
|
}
|
|
1293
|
+
// Bare `analyse --diff` with no mode compares uncommitted working-tree changes; omitting `--diff` runs a full scan.
|
|
662
1294
|
return rawOptions.diff === true ? { paths, options: { diff: "working-tree" } } : { paths, options: {} };
|
|
663
1295
|
}
|
|
664
1296
|
|
|
665
|
-
|
|
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
|
+
*/
|
|
666
1303
|
function changedRangesOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "changedRanges">> {
|
|
667
1304
|
return typeof rawOptions.changedRanges === "string" ? { changedRanges: rawOptions.changedRanges } : {};
|
|
668
1305
|
}
|
|
669
1306
|
|
|
670
|
-
|
|
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
|
+
*/
|
|
671
1313
|
function sinceOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "since">> {
|
|
672
1314
|
return typeof rawOptions.since === "string" ? { since: rawOptions.since } : {};
|
|
673
1315
|
}
|
|
674
1316
|
|
|
675
|
-
|
|
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
|
+
*/
|
|
676
1323
|
function historyFileOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "historyFile">> {
|
|
677
1324
|
return typeof rawOptions.historyFile === "string" ? { historyFile: rawOptions.historyFile } : {};
|
|
678
1325
|
}
|
|
679
1326
|
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
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
|
+
*/
|
|
683
1334
|
function baselineOption(baselineValue: unknown, context: NormalizeContext): Partial<Pick<AnalysisOptions, "baseline">> {
|
|
684
1335
|
if (!context.shouldAllowBaselineFlag) {
|
|
685
1336
|
return {};
|
|
@@ -690,8 +1341,12 @@ function baselineOption(baselineValue: unknown, context: NormalizeContext): Part
|
|
|
690
1341
|
return baselineValue === true ? { baseline: DEFAULT_BASELINE } : {};
|
|
691
1342
|
}
|
|
692
1343
|
|
|
693
|
-
|
|
694
|
-
|
|
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
|
+
*/
|
|
695
1350
|
function generateBaselineOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "generateBaseline">> {
|
|
696
1351
|
if (typeof rawOptions.generateBaseline === "string") {
|
|
697
1352
|
return { generateBaseline: rawOptions.generateBaseline };
|
|
@@ -699,42 +1354,130 @@ function generateBaselineOption(rawOptions: Record<string, unknown>): Partial<Pi
|
|
|
699
1354
|
return rawOptions.generateBaseline === true ? { generateBaseline: DEFAULT_BASELINE } : {};
|
|
700
1355
|
}
|
|
701
1356
|
|
|
702
|
-
|
|
703
|
-
|
|
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
|
+
*/
|
|
704
1375
|
function stringChoice<T extends string>(rawValue: unknown, choices: readonly T[], fallback: T): T {
|
|
705
1376
|
return typeof rawValue === "string" && choices.includes(rawValue as T) ? (rawValue as T) : fallback;
|
|
706
1377
|
}
|
|
707
1378
|
|
|
708
1379
|
/*
|
|
709
|
-
*
|
|
710
|
-
*
|
|
711
|
-
*
|
|
712
|
-
*
|
|
713
|
-
*
|
|
714
|
-
* 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`).
|
|
715
1385
|
*/
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
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;
|
|
719
1424
|
}
|
|
720
|
-
const
|
|
721
|
-
const
|
|
722
|
-
|
|
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);
|
|
723
1430
|
}
|
|
724
1431
|
|
|
725
|
-
|
|
726
|
-
*
|
|
727
|
-
*
|
|
728
|
-
*
|
|
729
|
-
*
|
|
730
|
-
*
|
|
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
|
|
731
1473
|
*/
|
|
732
|
-
async function runWithConfigErrorHandling(action: () => Promise<void> | void): Promise<void> {
|
|
1474
|
+
async function runWithConfigErrorHandling(action: () => Promise<void> | void, publishRefusal?: (error: ConfigLoadError) => void): Promise<void> {
|
|
733
1475
|
try {
|
|
734
1476
|
await action();
|
|
735
1477
|
} catch (error) {
|
|
736
1478
|
if (error instanceof ConfigLoadError) {
|
|
737
1479
|
process.stderr.write(`gruff-ts: config error\n ${error.message}\n\nSuggested fix:\n ${error.suggestion}\n`);
|
|
1480
|
+
publishRefusal?.(error);
|
|
738
1481
|
process.exitCode = 2;
|
|
739
1482
|
return;
|
|
740
1483
|
}
|