@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/config.ts
CHANGED
|
@@ -1,92 +1,165 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
1
|
+
// Resolves the project settings used by analyse, summary, report, and hook.
|
|
2
|
+
//
|
|
3
|
+
// Starts with built-in defaults and layers on settings from the user's project, profile, and command flags.
|
|
4
|
+
// Invalid settings produce a startup error before the user relies on the requested scan or exit gate.
|
|
3
5
|
import { existsSync } from "node:fs";
|
|
4
|
-
import { dirname, isAbsolute, join } from "node:path";
|
|
6
|
+
import { basename, dirname, isAbsolute, join } from "node:path";
|
|
5
7
|
import { arrayValue, isString, objectValue, parseConfigFile, SUGGEST_EDIT_CONFIG, SUGGEST_INIT_FORCE } from "./config-parse.ts";
|
|
6
8
|
import { ConfigLoadError } from "./config-load-error.ts";
|
|
7
9
|
import { BUILT_IN_PROFILES, builtInProfileNames, DEFAULT_PROFILE_NAME, isKnownRuleId, ruleOptionKeys } from "./profiles.ts";
|
|
8
|
-
import
|
|
10
|
+
import { ruleDefaultEnabled } from "./rules.ts";
|
|
11
|
+
import { applyExecutionSelectors } from "./selectors.ts";
|
|
12
|
+
import { parseSensitiveExclusions } from "./sensitive-exclusions.ts";
|
|
13
|
+
import type { AnalysisOptions, Config, DeepScanBudgetOverride, FailThreshold, InlineProfileSpec, MinimumSeverityCommand, ProfileDefinition, ProfileRuleSetting, ProfileSpec, Severity } from "./types.ts";
|
|
9
14
|
|
|
15
|
+
// Represents one validated per-rule override before it joins the user's effective configuration.
|
|
16
|
+
//
|
|
17
|
+
// Optional fields preserve the difference between an omitted setting and an explicit value.
|
|
10
18
|
type RuleOverride = Config["rules"] extends Map<string, infer RuleOverrideValue> ? RuleOverrideValue : never;
|
|
11
19
|
|
|
12
20
|
const DEFAULT_CONFIG_FILES = [".gruff-ts.yaml", ".gruff.json", ".gruff.yaml", ".gruff.yml"] as const;
|
|
13
21
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
22
|
+
/*
|
|
23
|
+
* Every key a `.gruff-ts.yaml` may carry, at the root and inside the two blocks that take a fixed set.
|
|
24
|
+
*
|
|
25
|
+
* A key outside these sets is refused rather than ignored: a misspelled `sensitivExclusions:` or `minimumSeverty:`
|
|
26
|
+
* that loads silently is a setting the user believes is in force and is not, which is the one configuration failure
|
|
27
|
+
* a reader cannot see by looking at their own file.
|
|
28
|
+
*/
|
|
29
|
+
const KNOWN_ROOT_KEYS: ReadonlySet<string> = new Set([
|
|
30
|
+
"schemaVersion", "profile", "deepScanBudget", "minimumSeverity", "failOn", "paths", "allowlists", "rules", "sensitiveExclusions",
|
|
31
|
+
]);
|
|
32
|
+
const KNOWN_PATHS_KEYS: ReadonlySet<string> = new Set(["ignore"]);
|
|
33
|
+
const KNOWN_ALLOWLISTS_KEYS: ReadonlySet<string> = new Set([
|
|
34
|
+
"acceptedAbbreviations", "acceptedClassFilePairs", "placeholderNames", "trackingTokens",
|
|
35
|
+
]);
|
|
36
|
+
// Recognised separately so the loader can refuse it by name with section 5's explanation without advertising it as a valid key.
|
|
37
|
+
const REFUSED_ALLOWLISTS_KEYS: ReadonlySet<string> = new Set(["secretPreviews"]);
|
|
38
|
+
const LEGACY_SECRET_PREVIEWS_ERROR = 'Config key "allowlists.secretPreviews" is removed in 0.6.0: FAMILY-CONTRACT.md section 5 makes category markers unconditional, so the key authorises nothing; delete it from the configuration.';
|
|
39
|
+
const LEGACY_MINIMUM_SEVERITY_ERROR = 'Config key "minimumSeverity" is the display floor in 0.6.0 and takes one severity, not a per-command map; move the per-command exit gate to "failOn", which is the key that gates the exit code.';
|
|
40
|
+
// Pinned-corpus size and scan-cost measurements set these paired defaults because either line count
|
|
41
|
+
// or byte count can make deep parsing disproportionately expensive while ordinary source stays below both.
|
|
42
|
+
export const DEEP_SCAN_DEFAULT_MAX_LINES = 20_000;
|
|
43
|
+
export const DEEP_SCAN_DEFAULT_MAX_BYTES = 2_000_000;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Creates the complete zero-config behavior used when a user runs Gruff without custom settings.
|
|
47
|
+
* User and profile values may overlay these defaults later; the schema version remains fixed for this release.
|
|
48
|
+
*
|
|
49
|
+
* @returns Default configuration with built-in allowlists, empty rule overrides, and default deep-scan limits.
|
|
50
|
+
*/
|
|
18
51
|
function defaultConfig(): Config {
|
|
19
52
|
return {
|
|
20
53
|
schemaVersion: "gruff-ts.config.v0.1",
|
|
21
54
|
ignoredPaths: [],
|
|
22
55
|
acceptedAbbreviations: new Set(["age", "app", "db", "fs", "id", "io", "key", "log", "max", "min", "now", "raw", "rx", "tx", "ui", "url"]),
|
|
23
|
-
secretPreviews: new Set(),
|
|
24
|
-
bannedGenericNames: new Set(["process", "handle", "doit", "run", "execute", "manage"]),
|
|
25
|
-
acceptedBooleanNames: new Set(["all", "apply", "check", "dev", "enabled", "force", "fresh", "harness", "json", "ok", "verbose", "yes"]),
|
|
26
56
|
acceptedClassFilePairs: new Set(),
|
|
27
|
-
acceptedCasingPairs: new Set(),
|
|
28
|
-
booleanPrefixes: new Set(["is", "has", "can", "should", "does", "did", "was", "will", "may", "in", "scan", "supports", "requires", "allow", "check", "enable", "exclude", "include", "omit", "skip", "with", "without"]),
|
|
29
|
-
hungarianPrefixes: new Set(["str", "obj", "arr", "bool", "int", "num"]),
|
|
30
57
|
placeholderNames: new Set(["foo", "bar", "baz", "tmp", "temp", "thing", "stuff", "data", "value", "item"]),
|
|
31
|
-
|
|
32
|
-
knownAcronyms: new Set(["url", "http", "https", "id", "xml", "json", "html", "css", "api", "sql", "db", "io", "ui", "uuid", "ip", "tcp", "udp", "ast", "cli", "npm"]),
|
|
58
|
+
trackingTokens: [],
|
|
33
59
|
minimumSeverity: new Map(),
|
|
34
60
|
rules: new Map(),
|
|
61
|
+
deepScanBudget: {
|
|
62
|
+
enabled: true,
|
|
63
|
+
maxLines: DEEP_SCAN_DEFAULT_MAX_LINES,
|
|
64
|
+
maxBytes: DEEP_SCAN_DEFAULT_MAX_BYTES,
|
|
65
|
+
override: "default",
|
|
66
|
+
},
|
|
67
|
+
sensitiveExclusions: [],
|
|
35
68
|
};
|
|
36
69
|
}
|
|
37
70
|
|
|
38
|
-
|
|
71
|
+
/**
|
|
72
|
+
* Resolves a user-supplied config or profile path against the caller's base directory.
|
|
73
|
+
* Absolute paths remain unchanged so CLI and config-file references behave consistently.
|
|
74
|
+
*
|
|
75
|
+
* @param projectRoot - base directory used to anchor relative paths
|
|
76
|
+
* @param path - user-supplied config or profile path to resolve
|
|
77
|
+
* @returns Original path when absolute, or the path joined under `projectRoot`.
|
|
78
|
+
*/
|
|
39
79
|
function absolutize(projectRoot: string, path: string): string {
|
|
40
80
|
return isAbsolute(path) ? path : join(projectRoot, path);
|
|
41
81
|
}
|
|
42
82
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
83
|
+
/**
|
|
84
|
+
* Builds effective analysis settings by layering the config file, profile, CLI budget, and rule selectors over defaults.
|
|
85
|
+
* A missing default file leaves built-in settings in place; read, parse, and validation errors stop loading.
|
|
86
|
+
*
|
|
87
|
+
* @param projectRoot - workspace root that anchors config discovery and profile resolution
|
|
88
|
+
* @param options - CLI options that can choose or skip a config file, override the profile, set budget, and select rules
|
|
89
|
+
* @returns Effective analysis settings after all config sources and overrides are applied.
|
|
90
|
+
*/
|
|
46
91
|
function loadConfig(projectRoot: string, options: AnalysisOptions): Config {
|
|
47
92
|
const config = defaultConfig();
|
|
48
93
|
const path = options.shouldSkipConfig ? undefined : selectedConfigPath(projectRoot, options);
|
|
49
|
-
const
|
|
94
|
+
const parsedConfig: Record<string, unknown> = path ? parseConfigFile(path, options.config ?? basename(path)) : {};
|
|
95
|
+
// Schema and supported-key checks apply to selected files. Zero-config use needs no file.
|
|
50
96
|
if (path) {
|
|
51
|
-
applyConfigValues(config,
|
|
97
|
+
applyConfigValues(config, parsedConfig);
|
|
52
98
|
}
|
|
53
|
-
applyProfile(config, options,
|
|
99
|
+
applyProfile(config, options, parsedConfig, projectRoot, path);
|
|
100
|
+
applyDeepScanBudgetOverride(config, options.deepScanBudget);
|
|
101
|
+
// The execution selectors choose which rules run, so they narrow the catalogue last, after every other source.
|
|
102
|
+
applyExecutionSelectors(config, options.execution);
|
|
54
103
|
return config;
|
|
55
104
|
}
|
|
56
105
|
|
|
57
|
-
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
106
|
+
/**
|
|
107
|
+
* Fills missing rule entries in the effective config from the selected profile and merges its ignore paths.
|
|
108
|
+
* Selects the CLI profile before the parsed file's profile even when file loading is skipped; profile errors stop loading.
|
|
109
|
+
*
|
|
110
|
+
* @param config - effective configuration updated in place with profile rule defaults and ignore paths
|
|
111
|
+
* @param options - CLI options that may supply an overriding profile specification
|
|
112
|
+
* @param parsedConfig - parsed config file mapping that may declare a `profile` entry
|
|
113
|
+
* @param projectRoot - base directory used to resolve a CLI profile path when relative
|
|
114
|
+
* @param configPath - resolved config path anchoring relative `profile:` entries in that config, or undefined when none loaded
|
|
115
|
+
* @returns Nothing. Mutates `config` in place when a profile is configured, or leaves it unchanged when omitted.
|
|
116
|
+
*/
|
|
117
|
+
function applyProfile(
|
|
118
|
+
config: Config,
|
|
119
|
+
options: AnalysisOptions,
|
|
120
|
+
parsedConfig: Record<string, unknown>,
|
|
121
|
+
projectRoot: string,
|
|
122
|
+
configPath: string | undefined,
|
|
123
|
+
): void {
|
|
124
|
+
const usesCliProfile = options.profile !== undefined;
|
|
125
|
+
const configuredProfile = usesCliProfile ? options.profile : parsedConfig.profile;
|
|
126
|
+
// When both sources omit a profile, the current defaults and explicit settings carry forward.
|
|
127
|
+
if (configuredProfile === undefined) {
|
|
69
128
|
return;
|
|
70
129
|
}
|
|
71
|
-
|
|
130
|
+
// A profile named inside a config file resolves relative to that config file's directory so `--config` and hook replay stay portable.
|
|
131
|
+
const baseDirectory = usesCliProfile || configPath === undefined ? projectRoot : dirname(configPath);
|
|
132
|
+
applyProfileUnderlay(config, resolveProfile(parseProfileSpec(configuredProfile), baseDirectory));
|
|
72
133
|
}
|
|
73
134
|
|
|
74
|
-
|
|
75
|
-
|
|
135
|
+
/**
|
|
136
|
+
* Fills the effective config's missing rule entries from the resolved profile.
|
|
137
|
+
* Profile ignore paths join explicit ignores so either user choice keeps a path out of the scan.
|
|
138
|
+
*
|
|
139
|
+
* @param config - effective configuration updated in place with fallback rule entries and merged ignore paths
|
|
140
|
+
* @param definition - resolved profile supplying rule settings and ignore paths
|
|
141
|
+
* @returns Nothing. Mutates `config.rules` and `config.ignoredPaths` in place.
|
|
142
|
+
*/
|
|
76
143
|
function applyProfileUnderlay(config: Config, definition: ProfileDefinition): void {
|
|
77
144
|
for (const [ruleId, setting] of definition.rules) {
|
|
145
|
+
// An existing rule entry came from the user's top-level config and must remain authoritative.
|
|
78
146
|
if (!config.rules.has(ruleId)) {
|
|
79
147
|
config.rules.set(ruleId, profileRuleToConfig(setting));
|
|
80
148
|
}
|
|
81
149
|
}
|
|
150
|
+
// Empty profile ignores leave the user's current scan surface unchanged.
|
|
82
151
|
if (definition.ignoredPaths.length > 0) {
|
|
83
152
|
config.ignoredPaths = [...new Set([...config.ignoredPaths, ...definition.ignoredPaths])];
|
|
84
153
|
}
|
|
85
154
|
}
|
|
86
155
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
156
|
+
/**
|
|
157
|
+
* Converts one profile rule into the shape used during analysis.
|
|
158
|
+
* Omitted fields stay absent, while missing options become an empty map for callers that enumerate them.
|
|
159
|
+
*
|
|
160
|
+
* @param setting - validated rule setting from a resolved profile
|
|
161
|
+
* @returns Per-rule override preserving explicit fields and defaulting `options` to an empty map.
|
|
162
|
+
*/
|
|
90
163
|
function profileRuleToConfig(setting: ProfileRuleSetting): RuleOverride {
|
|
91
164
|
return {
|
|
92
165
|
...(setting.enabled !== undefined ? { enabled: setting.enabled } : {}),
|
|
@@ -96,22 +169,14 @@ function profileRuleToConfig(setting: ProfileRuleSetting): RuleOverride {
|
|
|
96
169
|
};
|
|
97
170
|
}
|
|
98
171
|
|
|
99
|
-
|
|
100
|
-
* Resolves a
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
* same-rule fields (last assignment wins for a repeated key), and a child `ignoredPaths` array
|
|
108
|
-
* replaces - does not concatenate - the parent's. `chain` carries the ordered, already-visited file
|
|
109
|
-
* paths so a cycle (A extends B extends A) is rejected with a message naming both in order, instead of
|
|
110
|
-
* recursing until the stack overflows.
|
|
111
|
-
*
|
|
112
|
-
* Throws ConfigLoadError on: a missing `extends:` file, a rule id not in RULE_DESCRIPTORS, or an
|
|
113
|
-
* inheritance cycle. Every failure surfaces at config-load time, never at scan time. File paths only:
|
|
114
|
-
* `extends:` never fetches a remote URL or runs a shell.
|
|
172
|
+
/**
|
|
173
|
+
* Resolves a built-in, file-backed, or inline profile, with child overrides taking precedence.
|
|
174
|
+
* Keeps references local and uses the visit chain to report invalid profiles or explain inheritance cycles.
|
|
175
|
+
*
|
|
176
|
+
* @param spec - parsed profile reference string or inline profile specification
|
|
177
|
+
* @param projectRoot - directory used to resolve initial relative file paths
|
|
178
|
+
* @param chain - ancestor profile paths visited so far for inheritance cycle detection
|
|
179
|
+
* @returns Effective profile definition after resolving bases and applying overrides.
|
|
115
180
|
*/
|
|
116
181
|
function resolveProfile(spec: ProfileSpec, projectRoot: string, chain: string[] = []): ProfileDefinition {
|
|
117
182
|
if (typeof spec === "string") {
|
|
@@ -120,24 +185,38 @@ function resolveProfile(spec: ProfileSpec, projectRoot: string, chain: string[]
|
|
|
120
185
|
return resolveInlineProfile(spec, projectRoot, chain);
|
|
121
186
|
}
|
|
122
187
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
188
|
+
/**
|
|
189
|
+
* Resolves a bundled profile name or a local file reference into a profile definition.
|
|
190
|
+
* Bundled names take precedence; file resolution uses the visit chain to detect cycles and can fail with a config error.
|
|
191
|
+
*
|
|
192
|
+
* @param ref - built-in profile name or path to a local profile file
|
|
193
|
+
* @param projectRoot - directory from which relative file references are resolved
|
|
194
|
+
* @param chain - ancestor profile paths visited so far for cycle detection
|
|
195
|
+
* @returns Cloned built-in preset or resolved file-backed profile definition.
|
|
196
|
+
*/
|
|
128
197
|
function resolveProfileRef(ref: string, projectRoot: string, chain: string[]): ProfileDefinition {
|
|
129
198
|
const builtIn = BUILT_IN_PROFILES.get(ref) ?? BUILT_IN_PROFILES.get(`gruff.${ref}`);
|
|
199
|
+
// A bundled match receives its own rule map and ignore list so collection edits cannot alter the preset.
|
|
130
200
|
if (builtIn) {
|
|
131
201
|
return cloneProfileDefinition(builtIn);
|
|
132
202
|
}
|
|
133
203
|
return resolveProfileFile(ref, projectRoot, chain);
|
|
134
204
|
}
|
|
135
205
|
|
|
136
|
-
|
|
137
|
-
|
|
206
|
+
/**
|
|
207
|
+
* Loads a local profile with its inherited settings resolved before analysis.
|
|
208
|
+
* Resolves `ref` from `projectRoot`, uses the file's directory for relative bases, and lets other filesystem read errors propagate.
|
|
209
|
+
*
|
|
210
|
+
* @param ref - local profile file path to read and resolve
|
|
211
|
+
* @param projectRoot - directory used to resolve `ref` when relative
|
|
212
|
+
* @param chain - ancestor profile paths tracked for cycle detection
|
|
213
|
+
* @returns Resolved profile definition with inherited bases applied.
|
|
214
|
+
* @throws {ConfigLoadError} - if a profile file is missing or invalid, or inheritance revisits a path in the chain.
|
|
215
|
+
*/
|
|
138
216
|
function resolveProfileFile(ref: string, projectRoot: string, chain: string[]): ProfileDefinition {
|
|
139
217
|
const path = absolutize(projectRoot, ref);
|
|
140
218
|
assertNoProfileCycle(path, chain);
|
|
219
|
+
// A missing user-selected file cannot safely fall back to a different profile.
|
|
141
220
|
if (!existsSync(path)) {
|
|
142
221
|
throw new ConfigLoadError(
|
|
143
222
|
`Profile extends file not found: ${path}.`,
|
|
@@ -147,17 +226,31 @@ function resolveProfileFile(ref: string, projectRoot: string, chain: string[]):
|
|
|
147
226
|
return resolveInlineProfile(inlineSpecFromObject(parseConfigFile(path)), dirname(path), [...chain, path]);
|
|
148
227
|
}
|
|
149
228
|
|
|
150
|
-
|
|
151
|
-
|
|
229
|
+
/**
|
|
230
|
+
* Resolves an inline profile by applying its overrides onto the resolved base profile.
|
|
231
|
+
* Omitted `extends` selects the recommended profile; invalid base profiles or child rules stop loading with `ConfigLoadError`.
|
|
232
|
+
*
|
|
233
|
+
* @param spec - inline profile overrides and optional `extends` base reference
|
|
234
|
+
* @param projectRoot - directory containing the profile file for resolving relative bases
|
|
235
|
+
* @param chain - ancestor profile paths used to detect inheritance cycles
|
|
236
|
+
* @returns Profile definition combining the resolved base and inline overrides.
|
|
237
|
+
*/
|
|
152
238
|
function resolveInlineProfile(spec: InlineProfileSpec, projectRoot: string, chain: string[]): ProfileDefinition {
|
|
153
239
|
const base = resolveProfileRef(spec.extends ?? DEFAULT_PROFILE_NAME, projectRoot, chain);
|
|
154
240
|
return overlayProfile(base, spec);
|
|
155
241
|
}
|
|
156
242
|
|
|
157
|
-
|
|
158
|
-
|
|
243
|
+
/**
|
|
244
|
+
* Builds a new profile with inline settings taking precedence over the resolved base field by field.
|
|
245
|
+
* A supplied ignore list replaces the base list while omission inherits it; throws `ConfigLoadError` for unknown child rule IDs.
|
|
246
|
+
*
|
|
247
|
+
* @param base - resolved base profile definition supplying inherited rules and ignore paths
|
|
248
|
+
* @param spec - inline profile overrides to apply on top of `base`
|
|
249
|
+
* @returns New profile definition with child overrides applied over `base`.
|
|
250
|
+
*/
|
|
159
251
|
function overlayProfile(base: ProfileDefinition, spec: InlineProfileSpec): ProfileDefinition {
|
|
160
252
|
const rules = new Map(base.rules);
|
|
253
|
+
// Each child rule may override only the fields the user supplied while retaining inherited fields.
|
|
161
254
|
for (const [ruleId, setting] of Object.entries(spec.rules ?? {})) {
|
|
162
255
|
assertKnownProfileRule(ruleId);
|
|
163
256
|
rules.set(ruleId, mergeRuleSetting(rules.get(ruleId), setting));
|
|
@@ -166,22 +259,40 @@ function overlayProfile(base: ProfileDefinition, spec: InlineProfileSpec): Profi
|
|
|
166
259
|
return { name: base.name, rules, ignoredPaths };
|
|
167
260
|
}
|
|
168
261
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
262
|
+
/**
|
|
263
|
+
* Merges one inherited rule setting with the user's child fields.
|
|
264
|
+
* Explicit false and zero values win, omitted fields continue to inherit, and no parent yields only child fields.
|
|
265
|
+
*
|
|
266
|
+
* @param parent - inherited rule setting from the base profile, when present
|
|
267
|
+
* @param child - child rule setting whose defined fields override `parent`
|
|
268
|
+
* @returns Combined rule setting with child fields overriding any inherited fields.
|
|
269
|
+
*/
|
|
173
270
|
function mergeRuleSetting(parent: ProfileRuleSetting | undefined, child: ProfileRuleSetting): ProfileRuleSetting {
|
|
174
271
|
return { ...parent, ...child };
|
|
175
272
|
}
|
|
176
273
|
|
|
177
|
-
|
|
274
|
+
/**
|
|
275
|
+
* Copies a resolved profile with its own rule map and ignore list while inner rule settings remain shared.
|
|
276
|
+
* Use this for bundled profiles whose shared definitions must remain stable across commands.
|
|
277
|
+
*
|
|
278
|
+
* @param definition - profile definition whose collections are shallow-cloned
|
|
279
|
+
* @returns Cloned profile definition with independent `rules` map and `ignoredPaths` array.
|
|
280
|
+
*/
|
|
178
281
|
function cloneProfileDefinition(definition: ProfileDefinition): ProfileDefinition {
|
|
179
282
|
return { name: definition.name, rules: new Map(definition.rules), ignoredPaths: [...definition.ignoredPaths] };
|
|
180
283
|
}
|
|
181
284
|
|
|
182
|
-
|
|
183
|
-
|
|
285
|
+
/**
|
|
286
|
+
* Checks the profile path against the active resolution chain to prevent recursive loading from looping.
|
|
287
|
+
* Throws with the visit order so users can find and break the `extends` cycle.
|
|
288
|
+
*
|
|
289
|
+
* @param key - resolved profile path about to be loaded
|
|
290
|
+
* @param chain - ordered ancestor profile paths currently being resolved
|
|
291
|
+
* @returns Nothing. Completes when `key` is not already present in `chain`.
|
|
292
|
+
* @throws {ConfigLoadError} - when the key is already in the chain of profile paths being resolved.
|
|
293
|
+
*/
|
|
184
294
|
function assertNoProfileCycle(key: string, chain: string[]): void {
|
|
295
|
+
// A repeated path means the user's profile chain has returned to a file already being resolved.
|
|
185
296
|
if (chain.includes(key)) {
|
|
186
297
|
throw new ConfigLoadError(
|
|
187
298
|
`Profile inheritance cycle detected: ${[...chain, key].join(" -> ")}.`,
|
|
@@ -190,9 +301,16 @@ function assertNoProfileCycle(key: string, chain: string[]): void {
|
|
|
190
301
|
}
|
|
191
302
|
}
|
|
192
303
|
|
|
193
|
-
|
|
194
|
-
|
|
304
|
+
/**
|
|
305
|
+
* Checks a profile's rule identifier against the catalogue before it can affect analysis.
|
|
306
|
+
* Throws for unknown names so users do not mistake a typo for applied policy.
|
|
307
|
+
*
|
|
308
|
+
* @param ruleId - rule identifier configured in a profile's `rules` block
|
|
309
|
+
* @returns Nothing. Completes when `ruleId` exists in the rule catalogue.
|
|
310
|
+
* @throws {ConfigLoadError} - when the rule id is not in the gruff-ts rule catalogue.
|
|
311
|
+
*/
|
|
195
312
|
function assertKnownProfileRule(ruleId: string): void {
|
|
313
|
+
// A name outside the rule catalogue cannot produce the behavior the user requested.
|
|
196
314
|
if (!isKnownRuleId(ruleId)) {
|
|
197
315
|
throw new ConfigLoadError(
|
|
198
316
|
`Unknown rule id in profile: ${JSON.stringify(ruleId)}.`,
|
|
@@ -201,16 +319,21 @@ function assertKnownProfileRule(ruleId: string): void {
|
|
|
201
319
|
}
|
|
202
320
|
}
|
|
203
321
|
|
|
204
|
-
|
|
205
|
-
*
|
|
206
|
-
*
|
|
207
|
-
*
|
|
322
|
+
/**
|
|
323
|
+
* Converts the user's parsed profile value into a named/file reference or inline profile.
|
|
324
|
+
* An empty mapping leaves base selection to the profile resolver.
|
|
325
|
+
*
|
|
326
|
+
* @param configuredProfile - raw `profile` setting from CLI options or parsed config
|
|
327
|
+
* @returns Profile reference string or validated inline profile specification.
|
|
328
|
+
* @throws {ConfigLoadError} - for a value outside string or mapping, a non-string extends, or a rule mapping that fails field validation.
|
|
208
329
|
*/
|
|
209
|
-
function parseProfileSpec(
|
|
210
|
-
|
|
211
|
-
|
|
330
|
+
function parseProfileSpec(configuredProfile: unknown): ProfileSpec {
|
|
331
|
+
// A string preserves the exact built-in name or local path the user selected.
|
|
332
|
+
if (typeof configuredProfile === "string") {
|
|
333
|
+
return configuredProfile;
|
|
212
334
|
}
|
|
213
|
-
const block = objectValue(
|
|
335
|
+
const block = objectValue(configuredProfile);
|
|
336
|
+
// A non-string value with another shape cannot identify a profile, so config loading stops.
|
|
214
337
|
if (!block) {
|
|
215
338
|
throw new ConfigLoadError(
|
|
216
339
|
"`profile:` must be a built-in name, a profile file path, or a mapping with `extends:` and overrides.",
|
|
@@ -220,178 +343,401 @@ function parseProfileSpec(rawSpec: unknown): ProfileSpec {
|
|
|
220
343
|
return inlineSpecFromObject(block);
|
|
221
344
|
}
|
|
222
345
|
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
346
|
+
/**
|
|
347
|
+
* Extracts overrides from a parsed inline or file-backed profile mapping.
|
|
348
|
+
* Without an `extends` field, resolution uses the recommended profile; extra top-level fields have no effect.
|
|
349
|
+
*
|
|
350
|
+
* @param block - parsed key-value mapping representing an inline or file-backed profile
|
|
351
|
+
* @returns Validated inline profile specification with optional `extends`, `rules`, and `ignoredPaths`.
|
|
352
|
+
* @throws {ConfigLoadError} - when extends is supplied with a non-string value or a rule mapping fails field validation.
|
|
353
|
+
*/
|
|
226
354
|
function inlineSpecFromObject(block: Record<string, unknown>): InlineProfileSpec {
|
|
227
355
|
const spec: InlineProfileSpec = {};
|
|
356
|
+
// A supplied base must name a built-in profile or local profile file.
|
|
228
357
|
if ("extends" in block) {
|
|
358
|
+
// Non-string bases cannot resolve to the profile the user intended.
|
|
229
359
|
if (!isString(block.extends)) {
|
|
230
360
|
throw new ConfigLoadError("`profile.extends` must be a string: a built-in name or a relative profile file path.", SUGGEST_EDIT_CONFIG);
|
|
231
361
|
}
|
|
232
362
|
spec.extends = block.extends;
|
|
233
363
|
}
|
|
234
364
|
const rulesBlock = objectValue(block.rules);
|
|
365
|
+
// Without a rules mapping, the profile adds no rule overrides.
|
|
235
366
|
if (rulesBlock) {
|
|
236
367
|
spec.rules = profileRulesFromBlock(rulesBlock);
|
|
237
368
|
}
|
|
369
|
+
// An ignoredPaths key replaces inherited ignores. A non-list value or a list without strings clears them.
|
|
238
370
|
if ("ignoredPaths" in block) {
|
|
239
371
|
spec.ignoredPaths = arrayValue(block.ignoredPaths).filter(isString);
|
|
240
372
|
}
|
|
241
373
|
return spec;
|
|
242
374
|
}
|
|
243
375
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
376
|
+
/**
|
|
377
|
+
* Extracts rule settings from the parsed profile `rules` mapping and rejects non-mapping values so typos never become silent no-ops.
|
|
378
|
+
* Shares field validation with direct config and propagates `ConfigLoadError` for invalid fields; rule IDs are checked during overlay.
|
|
379
|
+
*
|
|
380
|
+
* @param rulesBlock - parsed `rules` mapping from a profile definition
|
|
381
|
+
* @returns Record mapping rule identifiers to validated profile rule settings.
|
|
382
|
+
* @throws {ConfigLoadError} when a rule entry is not a mapping or fails field validation.
|
|
383
|
+
*/
|
|
247
384
|
function profileRulesFromBlock(rulesBlock: Record<string, unknown>): Record<string, ProfileRuleSetting> {
|
|
248
385
|
const rules: Record<string, ProfileRuleSetting> = {};
|
|
249
386
|
for (const [ruleId, value] of Object.entries(rulesBlock)) {
|
|
250
387
|
const rule = objectValue(value);
|
|
251
|
-
|
|
252
|
-
|
|
388
|
+
// Reject scalar or array rule entries such as `size.function-length: true` instead of silently ignoring the user's policy.
|
|
389
|
+
if (!rule) {
|
|
390
|
+
throw new ConfigLoadError(
|
|
391
|
+
`Invalid config for rule ${JSON.stringify(ruleId)}: expected a mapping with enabled, threshold, severity, or options.`,
|
|
392
|
+
SUGGEST_EDIT_CONFIG,
|
|
393
|
+
);
|
|
253
394
|
}
|
|
395
|
+
rules[ruleId] = ruleConfigValue(ruleId, rule);
|
|
254
396
|
}
|
|
255
397
|
return rules;
|
|
256
398
|
}
|
|
257
399
|
|
|
258
|
-
|
|
259
|
-
|
|
400
|
+
/**
|
|
401
|
+
* Selects the explicit `--config` path or the first supported project-root config file.
|
|
402
|
+
* An explicit path resolves relative to the launch directory as scan targets are; no match selects zero-config behavior without error.
|
|
403
|
+
*
|
|
404
|
+
* @param projectRoot - workspace root searched when no explicit `--config` path is supplied
|
|
405
|
+
* @param options - CLI analysis options that may specify an explicit `config` path
|
|
406
|
+
* @returns Resolved path to the selected configuration file, or `undefined` when none applies.
|
|
407
|
+
*/
|
|
260
408
|
function selectedConfigPath(projectRoot: string, options: AnalysisOptions): string | undefined {
|
|
261
|
-
return options.config ? absolutize(
|
|
409
|
+
return options.config ? absolutize(process.cwd(), options.config) : defaultConfigPath(projectRoot);
|
|
262
410
|
}
|
|
263
411
|
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
412
|
+
/**
|
|
413
|
+
* Updates the effective config from the parsed file before applying profiles and CLI overrides.
|
|
414
|
+
* Checks the schema and supported keys first, then validates each section; a `ConfigLoadError` stops loading on a rejected setting.
|
|
415
|
+
*
|
|
416
|
+
* @param config - effective configuration mutated in place with validated settings from the file
|
|
417
|
+
* @param parsedConfig - raw parsed configuration mapping to validate and apply
|
|
418
|
+
* @returns Nothing. Updates `config` in place across schema, keys, budget, severity, paths, allowlists, rules, and exclusions.
|
|
419
|
+
*/
|
|
420
|
+
function applyConfigValues(config: Config, parsedConfig: Record<string, unknown>): void {
|
|
421
|
+
applySchemaVersionConfig(parsedConfig);
|
|
422
|
+
assertKnownKeys(parsedConfig, KNOWN_ROOT_KEYS, "");
|
|
423
|
+
assertKnownKeys(objectValue(parsedConfig.paths), KNOWN_PATHS_KEYS, "paths.");
|
|
424
|
+
assertKnownKeys(objectValue(parsedConfig.allowlists), KNOWN_ALLOWLISTS_KEYS, "allowlists.", REFUSED_ALLOWLISTS_KEYS);
|
|
425
|
+
applyDeepScanBudgetConfig(config, parsedConfig);
|
|
426
|
+
applyDisplayFloorConfig(config, parsedConfig);
|
|
427
|
+
applyFailOnConfig(config, parsedConfig);
|
|
428
|
+
applyPathConfig(config, parsedConfig);
|
|
429
|
+
applyAllowlistConfig(config, parsedConfig);
|
|
430
|
+
applyRuleConfig(config, parsedConfig);
|
|
431
|
+
config.sensitiveExclusions = parseSensitiveExclusions(parsedConfig);
|
|
275
432
|
}
|
|
276
433
|
|
|
277
|
-
|
|
278
|
-
* Validates
|
|
279
|
-
*
|
|
280
|
-
*
|
|
281
|
-
*
|
|
282
|
-
*
|
|
283
|
-
*
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
434
|
+
/**
|
|
435
|
+
* Validates config key names before analysis because an ignored typo would leave a setting out of force.
|
|
436
|
+
* The error names the first rejected key and gives a stable, sorted list of accepted keys, excluding separately refused legacy keys.
|
|
437
|
+
*
|
|
438
|
+
* @param block - config mapping to validate. An omitted block is allowed.
|
|
439
|
+
* @param known - permitted unprefixed key names for the block
|
|
440
|
+
* @param prefix - config path prefix shown before key names in the diagnostic
|
|
441
|
+
* @param separatelyRefused - optional legacy keys deferred to a dedicated migration error; an empty set rejects every unknown key here
|
|
442
|
+
* @returns nothing. Validation continues for an omitted block or one whose keys are all recognised.
|
|
443
|
+
* @throws {ConfigLoadError} - the block contains a key outside the known set
|
|
444
|
+
*/
|
|
445
|
+
function assertKnownKeys(
|
|
446
|
+
block: Record<string, unknown> | undefined,
|
|
447
|
+
known: ReadonlySet<string>,
|
|
448
|
+
prefix: string,
|
|
449
|
+
separatelyRefused: ReadonlySet<string> = new Set(),
|
|
450
|
+
): void {
|
|
451
|
+
// A missing or non-mapping section supplies no keys here, so the caller can continue its other config checks.
|
|
452
|
+
if (!block) {
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
const unknownKey = Object.keys(block).find((key) => !known.has(key) && !separatelyRefused.has(key));
|
|
456
|
+
if (unknownKey === undefined) {
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
const rejected = JSON.stringify(prefix + unknownKey);
|
|
460
|
+
const accepted = [...known].sort().map((key) => prefix + key).join(", ");
|
|
461
|
+
throw new ConfigLoadError(`Unknown config key ${rejected}. Valid keys: ${accepted}.`, SUGGEST_EDIT_CONFIG);
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* Applies the user's configured line and byte limits before analysis so the report can explain any truncated checks.
|
|
466
|
+
* Omitted settings inherit the current budget; null values are invalid.
|
|
467
|
+
*
|
|
468
|
+
* @param config - effective configuration whose `deepScanBudget` is updated in place
|
|
469
|
+
* @param parsedConfig - parsed config mapping that may contain a `deepScanBudget` block
|
|
470
|
+
* @returns Nothing. Updates `config.deepScanBudget` in place when `deepScanBudget` is configured.
|
|
471
|
+
* @throws {ConfigLoadError} for an invalid budget mapping, unknown key, or invalid enabled flag or limit.
|
|
472
|
+
*/
|
|
473
|
+
function applyDeepScanBudgetConfig(config: Config, parsedConfig: Record<string, unknown>): void {
|
|
474
|
+
const rawBudget = parsedConfig.deepScanBudget;
|
|
475
|
+
// A project with no budget block keeps the current limits.
|
|
476
|
+
if (rawBudget === undefined) {
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
const budget = objectValue(rawBudget);
|
|
480
|
+
// An explicit null does not select a budget. Users who want unlimited analysis can set enabled to false.
|
|
481
|
+
if (!budget) {
|
|
482
|
+
throw new ConfigLoadError('Config key "deepScanBudget" must be a mapping.', SUGGEST_EDIT_CONFIG);
|
|
483
|
+
}
|
|
484
|
+
const allowedKeys = new Set(["enabled", "maxLines", "maxBytes"]);
|
|
485
|
+
const unknownKey = Object.keys(budget).find((key) => !allowedKeys.has(key));
|
|
486
|
+
// A typo such as maxLine could make a user think a limit is in effect when it was ignored.
|
|
487
|
+
if (unknownKey) {
|
|
488
|
+
throw new ConfigLoadError(`Unknown deepScanBudget key: ${JSON.stringify(unknownKey)}. Valid keys: enabled, maxLines, maxBytes.`, SUGGEST_EDIT_CONFIG);
|
|
489
|
+
}
|
|
490
|
+
// A user can change just the line or byte limit and keep the inherited enabled setting.
|
|
491
|
+
const enabled = budget.enabled === undefined ? config.deepScanBudget.enabled : budget.enabled;
|
|
492
|
+
// An explicit null or string gives the user an error with the accepted settings.
|
|
493
|
+
if (typeof enabled !== "boolean") {
|
|
494
|
+
throw new ConfigLoadError('Config key "deepScanBudget.enabled" must be true or false.', SUGGEST_EDIT_CONFIG);
|
|
495
|
+
}
|
|
496
|
+
const maxLines = positiveBudgetLimit(budget.maxLines, "maxLines", config.deepScanBudget.maxLines);
|
|
497
|
+
const maxBytes = positiveBudgetLimit(budget.maxBytes, "maxBytes", config.deepScanBudget.maxBytes);
|
|
498
|
+
config.deepScanBudget = { enabled, maxLines, maxBytes, override: "config" };
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* Validates a configured scan bound as a safe positive integer, or returns the caller's fallback when omitted.
|
|
503
|
+
*
|
|
504
|
+
* @param configuredLimit - raw limit value supplied under `deepScanBudget`
|
|
505
|
+
* @param key - limit key name (`maxLines` or `maxBytes`) reported in the config error
|
|
506
|
+
* @param fallback - inherited bound returned when `configuredLimit` is undefined
|
|
507
|
+
* @returns Validated positive integer limit, or `fallback` when omitted.
|
|
508
|
+
* @throws {ConfigLoadError} - when the limit is set but is not a number, not a safe integer, or not greater than zero.
|
|
509
|
+
*/
|
|
510
|
+
function positiveBudgetLimit(configuredLimit: unknown, key: "maxLines" | "maxBytes", fallback: number): number {
|
|
511
|
+
if (configuredLimit === undefined) {
|
|
512
|
+
return fallback;
|
|
513
|
+
}
|
|
514
|
+
if (typeof configuredLimit !== "number" || !Number.isSafeInteger(configuredLimit) || configuredLimit <= 0) {
|
|
515
|
+
throw new ConfigLoadError(`Config key "deepScanBudget.${key}" must be a positive integer.`, SUGGEST_EDIT_CONFIG);
|
|
516
|
+
}
|
|
517
|
+
return configuredLimit;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* Applies a CLI budget choice to the effective config; an absent choice leaves the existing budget in effect.
|
|
522
|
+
* Enabling sets both limits from the CLI, disabling retains the existing limits, and either choice records the CLI as source.
|
|
523
|
+
*
|
|
524
|
+
* @param config - effective configuration whose `deepScanBudget` is updated in place
|
|
525
|
+
* @param override - CLI budget override when supplied, or `undefined` to preserve existing settings
|
|
526
|
+
* @returns Nothing. Mutates `config.deepScanBudget` when `override` is present.
|
|
527
|
+
*/
|
|
528
|
+
function applyDeepScanBudgetOverride(config: Config, override: DeepScanBudgetOverride | undefined): void {
|
|
529
|
+
if (!override) {
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
config.deepScanBudget = override.enabled
|
|
533
|
+
? { enabled: true, maxLines: override.maxLines, maxBytes: override.maxBytes, override: "cli" }
|
|
534
|
+
: { ...config.deepScanBudget, enabled: false, override: "cli" };
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* Checks the parsed configuration's required schema version before any user setting affects the scan.
|
|
539
|
+
* Throws with migration guidance for missing or unsupported versions; the supported value already matches the default config.
|
|
540
|
+
*
|
|
541
|
+
* @param parsedConfig - raw parsed configuration mapping expected to carry `schemaVersion`
|
|
542
|
+
* @returns Nothing. Completes when `schemaVersion` equals `"gruff-ts.config.v0.1"`.
|
|
543
|
+
* @throws {ConfigLoadError} - when schemaVersion is missing or is any value other than "gruff-ts.config.v0.1".
|
|
544
|
+
*/
|
|
545
|
+
function applySchemaVersionConfig(parsedConfig: Record<string, unknown>): void {
|
|
546
|
+
const schemaVersion = parsedConfig.schemaVersion;
|
|
547
|
+
// A missing version leaves Gruff unable to know which configuration contract the user intended.
|
|
287
548
|
if (schemaVersion === undefined) {
|
|
288
549
|
throw new ConfigLoadError('Config must include `schemaVersion: gruff-ts.config.v0.1` at the top.', SUGGEST_INIT_FORCE);
|
|
289
550
|
}
|
|
551
|
+
// Any other version is unsupported and must not be interpreted as the current schema.
|
|
290
552
|
if (schemaVersion !== "gruff-ts.config.v0.1") {
|
|
291
553
|
throw new ConfigLoadError(`Unsupported schemaVersion: ${JSON.stringify(schemaVersion)}. Supported: "gruff-ts.config.v0.1".`, SUGGEST_INIT_FORCE);
|
|
292
554
|
}
|
|
293
555
|
}
|
|
294
556
|
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
557
|
+
/**
|
|
558
|
+
* Sets the report's display floor. Existing per-command gates must move to failOn to keep their build behavior.
|
|
559
|
+
*
|
|
560
|
+
* @param config - effective config whose display floor is updated
|
|
561
|
+
* @param parsedConfig - file settings that may supply a minimumSeverity value
|
|
562
|
+
* @returns - nothing. Updates the effective config in place when a valid floor is supplied.
|
|
563
|
+
* @throws {ConfigLoadError} - when minimumSeverity is a mapping or a supplied value other than advisory, warning, or error
|
|
564
|
+
*/
|
|
565
|
+
function applyDisplayFloorConfig(config: Config, parsedConfig: Record<string, unknown>): void {
|
|
566
|
+
const configuredFloor = parsedConfig.minimumSeverity;
|
|
567
|
+
// An omitted key leaves the current display floor in effect.
|
|
568
|
+
if (configuredFloor === undefined) {
|
|
302
569
|
return;
|
|
303
570
|
}
|
|
571
|
+
if (objectValue(configuredFloor)) {
|
|
572
|
+
throw new ConfigLoadError(LEGACY_MINIMUM_SEVERITY_ERROR, "Rename the `minimumSeverity:` mapping to `failOn:`, and set `minimumSeverity:` to one severity if you also want a display floor.");
|
|
573
|
+
}
|
|
574
|
+
if (configuredFloor !== "advisory" && configuredFloor !== "warning" && configuredFloor !== "error") {
|
|
575
|
+
throw new ConfigLoadError(`Config key "minimumSeverity" must be one of: advisory, warning, error. Got: ${JSON.stringify(configuredFloor)}.`, SUGGEST_EDIT_CONFIG);
|
|
576
|
+
}
|
|
577
|
+
config.displayFloor = configuredFloor;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/**
|
|
581
|
+
* Loads a project's per-command exit gates so a developer and CI get the same result without repeating `--fail-on`.
|
|
582
|
+
*
|
|
583
|
+
* @param config - effective configuration whose `minimumSeverity` map receives validated command gates
|
|
584
|
+
* @param parsedConfig - parsed configuration mapping that may supply a `failOn` section
|
|
585
|
+
* @returns Nothing. Populates `config.minimumSeverity` in place for each configured command gate.
|
|
586
|
+
* @throws {ConfigLoadError} for a non-mapping, an unknown command, or an invalid threshold.
|
|
587
|
+
*/
|
|
588
|
+
function applyFailOnConfig(config: Config, parsedConfig: Record<string, unknown>): void {
|
|
589
|
+
// Omitting failOn keeps the current command thresholds.
|
|
590
|
+
if (parsedConfig.failOn === undefined) {
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
const block = objectValue(parsedConfig.failOn);
|
|
594
|
+
// A bare `failOn: warning` gives no command to gate. Ask the user to name one, such as analyse.
|
|
595
|
+
if (!block) {
|
|
596
|
+
throw new ConfigLoadError('Config key "failOn" must be a mapping of commands to thresholds.', SUGGEST_EDIT_CONFIG);
|
|
597
|
+
}
|
|
598
|
+
// Apply each gate so a project can fail analyse at warning while allowing summary to exit successfully.
|
|
304
599
|
for (const [commandName, value] of Object.entries(block)) {
|
|
305
|
-
config.minimumSeverity.set(
|
|
600
|
+
config.minimumSeverity.set(assertGatedCommand(commandName), parseFailThresholdConfig(value));
|
|
306
601
|
}
|
|
307
602
|
}
|
|
308
603
|
|
|
309
|
-
|
|
310
|
-
*
|
|
311
|
-
* dashboard
|
|
312
|
-
*
|
|
313
|
-
*
|
|
604
|
+
/**
|
|
605
|
+
* Checks a `failOn` command name to confirm it supports a configured exit threshold.
|
|
606
|
+
* Throws for `dashboard` and unknown names because they cannot provide the gate the configuration implies.
|
|
607
|
+
*
|
|
608
|
+
* @param commandName - command key read from the `failOn` configuration block
|
|
609
|
+
* @returns Unchanged `commandName` narrowed to the supported gated commands.
|
|
610
|
+
* @throws {ConfigLoadError} - when commandName is dashboard or any name other than analyse, summary, or report.
|
|
314
611
|
*/
|
|
315
|
-
function
|
|
612
|
+
function assertGatedCommand(commandName: string): MinimumSeverityCommand {
|
|
613
|
+
// Dashboard has no --fail-on behavior, so accepting it would promise users a gate that cannot run.
|
|
316
614
|
if (commandName === "dashboard") {
|
|
317
|
-
throw new ConfigLoadError('Unknown command in
|
|
615
|
+
throw new ConfigLoadError('Unknown command in failOn: "dashboard". The dashboard subcommand does not currently expose a --fail-on flag; configuring its threshold is not supported.', "Remove the `dashboard:` line from `failOn:` in `.gruff-ts.yaml`, or open an issue if dashboard should gate.");
|
|
318
616
|
}
|
|
617
|
+
// These are the only commands whose user-facing exit status supports a configured minimum severity.
|
|
319
618
|
if (commandName === "analyse" || commandName === "summary" || commandName === "report") {
|
|
320
619
|
return commandName;
|
|
321
620
|
}
|
|
322
|
-
throw new ConfigLoadError(`Unknown command in
|
|
621
|
+
throw new ConfigLoadError(`Unknown command in failOn: ${JSON.stringify(commandName)}. Valid keys: analyse, summary, report.`, SUGGEST_EDIT_CONFIG);
|
|
323
622
|
}
|
|
324
623
|
|
|
325
|
-
|
|
326
|
-
* Validates
|
|
327
|
-
*
|
|
328
|
-
*
|
|
329
|
-
*
|
|
624
|
+
/**
|
|
625
|
+
* Validates a configured exit threshold against the CLI's accepted values.
|
|
626
|
+
* Unsupported values fail with the accepted choices instead of silently changing the user's CI gate.
|
|
627
|
+
*
|
|
628
|
+
* @param configuredThreshold - raw threshold value configured for a gated command
|
|
629
|
+
* @returns Validated fail threshold (`none`, `advisory`, `warning`, or `error`).
|
|
630
|
+
* @throws {ConfigLoadError} - when the configured threshold is not none, advisory, warning, or error.
|
|
330
631
|
*/
|
|
331
|
-
function parseFailThresholdConfig(
|
|
332
|
-
|
|
333
|
-
|
|
632
|
+
function parseFailThresholdConfig(configuredThreshold: unknown): FailThreshold {
|
|
633
|
+
// CLI resolution receives none as an explicit gate choice, distinct from an omitted threshold.
|
|
634
|
+
if (configuredThreshold === "none" || configuredThreshold === "advisory" || configuredThreshold === "warning" || configuredThreshold === "error") {
|
|
635
|
+
return configuredThreshold;
|
|
334
636
|
}
|
|
335
|
-
throw new ConfigLoadError(`FailThreshold must be one of: advisory, warning, error, none. Got: ${JSON.stringify(
|
|
637
|
+
throw new ConfigLoadError(`FailThreshold must be one of: advisory, warning, error, none. Got: ${JSON.stringify(configuredThreshold)}.`, SUGGEST_EDIT_CONFIG);
|
|
336
638
|
}
|
|
337
639
|
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
640
|
+
/**
|
|
641
|
+
* Looks up the configured threshold for one command during CLI option resolution.
|
|
642
|
+
* Missing values mean the user did not override that command, so callers continue to the binary default.
|
|
643
|
+
*
|
|
644
|
+
* @param config - effective configuration holding per-command exit thresholds
|
|
645
|
+
* @param command - gated subcommand whose configured threshold is requested
|
|
646
|
+
* @returns Configured threshold for `command`, or `undefined` when unconfigured.
|
|
647
|
+
*/
|
|
341
648
|
function minimumSeverityFor(config: Config, command: MinimumSeverityCommand): FailThreshold | undefined {
|
|
342
649
|
return config.minimumSeverity.get(command);
|
|
343
650
|
}
|
|
344
651
|
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
652
|
+
/**
|
|
653
|
+
* Replaces the effective config's path exclusions with strings from the parsed `paths.ignore` list.
|
|
654
|
+
* A missing list, a non-list value, or a list with no strings clears these config-based exclusions.
|
|
655
|
+
*
|
|
656
|
+
* @param config - effective configuration whose `ignoredPaths` list is replaced in place
|
|
657
|
+
* @param parsedConfig - parsed configuration mapping that may contain `paths.ignore`
|
|
658
|
+
* @returns Nothing. Updates `config.ignoredPaths` in place.
|
|
659
|
+
*/
|
|
660
|
+
function applyPathConfig(config: Config, parsedConfig: Record<string, unknown>): void {
|
|
661
|
+
const paths = objectValue(parsedConfig.paths);
|
|
349
662
|
config.ignoredPaths = arrayValue(paths?.ignore).filter(isString);
|
|
350
663
|
}
|
|
351
664
|
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
665
|
+
/**
|
|
666
|
+
* Updates the effective config from parsed allowlists, lowercasing supplied naming values for matching.
|
|
667
|
+
* A present naming or tracking key replaces its setting (non-lists or stringless lists clear it); omitted keys keep theirs.
|
|
668
|
+
*
|
|
669
|
+
* @param config - effective configuration whose allowlist sets and tracking tokens are updated in place
|
|
670
|
+
* @param parsedConfig - parsed configuration mapping that may contain an `allowlists` section
|
|
671
|
+
* @returns Nothing. Mutates `config` allowlist sets and compiled `trackingTokens` in place.
|
|
672
|
+
* @throws {ConfigLoadError} - when allowlists.secretPreviews is present or a tracking token string is an invalid regular expression.
|
|
673
|
+
*/
|
|
674
|
+
function applyAllowlistConfig(config: Config, parsedConfig: Record<string, unknown>): void {
|
|
675
|
+
const allowlists = objectValue(parsedConfig.allowlists);
|
|
357
676
|
const abbreviations = arrayValue(allowlists?.acceptedAbbreviations).filter(isString);
|
|
677
|
+
// A supplied abbreviation list replaces the defaults, including when the user intentionally supplies an empty list.
|
|
358
678
|
if (allowlists && "acceptedAbbreviations" in allowlists) {
|
|
359
679
|
config.acceptedAbbreviations = new Set(abbreviations.map((value) => value.toLowerCase()));
|
|
360
680
|
}
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
681
|
+
// Even an empty legacy list stops loading because category redaction markers are unconditional.
|
|
682
|
+
if (allowlists && "secretPreviews" in allowlists) {
|
|
683
|
+
throw new ConfigLoadError(LEGACY_SECRET_PREVIEWS_ERROR, "Delete the `allowlists.secretPreviews:` entry from `.gruff-ts.yaml`; nothing replaces it.");
|
|
684
|
+
}
|
|
364
685
|
applyNamingAllowlist(config, allowlists, "acceptedClassFilePairs");
|
|
365
|
-
applyNamingAllowlist(config, allowlists, "acceptedCasingPairs");
|
|
366
|
-
applyNamingAllowlist(config, allowlists, "booleanPrefixes");
|
|
367
|
-
applyNamingAllowlist(config, allowlists, "hungarianPrefixes");
|
|
368
686
|
applyNamingAllowlist(config, allowlists, "placeholderNames");
|
|
369
|
-
|
|
370
|
-
|
|
687
|
+
// Tracking tokens are project vocabulary, so none ship by default. Each supplied string becomes a case-insensitive pattern.
|
|
688
|
+
if (allowlists && "trackingTokens" in allowlists) {
|
|
689
|
+
config.trackingTokens = arrayValue(allowlists.trackingTokens).filter(isString).map((pattern) => trackingTokenPattern(pattern));
|
|
690
|
+
}
|
|
371
691
|
}
|
|
372
692
|
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
693
|
+
/**
|
|
694
|
+
* Compiles a case-insensitive regular expression for a pattern from `allowlists.trackingTokens`.
|
|
695
|
+
*
|
|
696
|
+
* @param pattern - regular expression source text supplied in configuration
|
|
697
|
+
* @returns Case-insensitive regular expression built from `pattern`.
|
|
698
|
+
* @throws {ConfigLoadError} - Invalid syntax stops config loading and identifies the entry to fix or remove.
|
|
699
|
+
*/
|
|
700
|
+
function trackingTokenPattern(pattern: string): RegExp {
|
|
701
|
+
try {
|
|
702
|
+
return new RegExp(pattern, "i");
|
|
703
|
+
} catch {
|
|
704
|
+
throw new ConfigLoadError(`Config key "allowlists.trackingTokens" holds an invalid regular expression: ${JSON.stringify(pattern)}.`, "Fix or remove that entry in `.gruff-ts.yaml`.");
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* Replaces the effective config's naming set for the selected key with lowercase strings from the parsed allowlists.
|
|
710
|
+
* A supplied value with no usable strings clears the selected set; missing sections or keys leave it untouched.
|
|
711
|
+
*
|
|
712
|
+
* @param config - effective configuration whose selected naming set is updated in place
|
|
713
|
+
* @param allowlists - parsed `allowlists` mapping, or `undefined` when omitted
|
|
714
|
+
* @param key - target naming allowlist field (`acceptedClassFilePairs` or `placeholderNames`)
|
|
715
|
+
* @returns Nothing. Replaces `config[key]` when `allowlists` explicitly contains `key`.
|
|
716
|
+
*/
|
|
717
|
+
function applyNamingAllowlist(config: Config, allowlists: Record<string, unknown> | undefined, key: "acceptedClassFilePairs" | "placeholderNames"): void {
|
|
718
|
+
// If the section or selected key is missing, the current set stays in effect.
|
|
376
719
|
if (!allowlists || !(key in allowlists)) {
|
|
377
720
|
return;
|
|
378
721
|
}
|
|
379
722
|
config[key] = new Set(arrayValue(allowlists[key]).filter(isString).map((value) => value.toLowerCase()));
|
|
380
723
|
}
|
|
381
724
|
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
725
|
+
/**
|
|
726
|
+
* Applies per-rule overrides from the parsed `rules` mapping to the effective config.
|
|
727
|
+
* Rejects unknown rule IDs and non-mapping rule entries loudly so malformed settings never become silent no-ops.
|
|
728
|
+
*
|
|
729
|
+
* @param config - effective configuration whose `rules` map receives validated per-rule overrides
|
|
730
|
+
* @param parsedConfig - parsed configuration mapping that may supply a `rules` section
|
|
731
|
+
* @returns Nothing. Populates `config.rules` in place for each valid rule mapping.
|
|
732
|
+
* @throws {ConfigLoadError} when a rule entry is not a mapping, names an unknown rule, has an unknown key, or fails field validation.
|
|
733
|
+
*/
|
|
734
|
+
function applyRuleConfig(config: Config, parsedConfig: Record<string, unknown>): void {
|
|
735
|
+
const rules = objectValue(parsedConfig.rules);
|
|
736
|
+
// Without a rules mapping, the effective config adds no file overrides from this section.
|
|
387
737
|
if (!rules) {
|
|
388
738
|
return;
|
|
389
739
|
}
|
|
390
740
|
for (const [ruleId, value] of Object.entries(rules)) {
|
|
391
|
-
const rule = objectValue(value);
|
|
392
|
-
if (!rule) {
|
|
393
|
-
continue;
|
|
394
|
-
}
|
|
395
741
|
// A misspelled id would otherwise sit in the map as a silent no-op the user believes is policy.
|
|
396
742
|
if (!isKnownRuleId(ruleId)) {
|
|
397
743
|
throw new ConfigLoadError(
|
|
@@ -399,13 +745,35 @@ function applyRuleConfig(config: Config, raw: Record<string, unknown>): void {
|
|
|
399
745
|
"Use a rule id from `gruff-ts list-rules`; `rules:` keys must match the catalogue exactly.",
|
|
400
746
|
);
|
|
401
747
|
}
|
|
748
|
+
const rule = objectValue(value);
|
|
749
|
+
// Reject shorthand scalars such as `size.function-length: false` instead of ignoring the override silently.
|
|
750
|
+
if (!rule) {
|
|
751
|
+
throw new ConfigLoadError(
|
|
752
|
+
`Invalid config for rule ${JSON.stringify(ruleId)}: expected a mapping with enabled, threshold, severity, or options.`,
|
|
753
|
+
SUGGEST_EDIT_CONFIG,
|
|
754
|
+
);
|
|
755
|
+
}
|
|
402
756
|
config.rules.set(ruleId, ruleConfigValue(ruleId, rule));
|
|
403
757
|
}
|
|
404
758
|
}
|
|
405
759
|
|
|
406
|
-
//
|
|
407
|
-
|
|
760
|
+
// Every key a rule block may carry; a sibling port's `thresholds:` map is not one of them.
|
|
761
|
+
const RULE_BLOCK_KEYS: ReadonlySet<string> = new Set(["enabled", "options", "severity", "threshold"]);
|
|
762
|
+
|
|
763
|
+
// Option keys that switch a rule on or off for a wider scope, such as the tag rules' `everyCallable`; every other option is numeric.
|
|
764
|
+
const BOOLEAN_RULE_OPTION_KEYS: ReadonlySet<string> = new Set(["everyCallable"]);
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* Builds an override from the supplied rule block; direct config and profiles share this field-validation path.
|
|
768
|
+
* Without an `options` mapping callers use option defaults; throws `ConfigLoadError` for unknown keys or invalid fields.
|
|
769
|
+
*
|
|
770
|
+
* @param ruleId - catalogue rule identifier used to select accepted options and identify errors
|
|
771
|
+
* @param rule - parsed mapping of rule override fields (`enabled`, `threshold`, `severity`, `options`)
|
|
772
|
+
* @returns Validated rule override containing explicit fields and validated option values.
|
|
773
|
+
*/
|
|
408
774
|
function ruleConfigValue(ruleId: string, rule: Record<string, unknown>): RuleOverride {
|
|
775
|
+
// A key alongside threshold that gruff-ts does not read, such as a sibling port's spelling, is refused, not ignored.
|
|
776
|
+
assertKnownKeys(rule, RULE_BLOCK_KEYS, `rules.${ruleId}.`);
|
|
409
777
|
assertRuleThresholdConfig(rule);
|
|
410
778
|
assertRuleEnabledConfig(rule);
|
|
411
779
|
const ruleOverride: RuleOverride = { options: validatedRuleOptions(ruleId, rule.options) };
|
|
@@ -415,13 +783,16 @@ function ruleConfigValue(ruleId: string, rule: Record<string, unknown>): RuleOve
|
|
|
415
783
|
return ruleOverride;
|
|
416
784
|
}
|
|
417
785
|
|
|
418
|
-
|
|
419
|
-
*
|
|
420
|
-
*
|
|
421
|
-
*
|
|
422
|
-
*
|
|
786
|
+
/**
|
|
787
|
+
* Validates the rule block's explicit `enabled` setting before it can change the user's scan.
|
|
788
|
+
* Missing means inherit; throws on YAML words such as `no` because only `true` and `false` reliably control the rule.
|
|
789
|
+
*
|
|
790
|
+
* @param rule - parsed rule mapping to inspect for an `enabled` setting
|
|
791
|
+
* @returns Nothing. Completes when `enabled` is omitted or strictly a true/false flag.
|
|
792
|
+
* @throws {ConfigLoadError} - when the rule block sets enabled to a non-boolean value.
|
|
423
793
|
*/
|
|
424
794
|
function assertRuleEnabledConfig(rule: Record<string, unknown>): void {
|
|
795
|
+
// A supplied non-boolean would otherwise look like a successful enable or disable choice while doing nothing.
|
|
425
796
|
if ("enabled" in rule && typeof rule.enabled !== "boolean") {
|
|
426
797
|
throw new ConfigLoadError(
|
|
427
798
|
`Rule config key "enabled" must be true or false; got ${JSON.stringify(rule.enabled)}.`,
|
|
@@ -430,79 +801,133 @@ function assertRuleEnabledConfig(rule: Record<string, unknown>): void {
|
|
|
430
801
|
}
|
|
431
802
|
}
|
|
432
803
|
|
|
433
|
-
|
|
434
|
-
*
|
|
435
|
-
*
|
|
436
|
-
* "must be configured together" gate would block any severity-only override on those rules even
|
|
437
|
-
* though `gruff-ts list-rules <id>` advertises `rules.<id>.severity` as a public knob. Each field
|
|
438
|
-
* is independently optional and falls through to the descriptor default when absent.
|
|
804
|
+
/**
|
|
805
|
+
* Checks the rule block's optional `threshold` and `severity` overrides independently before analysis.
|
|
806
|
+
* Omitted fields keep their inherited settings; invalid overrides identify the exact field to correct.
|
|
439
807
|
*
|
|
440
|
-
*
|
|
441
|
-
*
|
|
442
|
-
*
|
|
808
|
+
* @param rule - parsed rule mapping to inspect for `threshold` and `severity`
|
|
809
|
+
* @returns Nothing. Completes when supplied `threshold` and `severity` overrides are valid.
|
|
810
|
+
* @throws {ConfigLoadError} - when threshold is nonnumeric or severity is outside advisory, warning, and error.
|
|
443
811
|
*/
|
|
444
812
|
function assertRuleThresholdConfig(rule: Record<string, unknown>): void {
|
|
813
|
+
// A supplied threshold must be numeric to define a meaningful rule boundary for the user.
|
|
445
814
|
if ("threshold" in rule && typeof rule.threshold !== "number") {
|
|
446
815
|
throw new ConfigLoadError('Rule config key "threshold" must be numeric.', SUGGEST_EDIT_CONFIG);
|
|
447
816
|
}
|
|
817
|
+
// A supplied severity must use the report severity names that --fail-on compares against.
|
|
448
818
|
if ("severity" in rule && !isSeverity(rule.severity)) {
|
|
449
819
|
throw new ConfigLoadError('Rule config key "severity" must be "advisory", "warning", or "error".', SUGGEST_EDIT_CONFIG);
|
|
450
820
|
}
|
|
451
821
|
}
|
|
452
822
|
|
|
453
|
-
/**
|
|
823
|
+
/**
|
|
824
|
+
* Copies an explicit `enabled` choice from the configured rule entry into the supplied rule override.
|
|
825
|
+
* Missing values preserve the profile or descriptor behavior the user already selected.
|
|
826
|
+
*
|
|
827
|
+
* @param ruleOverride - target override object updated in place
|
|
828
|
+
* @param rule - parsed rule mapping that may supply an explicit `enabled` flag
|
|
829
|
+
* @returns Nothing. Sets `ruleOverride.enabled` when `rule.enabled` is a true/false flag.
|
|
830
|
+
*/
|
|
454
831
|
function applyRuleEnabledConfig(ruleOverride: RuleOverride, rule: Record<string, unknown>): void {
|
|
832
|
+
// Only an explicit boolean represents a user choice to enable or disable the rule.
|
|
455
833
|
if (typeof rule.enabled === "boolean") {
|
|
456
834
|
ruleOverride.enabled = rule.enabled;
|
|
457
835
|
}
|
|
458
836
|
}
|
|
459
837
|
|
|
460
|
-
/**
|
|
838
|
+
/**
|
|
839
|
+
* Copies a numeric threshold from the configured rule entry into the supplied rule override.
|
|
840
|
+
*
|
|
841
|
+
* @param ruleOverride - target override object updated in place
|
|
842
|
+
* @param rule - parsed rule mapping that may supply a numeric `threshold`
|
|
843
|
+
* @returns Nothing. Sets `ruleOverride.threshold` when `rule.threshold` is numeric.
|
|
844
|
+
*/
|
|
461
845
|
function applyRuleThresholdConfig(ruleOverride: RuleOverride, rule: Record<string, unknown>): void {
|
|
846
|
+
// A missing or nonnumeric setting leaves the override untouched, preserving the inherited threshold when no override exists.
|
|
462
847
|
if (typeof rule.threshold === "number") {
|
|
463
848
|
ruleOverride.threshold = rule.threshold;
|
|
464
849
|
}
|
|
465
850
|
}
|
|
466
851
|
|
|
467
|
-
/**
|
|
852
|
+
/**
|
|
853
|
+
* Copies a supported severity from the configured rule entry into the supplied rule override.
|
|
854
|
+
* Missing or unsupported values leave the inherited severity untouched.
|
|
855
|
+
*
|
|
856
|
+
* @param ruleOverride - target override object updated in place
|
|
857
|
+
* @param rule - parsed rule mapping that may supply a `severity` override
|
|
858
|
+
* @returns Nothing. Sets `ruleOverride.severity` when `rule.severity` is a valid severity.
|
|
859
|
+
*/
|
|
468
860
|
function applyRuleSeverityConfig(ruleOverride: RuleOverride, rule: Record<string, unknown>): void {
|
|
861
|
+
// Only a supported severity can change how the finding appears and affects exit thresholds.
|
|
469
862
|
if (isSeverity(rule.severity)) {
|
|
470
863
|
ruleOverride.severity = rule.severity;
|
|
471
864
|
}
|
|
472
865
|
}
|
|
473
866
|
|
|
474
|
-
|
|
475
|
-
* Validates
|
|
476
|
-
*
|
|
477
|
-
*
|
|
478
|
-
*
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
867
|
+
/**
|
|
868
|
+
* Validates options from `optionsValue` for `ruleId`, using that rule's public option catalogue.
|
|
869
|
+
* Undefined, null, arrays, and non-object values yield an empty map, leaving the rule's option defaults in use.
|
|
870
|
+
*
|
|
871
|
+
* @param ruleId - catalogue rule identifier whose accepted option keys are enforced
|
|
872
|
+
* @param optionsValue - raw `options` value supplied in a rule configuration block
|
|
873
|
+
* @returns Validated option map keyed by option name.
|
|
874
|
+
* @throws {ConfigLoadError} - when an option name is not one the rule accepts, or its value has the wrong type.
|
|
875
|
+
*/
|
|
876
|
+
function validatedRuleOptions(ruleId: string, optionsValue: unknown): Map<string, number | boolean> {
|
|
877
|
+
const options = new Map<string, number | boolean>();
|
|
878
|
+
const configuredOptions = objectValue(optionsValue);
|
|
879
|
+
// No options mapping means this rule uses its documented option defaults.
|
|
880
|
+
if (!configuredOptions) {
|
|
484
881
|
return options;
|
|
485
882
|
}
|
|
486
883
|
const acceptedKeys = ruleOptionKeys(ruleId);
|
|
487
|
-
|
|
884
|
+
// Every supplied option must be both supported by the rule and of its type before analysis uses it.
|
|
885
|
+
for (const [name, option] of Object.entries(configuredOptions)) {
|
|
488
886
|
// Reject unknown keys first so a typo is reported as the typo, not as a type error.
|
|
489
887
|
if (!acceptedKeys.includes(name)) {
|
|
490
888
|
const accepted = acceptedKeys.length > 0 ? `accepts options: ${acceptedKeys.join(", ")}` : "accepts no options";
|
|
491
889
|
throw new ConfigLoadError(`Unknown option ${JSON.stringify(name)} for rule ${ruleId}; the rule ${accepted}.`, SUGGEST_EDIT_CONFIG);
|
|
492
890
|
}
|
|
493
|
-
|
|
494
|
-
throw new ConfigLoadError(`Rule config option ${JSON.stringify(name)} for ${ruleId} must be numeric; got ${JSON.stringify(option)}.`, SUGGEST_EDIT_CONFIG);
|
|
495
|
-
}
|
|
496
|
-
options.set(name, option);
|
|
891
|
+
options.set(name, ruleOptionValue(ruleId, name, option));
|
|
497
892
|
}
|
|
498
893
|
return options;
|
|
499
894
|
}
|
|
500
895
|
|
|
501
|
-
|
|
502
|
-
|
|
896
|
+
/**
|
|
897
|
+
* Validates one rule option value using boolean or numeric checks selected by `name`.
|
|
898
|
+
*
|
|
899
|
+
* @param ruleId - catalogue rule identifier reported in error diagnostics
|
|
900
|
+
* @param name - option key selecting boolean switch validation or numeric validation
|
|
901
|
+
* @param option - raw configured option value for `name`
|
|
902
|
+
* @returns Unchanged `option` value once confirmed to match the expected type.
|
|
903
|
+
* @throws {ConfigLoadError} - when a switch is not a boolean, or a numeric option is not a number.
|
|
904
|
+
*/
|
|
905
|
+
function ruleOptionValue(ruleId: string, name: string, option: unknown): number | boolean {
|
|
906
|
+
const isSwitch = BOOLEAN_RULE_OPTION_KEYS.has(name);
|
|
907
|
+
// A switch takes only true or false, so a YAML word such as yes cannot look like a choice that does nothing.
|
|
908
|
+
if (isSwitch && typeof option === "boolean") {
|
|
909
|
+
return option;
|
|
910
|
+
}
|
|
911
|
+
// A numeric option takes only a number, because nothing else can define the boundary the user intended.
|
|
912
|
+
if (!isSwitch && typeof option === "number") {
|
|
913
|
+
return option;
|
|
914
|
+
}
|
|
915
|
+
const expected = isSwitch ? "true or false" : "numeric";
|
|
916
|
+
throw new ConfigLoadError(`Rule config option ${JSON.stringify(name)} for ${ruleId} must be ${expected}; got ${JSON.stringify(option)}.`, SUGGEST_EDIT_CONFIG);
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/**
|
|
920
|
+
* Finds the first existing candidate path under `projectRoot` for zero-argument config discovery.
|
|
921
|
+
* Returns `undefined` when no candidate exists, so loading starts from built-in defaults.
|
|
922
|
+
*
|
|
923
|
+
* @param projectRoot - workspace directory checked in deterministic priority order for default config files
|
|
924
|
+
* @returns Path to the first existing candidate config file, or `undefined` when none exists.
|
|
925
|
+
*/
|
|
503
926
|
function defaultConfigPath(projectRoot: string): string | undefined {
|
|
927
|
+
// Config names are checked in documented priority order so users get a deterministic selection.
|
|
504
928
|
for (const fileName of DEFAULT_CONFIG_FILES) {
|
|
505
929
|
const candidate = join(projectRoot, fileName);
|
|
930
|
+
// Discovery selects one path. The loader handles reading and validation.
|
|
506
931
|
if (existsSync(candidate)) {
|
|
507
932
|
return candidate;
|
|
508
933
|
}
|
|
@@ -510,34 +935,137 @@ function defaultConfigPath(projectRoot: string): string | undefined {
|
|
|
510
935
|
return undefined;
|
|
511
936
|
}
|
|
512
937
|
|
|
513
|
-
|
|
514
|
-
|
|
938
|
+
/**
|
|
939
|
+
* Determines whether one rule should run for the user's scan.
|
|
940
|
+
* If the effective config has no enabled override for the rule, it runs unless its descriptor disables it by default.
|
|
941
|
+
*
|
|
942
|
+
* @param config - effective analysis configuration holding per-rule overrides
|
|
943
|
+
* @param ruleId - catalogue rule identifier to query
|
|
944
|
+
* @returns Whether `ruleId` is enabled for the scan.
|
|
945
|
+
*/
|
|
515
946
|
function ruleEnabled(config: Config, ruleId: string): boolean {
|
|
516
|
-
return config.rules.get(ruleId)?.enabled ??
|
|
947
|
+
return config.rules.get(ruleId)?.enabled ?? ruleDefaultEnabled(ruleId);
|
|
517
948
|
}
|
|
518
949
|
|
|
519
|
-
|
|
520
|
-
|
|
950
|
+
/**
|
|
951
|
+
* Looks up the configured threshold for one rule or falls back to the caller's documented default.
|
|
952
|
+
* Rules use this during analysis so omitted user settings behave consistently.
|
|
953
|
+
*
|
|
954
|
+
* @param config - effective analysis configuration holding per-rule overrides
|
|
955
|
+
* @param ruleId - catalogue rule identifier to query
|
|
956
|
+
* @param defaultValue - fallback limit used when no threshold override is configured
|
|
957
|
+
* @returns Configured threshold for `ruleId`, or `defaultValue` when omitted.
|
|
958
|
+
*/
|
|
521
959
|
function threshold(config: Config, ruleId: string, defaultValue: number): number {
|
|
522
960
|
return config.rules.get(ruleId)?.threshold ?? defaultValue;
|
|
523
961
|
}
|
|
524
962
|
|
|
525
|
-
|
|
526
|
-
|
|
963
|
+
/**
|
|
964
|
+
* Looks up the configured severity for one rule or falls back to the descriptor default shown to users.
|
|
965
|
+
* Rules use this when building findings so report severity and exit behavior stay aligned.
|
|
966
|
+
*
|
|
967
|
+
* @param config - effective analysis configuration holding per-rule overrides
|
|
968
|
+
* @param ruleId - catalogue rule identifier to query
|
|
969
|
+
* @param defaultSeverity - fallback severity used when no override is configured
|
|
970
|
+
* @returns Effective severity for `ruleId`.
|
|
971
|
+
*/
|
|
527
972
|
function ruleSeverity(config: Config, ruleId: string, defaultSeverity: Severity): Severity {
|
|
528
973
|
return config.rules.get(ruleId)?.severity ?? defaultSeverity;
|
|
529
974
|
}
|
|
530
975
|
|
|
531
|
-
|
|
532
|
-
|
|
976
|
+
/**
|
|
977
|
+
* Looks up the named numeric option for the selected rule in the effective config.
|
|
978
|
+
*
|
|
979
|
+
* @param config - effective analysis configuration holding per-rule overrides
|
|
980
|
+
* @param ruleId - catalogue rule identifier to query
|
|
981
|
+
* @param name - option key to read from the rule's validated options map
|
|
982
|
+
* @param defaultValue - fallback value returned when the option is missing or has another type
|
|
983
|
+
* @returns Configured option value for `name`, or `defaultValue` when absent or of another type.
|
|
984
|
+
*/
|
|
533
985
|
function optionNumber(config: Config, ruleId: string, name: string, defaultValue: number): number {
|
|
534
|
-
|
|
986
|
+
const option = config.rules.get(ruleId)?.options.get(name);
|
|
987
|
+
return typeof option === "number" ? option : defaultValue;
|
|
535
988
|
}
|
|
536
989
|
|
|
537
|
-
|
|
538
|
-
|
|
990
|
+
/**
|
|
991
|
+
* Looks up a named switch for the selected rule in the effective config, such as `everyCallable` for a tag rule.
|
|
992
|
+
*
|
|
993
|
+
* @param config - effective analysis configuration holding per-rule overrides
|
|
994
|
+
* @param ruleId - catalogue rule identifier to query
|
|
995
|
+
* @param name - option key to read from the rule's validated options map
|
|
996
|
+
* @param isOnByDefault - fallback flag returned when the option is missing or has another type
|
|
997
|
+
* @returns Configured switch state for `name`, or `isOnByDefault` when absent or of another type.
|
|
998
|
+
*/
|
|
999
|
+
function optionBoolean(config: Config, ruleId: string, name: string, isOnByDefault: boolean): boolean {
|
|
1000
|
+
const option = config.rules.get(ruleId)?.options.get(name);
|
|
1001
|
+
return typeof option === "boolean" ? option : isOnByDefault;
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
/**
|
|
1005
|
+
* Checks whether a parsed config value belongs to the public severity vocabulary (`advisory`, `warning`, or `error`).
|
|
1006
|
+
* Load-time validation and rule application share this guard so users see one consistent set of accepted values.
|
|
1007
|
+
*
|
|
1008
|
+
* @param configValue - raw configuration value to test against the supported severity names
|
|
1009
|
+
* @returns Whether `configValue` is a valid severity name.
|
|
1010
|
+
*/
|
|
539
1011
|
function isSeverity(configValue: unknown): configValue is Severity {
|
|
540
1012
|
return configValue === "advisory" || configValue === "warning" || configValue === "error";
|
|
541
1013
|
}
|
|
542
1014
|
|
|
543
|
-
|
|
1015
|
+
/**
|
|
1016
|
+
* Validates an already-parsed configuration mapping against the 0.6.0 config loader, including inline and built-in `profile:` blocks.
|
|
1017
|
+
*
|
|
1018
|
+
* Used by `migrate-config` so migrated output is guaranteed loadable before it is written.
|
|
1019
|
+
* When `baseDirectory` is supplied, relative file-backed profile references are resolved on disk too.
|
|
1020
|
+
*
|
|
1021
|
+
* @param parsedConfig - parsed YAML or JSON config object to validate
|
|
1022
|
+
* @param baseDirectory - optional folder for resolving file-backed profiles; when omitted, only built-in names and file-shaped paths are checked
|
|
1023
|
+
* @returns Nothing. Completes when every key, profile, rule override, allowlist, and sensitive exclusion passes 0.6.0 validation.
|
|
1024
|
+
* @throws {ConfigLoadError} - when any key, profile, rule id, option, allowlist, or sensitive exclusion would be rejected by `loadConfig`.
|
|
1025
|
+
*/
|
|
1026
|
+
function validateParsedConfig(parsedConfig: Record<string, unknown>, baseDirectory?: string): void {
|
|
1027
|
+
applyConfigValues(defaultConfig(), parsedConfig);
|
|
1028
|
+
// A migrated `profile:` must still name a real profile, or the migrated file would fail when the user next runs a scan.
|
|
1029
|
+
if (parsedConfig.profile !== undefined) {
|
|
1030
|
+
validateProfileValue(parseProfileSpec(parsedConfig.profile), baseDirectory);
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
/**
|
|
1035
|
+
* Validates a parsed `profile:` specification against built-in presets, rule IDs, and optionally on-disk file references.
|
|
1036
|
+
*
|
|
1037
|
+
* @param spec - parsed string or inline profile specification from configuration
|
|
1038
|
+
* @param baseDirectory - optional folder for resolving file-backed profiles; when omitted, on-disk profile files cannot be opened
|
|
1039
|
+
* @returns Nothing. Throws when the profile references an unknown preset/rule or fails resolution.
|
|
1040
|
+
* @throws {ConfigLoadError} - when a rule ID, built-in profile name, or referenced profile file is invalid.
|
|
1041
|
+
*/
|
|
1042
|
+
function validateProfileValue(spec: ProfileSpec, baseDirectory: string | undefined): void {
|
|
1043
|
+
// When the config's folder is known, resolve the profile exactly as a scan would, including profile files on disk.
|
|
1044
|
+
if (baseDirectory !== undefined) {
|
|
1045
|
+
resolveProfile(spec, baseDirectory);
|
|
1046
|
+
return;
|
|
1047
|
+
}
|
|
1048
|
+
// An inline profile can override rules; each one must be a rule ID this version knows.
|
|
1049
|
+
if (typeof spec === "object") {
|
|
1050
|
+
// The first unknown rule ID stops the migration with a config error.
|
|
1051
|
+
for (const ruleId of Object.keys(spec.rules ?? {})) {
|
|
1052
|
+
assertKnownProfileRule(ruleId);
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
const ref = typeof spec === "string" ? spec : spec.extends;
|
|
1056
|
+
// An inline profile without `extends:` has no base profile to check.
|
|
1057
|
+
if (ref === undefined) {
|
|
1058
|
+
return;
|
|
1059
|
+
}
|
|
1060
|
+
const isBuiltIn = BUILT_IN_PROFILES.has(ref) || BUILT_IN_PROFILES.has(`gruff.${ref}`);
|
|
1061
|
+
const looksLikeFilePath = /[\\/]|(?:\.ya?ml|\.json)$/iu.test(ref);
|
|
1062
|
+
// Without a folder to resolve files against, accept only a built-in name or a value shaped like a profile file path.
|
|
1063
|
+
if (!isBuiltIn && !looksLikeFilePath) {
|
|
1064
|
+
throw new ConfigLoadError(
|
|
1065
|
+
`Unknown profile: ${JSON.stringify(ref)}.`,
|
|
1066
|
+
`Use a built-in profile name (${builtInProfileNames().join(", ")}) or point at an existing .yaml/.yml/.json profile file.`,
|
|
1067
|
+
);
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
export { defaultConfigPath, loadConfig, minimumSeverityFor, optionBoolean, optionNumber, resolveProfile, ruleEnabled, ruleSeverity, threshold, validateParsedConfig };
|