@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
|
@@ -0,0 +1,670 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Updates a 0.5 project config for 0.6 when the user runs `migrate-config`.
|
|
3
|
+
*
|
|
4
|
+
* YAML edits keep surrounding comments and settings; JSON rewrites the document when a change is needed:
|
|
5
|
+
* - moves per-command exit gates to `failOn` and drops obsolete secret previews;
|
|
6
|
+
* - prunes retired 0.5 rules, allowlist keys, and sensitive exclusions;
|
|
7
|
+
* - pins `schemaVersion` and validates the migrated config through the 0.6 loader before returning.
|
|
8
|
+
*/
|
|
9
|
+
import { validateParsedConfig } from "./config.ts";
|
|
10
|
+
import { ConfigLoadError } from "./config-load-error.ts";
|
|
11
|
+
import { arrayValue, isString, objectValue, parseYamlConfig, SUGGEST_EDIT_CONFIG } from "./config-parse.ts";
|
|
12
|
+
import { isKnownRuleId } from "./profiles.ts";
|
|
13
|
+
|
|
14
|
+
// The one schema version this build reads; a migrated file that named another would be refused on the next run.
|
|
15
|
+
const SCHEMA_VERSION = "gruff-ts.config.v0.1";
|
|
16
|
+
|
|
17
|
+
/** One rewrite the migration applied, as a line a user can read against their own file. */
|
|
18
|
+
export interface ConfigMigrationChange {
|
|
19
|
+
line: number;
|
|
20
|
+
description: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/*
|
|
24
|
+
* The result of migrating one configuration file.
|
|
25
|
+
*
|
|
26
|
+
* `text` is what the CLI can write to the destination. An empty `changes` list means no settings needed updating.
|
|
27
|
+
*/
|
|
28
|
+
export interface ConfigMigration {
|
|
29
|
+
text: string;
|
|
30
|
+
changes: ConfigMigrationChange[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// The removed redaction key, dropped with any block it carries. Section 5 makes category markers unconditional.
|
|
34
|
+
const REMOVED_ALLOWLIST_KEY = "secretPreviews";
|
|
35
|
+
|
|
36
|
+
// The per-command exit gate's former spelling; as a scalar the same key is the 0.6 display floor and stays put.
|
|
37
|
+
const RENAMED_GATE_KEY = "minimumSeverity";
|
|
38
|
+
|
|
39
|
+
// The seven allowlist keys read only by retired 0.5 rules (UPGRADING.md item 24); removed during migration while real typos stay rejected.
|
|
40
|
+
const RETIRED_ALLOWLIST_KEYS: ReadonlySet<string> = new Set([
|
|
41
|
+
"acceptedBooleanNames",
|
|
42
|
+
"acceptedCasingPairs",
|
|
43
|
+
"bannedGenericNames",
|
|
44
|
+
"booleanPrefixes",
|
|
45
|
+
"hungarianPrefixes",
|
|
46
|
+
"knownAcronyms",
|
|
47
|
+
"negativeBooleanAllowed",
|
|
48
|
+
]);
|
|
49
|
+
|
|
50
|
+
// The 40 rules retired in 0.6.0 under ADR-021 (UPGRADING.md items 21, 24, and 26). Only known retired ids are
|
|
51
|
+
// pruned automatically so genuine typos in `rules:` or `sensitiveExclusions:` still fail validation loudly.
|
|
52
|
+
const RETIRED_0_5_RULE_IDS: ReadonlySet<string> = new Set([
|
|
53
|
+
"complexity.cognitive",
|
|
54
|
+
"design.deep-relative-import",
|
|
55
|
+
"docs.magic-threshold-without-rationale",
|
|
56
|
+
"docs.stale-comment",
|
|
57
|
+
"docs.useless-docblock",
|
|
58
|
+
"modernisation.loose-equality",
|
|
59
|
+
"modernisation.nullish-coalescing-candidate",
|
|
60
|
+
"modernisation.object-spread-candidate",
|
|
61
|
+
"modernisation.optional-chaining-candidate",
|
|
62
|
+
"modernisation.public-property",
|
|
63
|
+
"naming.acronym-case",
|
|
64
|
+
"naming.boolean-prefix",
|
|
65
|
+
"naming.generic-function",
|
|
66
|
+
"naming.generic-parameter",
|
|
67
|
+
"naming.hungarian-notation",
|
|
68
|
+
"naming.inconsistent-casing",
|
|
69
|
+
"naming.negative-boolean",
|
|
70
|
+
"security.floating-promise",
|
|
71
|
+
"security.github-actions-broad-permissions",
|
|
72
|
+
"security.insecure-random",
|
|
73
|
+
"security.process-exec",
|
|
74
|
+
"security.proto-access",
|
|
75
|
+
"security.risky-lifecycle-script",
|
|
76
|
+
"sensitive-data.hardcoded-env-value",
|
|
77
|
+
"sensitive-data.high-entropy-string",
|
|
78
|
+
"test-quality.conditional-logic",
|
|
79
|
+
"test-quality.exception-type-only",
|
|
80
|
+
"test-quality.magic-number-assertion",
|
|
81
|
+
"test-quality.mock-only-test",
|
|
82
|
+
"test-quality.no-assertions",
|
|
83
|
+
"test-quality.no-throw-only-test",
|
|
84
|
+
"test-quality.only-skip",
|
|
85
|
+
"test-quality.sleep-in-test",
|
|
86
|
+
"test-quality.snapshot-only-test",
|
|
87
|
+
"waste.commented-out-code",
|
|
88
|
+
"waste.console-log",
|
|
89
|
+
"waste.empty-function",
|
|
90
|
+
"waste.redundant-boolean-cast",
|
|
91
|
+
"waste.redundant-variable",
|
|
92
|
+
"waste.unused-parameter",
|
|
93
|
+
]);
|
|
94
|
+
|
|
95
|
+
/** Active YAML block tracked while scanning lines so pruning only touches matching child sections. */
|
|
96
|
+
interface ActiveYamlSection {
|
|
97
|
+
name: "allowlists" | "rules" | "profileRules" | "sensitiveExclusions";
|
|
98
|
+
childIndent: number;
|
|
99
|
+
headerMigratedIndex: number;
|
|
100
|
+
keptEntryCount: number;
|
|
101
|
+
removedEntryCount: number;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Converts legacy settings for `migrate-config` and returns the changes the CLI can show during a dry run.
|
|
106
|
+
* Validates the migrated result against the 0.6 loader before returning so broken output is never written.
|
|
107
|
+
*
|
|
108
|
+
* @param original - the whole config file. Empty YAML has no settings yet, while empty JSON is invalid.
|
|
109
|
+
* @param format - syntax selected by the config file's extension. An omitted format uses YAML.
|
|
110
|
+
* @param baseDirectory - optional directory used to resolve relative `profile:` references during validation.
|
|
111
|
+
* @returns the destination text and one entry per rewrite. An empty change list means the settings were current.
|
|
112
|
+
* @throws {ConfigLoadError} when the input cannot be parsed, contains conflicting migration keys, or fails 0.6 validation after migration.
|
|
113
|
+
*/
|
|
114
|
+
export function migrateConfigText(original: string, format: "yaml" | "json" = "yaml", baseDirectory?: string): ConfigMigration {
|
|
115
|
+
// An editor may add a byte-order mark. Strip it before parsing the selected file format.
|
|
116
|
+
const source = original.replace(/^\uFEFF/u, "");
|
|
117
|
+
return format === "json" ? migrateJsonConfig(source, baseDirectory) : migrateYamlConfig(source, original, baseDirectory);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Rewrites legacy YAML lines in place because re-serializing through a YAML emitter would strip user comments and formatting,
|
|
122
|
+
* then validates the rewritten document through the 0.6 loader.
|
|
123
|
+
*
|
|
124
|
+
* @param source - BOM-stripped YAML config text
|
|
125
|
+
* @param original - untouched original text returned verbatim when zero rewrites apply
|
|
126
|
+
* @param baseDirectory - optional directory used to resolve relative `profile:` references during validation
|
|
127
|
+
* @returns Migrated YAML text and ordered change descriptions.
|
|
128
|
+
* @throws {ConfigLoadError} when the input has conflicting keys, flow-style legacy keys survive, or 0.6 validation rejects the result.
|
|
129
|
+
*/
|
|
130
|
+
function migrateYamlConfig(source: string, original: string, baseDirectory?: string): ConfigMigration {
|
|
131
|
+
const shouldRenameGate = hasLegacyCommandGate(parseYamlConfig(source));
|
|
132
|
+
const lines = source.split(/\r?\n/u);
|
|
133
|
+
const rootIndent = leadingSpaces(lines[nextContentLine(lines, 0)] ?? "");
|
|
134
|
+
const changes: ConfigMigrationChange[] = [];
|
|
135
|
+
const migrated: string[] = [];
|
|
136
|
+
let activeSection: ActiveYamlSection | undefined;
|
|
137
|
+
let profileChildIndent: number | undefined;
|
|
138
|
+
let index = 0;
|
|
139
|
+
|
|
140
|
+
while (index < lines.length) {
|
|
141
|
+
const line = lines[index] ?? "";
|
|
142
|
+
const indent = leadingSpaces(line);
|
|
143
|
+
const trimmed = line.trim();
|
|
144
|
+
const isContentLine = trimmed.length > 0 && !trimmed.startsWith("#");
|
|
145
|
+
const isRootKey = indent === rootIndent && isContentLine;
|
|
146
|
+
if (isRootKey) {
|
|
147
|
+
finalizeEmptiedYamlSection(activeSection, migrated);
|
|
148
|
+
activeSection = enterYamlSection(lines, index, migrated.length);
|
|
149
|
+
profileChildIndent = enterYamlProfileBlock(lines, index);
|
|
150
|
+
} else if (profileChildIndent !== undefined && isContentLine && indent === profileChildIndent) {
|
|
151
|
+
// Inline `profile:` can carry its own nested `rules:` block whose retired 0.5 IDs must be pruned too.
|
|
152
|
+
finalizeEmptiedYamlSection(activeSection, migrated);
|
|
153
|
+
activeSection = enterYamlProfileRulesSection(lines, index, migrated.length);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const skipped = activeSection ? tryPruneYamlSectionEntry(activeSection, lines, index, changes) : 0;
|
|
157
|
+
if (skipped > 0) {
|
|
158
|
+
index += skipped;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const renamed = isRootKey && shouldRenameGate
|
|
163
|
+
? line.replace(/^(\s*)(?:minimumSeverity|"minimumSeverity"|'minimumSeverity')(\s*:)/u, "$1failOn$2")
|
|
164
|
+
: line;
|
|
165
|
+
|
|
166
|
+
if (renamed !== line) {
|
|
167
|
+
changes.push({ line: index + 1, description: `${RENAMED_GATE_KEY}: renamed to failOn:, which is the key that gates the exit code in 0.6` });
|
|
168
|
+
migrated.push(renamed);
|
|
169
|
+
index += 1;
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
migrated.push(line);
|
|
174
|
+
index += 1;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
finalizeEmptiedYamlSection(activeSection, migrated);
|
|
178
|
+
const result = withSchemaVersion(migrated, changes, original, rootIndent);
|
|
179
|
+
const updated = parseYamlConfig(result.text);
|
|
180
|
+
// A YAML key written in flow style can survive line-level removal. Stop before emitting unusable settings.
|
|
181
|
+
if (objectValue(updated.minimumSeverity) !== undefined || Object.hasOwn(objectValue(updated.allowlists) ?? {}, REMOVED_ALLOWLIST_KEY)) {
|
|
182
|
+
throw new ConfigLoadError("The legacy gate or allowlist could not be migrated safely.", SUGGEST_EDIT_CONFIG);
|
|
183
|
+
}
|
|
184
|
+
validateParsedConfig(updated, baseDirectory);
|
|
185
|
+
return result;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const EMPTIED_SECTION_HEADER = /^(\s*["']?(?:allowlists|rules|sensitiveExclusions)["']?\s*:)(\s*(?:#.*)?)$/u;
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Rewrites an emptied `sensitiveExclusions:`, `allowlists:`, or `rules:` YAML header to `[]` or `{}` so the migrated YAML stays valid.
|
|
192
|
+
*
|
|
193
|
+
* @param section - section state closing at a new root key or end-of-file
|
|
194
|
+
* @param migrated - mutable migrated lines array whose header line may be updated
|
|
195
|
+
* @returns Nothing. Updates `migrated[section.headerMigratedIndex]` only when every entry in `section` was pruned.
|
|
196
|
+
*/
|
|
197
|
+
function finalizeEmptiedYamlSection(section: ActiveYamlSection | undefined, migrated: string[]): void {
|
|
198
|
+
if (!section || section.removedEntryCount === 0 || section.keptEntryCount > 0) {
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
const headerLine = migrated[section.headerMigratedIndex];
|
|
202
|
+
if (headerLine !== undefined) {
|
|
203
|
+
const emptyLiteral = section.name === "sensitiveExclusions" ? "[]" : "{}";
|
|
204
|
+
migrated[section.headerMigratedIndex] = headerLine.replace(EMPTIED_SECTION_HEADER, `$1 ${emptyLiteral}$2`);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Identifies whether a root YAML key opens a migratable block (`allowlists`, `rules`, or `sensitiveExclusions`) and records its child indentation.
|
|
210
|
+
*
|
|
211
|
+
* @param lines - split YAML source lines
|
|
212
|
+
* @param index - current root key line index
|
|
213
|
+
* @param headerMigratedIndex - index where this header line will be written in `migrated`
|
|
214
|
+
* @returns Active section tracker when the root key has indented children, or undefined otherwise.
|
|
215
|
+
*/
|
|
216
|
+
function enterYamlSection(lines: string[], index: number, headerMigratedIndex: number): ActiveYamlSection | undefined {
|
|
217
|
+
const header = lines[index] ?? "";
|
|
218
|
+
const match = header.match(/^\s*(?:(allowlists|rules|sensitiveExclusions)|"(allowlists|rules|sensitiveExclusions)"|'(allowlists|rules|sensitiveExclusions)')\s*:\s*(?:#.*)?$/u);
|
|
219
|
+
const sectionName = (match?.[1] ?? match?.[2] ?? match?.[3]) as ActiveYamlSection["name"] | undefined;
|
|
220
|
+
if (!sectionName) {
|
|
221
|
+
return undefined;
|
|
222
|
+
}
|
|
223
|
+
const childLineIndex = nextContentLine(lines, index + 1);
|
|
224
|
+
const childIndent = leadingSpaces(lines[childLineIndex] ?? "");
|
|
225
|
+
if (childIndent <= leadingSpaces(header)) {
|
|
226
|
+
return undefined;
|
|
227
|
+
}
|
|
228
|
+
return { name: sectionName, childIndent, headerMigratedIndex, keptEntryCount: 0, removedEntryCount: 0 };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Checks whether a root YAML key opens an inline `profile:` mapping and returns its direct-child indentation.
|
|
233
|
+
*
|
|
234
|
+
* @param lines - split YAML source lines
|
|
235
|
+
* @param index - current root key line index
|
|
236
|
+
* @returns Child indentation when `profile:` has indented mapping keys, or undefined otherwise.
|
|
237
|
+
*/
|
|
238
|
+
function enterYamlProfileBlock(lines: string[], index: number): number | undefined {
|
|
239
|
+
const header = lines[index] ?? "";
|
|
240
|
+
// Only a bare `profile:` header opens an inline profile; `profile: strict` names a built-in profile and has no rules to prune.
|
|
241
|
+
if (!/^\s*(?:profile|"profile"|'profile')\s*:\s*(?:#.*)?$/u.test(header)) {
|
|
242
|
+
return undefined;
|
|
243
|
+
}
|
|
244
|
+
const childLineIndex = nextContentLine(lines, index + 1);
|
|
245
|
+
const childIndent = leadingSpaces(lines[childLineIndex] ?? "");
|
|
246
|
+
return childIndent > leadingSpaces(header) ? childIndent : undefined;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Identifies whether a direct child key under an inline YAML `profile:` block opens a `rules:` mapping.
|
|
251
|
+
*
|
|
252
|
+
* @param lines - split YAML source lines
|
|
253
|
+
* @param index - current profile-child line index
|
|
254
|
+
* @param headerMigratedIndex - index where this header line will be written in `migrated`
|
|
255
|
+
* @returns Active `profileRules` section tracker when `rules:` has indented children, or undefined otherwise.
|
|
256
|
+
*/
|
|
257
|
+
function enterYamlProfileRulesSection(lines: string[], index: number, headerMigratedIndex: number): ActiveYamlSection | undefined {
|
|
258
|
+
const header = lines[index] ?? "";
|
|
259
|
+
// Only a `rules:` header inside the inline profile can hold rule entries to prune.
|
|
260
|
+
if (!/^\s*(?:rules|"rules"|'rules')\s*:\s*(?:#.*)?$/u.test(header)) {
|
|
261
|
+
return undefined;
|
|
262
|
+
}
|
|
263
|
+
const childLineIndex = nextContentLine(lines, index + 1);
|
|
264
|
+
const childIndent = leadingSpaces(lines[childLineIndex] ?? "");
|
|
265
|
+
// A `rules:` key with nothing indented under it has no entries to prune.
|
|
266
|
+
if (childIndent <= leadingSpaces(header)) {
|
|
267
|
+
return undefined;
|
|
268
|
+
}
|
|
269
|
+
return { name: "profileRules", childIndent, headerMigratedIndex, keptEntryCount: 0, removedEntryCount: 0 };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Attempts to prune one retired entry at `index` inside the active YAML section (`allowlists`, `rules`, `profileRules`, or `sensitiveExclusions`).
|
|
274
|
+
* Tracks kept vs removed entries so an emptied section header can be rewritten to `[]` or `{}`.
|
|
275
|
+
*
|
|
276
|
+
* @param section - active YAML section metadata, mutated with kept/removed counts
|
|
277
|
+
* @param lines - full YAML lines array
|
|
278
|
+
* @param index - current line index
|
|
279
|
+
* @param changes - migration change log appended when an entry is pruned
|
|
280
|
+
* @returns Number of lines skipped (0 when the line is kept).
|
|
281
|
+
*/
|
|
282
|
+
function tryPruneYamlSectionEntry(section: ActiveYamlSection, lines: string[], index: number, changes: ConfigMigrationChange[]): number {
|
|
283
|
+
const line = lines[index] ?? "";
|
|
284
|
+
const trimmed = line.trim();
|
|
285
|
+
if (trimmed.length === 0 || trimmed.startsWith("#") || leadingSpaces(line) !== section.childIndent) {
|
|
286
|
+
return 0;
|
|
287
|
+
}
|
|
288
|
+
if (section.name === "allowlists") {
|
|
289
|
+
return pruneYamlAllowlistEntry(section, lines, index, changes);
|
|
290
|
+
}
|
|
291
|
+
// Top-level rules and an inline profile's rules are pruned the same way.
|
|
292
|
+
if (section.name === "rules" || section.name === "profileRules") {
|
|
293
|
+
return pruneYamlRuleEntry(section, lines, index, changes);
|
|
294
|
+
}
|
|
295
|
+
return pruneYamlSensitiveExclusionEntry(section, lines, index, changes);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Drops `secretPreviews` or any retired 0.5 allowlist key and its indented children inside `allowlists:`.
|
|
300
|
+
*
|
|
301
|
+
* @param section - active `allowlists` tracker updated with kept/removed counts
|
|
302
|
+
* @param lines - full YAML lines array
|
|
303
|
+
* @param index - line index of one key inside `allowlists:`
|
|
304
|
+
* @param changes - migration change log appended on removal
|
|
305
|
+
* @returns Count of lines to skip, or 0 when the allowlist key is current.
|
|
306
|
+
*/
|
|
307
|
+
function pruneYamlAllowlistEntry(section: ActiveYamlSection, lines: string[], index: number, changes: ConfigMigrationChange[]): number {
|
|
308
|
+
const key = yamlMappingKey(lines[index] ?? "");
|
|
309
|
+
if (!key) {
|
|
310
|
+
return 0;
|
|
311
|
+
}
|
|
312
|
+
if (key === REMOVED_ALLOWLIST_KEY) {
|
|
313
|
+
section.removedEntryCount += 1;
|
|
314
|
+
changes.push({ line: index + 1, description: `allowlists.${REMOVED_ALLOWLIST_KEY} removed; FAMILY-CONTRACT.md section 5 makes category markers unconditional` });
|
|
315
|
+
return indentedBlockLength(lines, index);
|
|
316
|
+
}
|
|
317
|
+
if (RETIRED_ALLOWLIST_KEYS.has(key)) {
|
|
318
|
+
section.removedEntryCount += 1;
|
|
319
|
+
changes.push({ line: index + 1, description: `allowlists.${key} removed; only read by rules retired in 0.6.0` });
|
|
320
|
+
return indentedBlockLength(lines, index);
|
|
321
|
+
}
|
|
322
|
+
section.keptEntryCount += 1;
|
|
323
|
+
return 0;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Drops a retired 0.5 rule block and its indented settings inside `rules:`.
|
|
328
|
+
*
|
|
329
|
+
* @param section - active `rules` tracker updated with kept/removed counts
|
|
330
|
+
* @param lines - full YAML lines array
|
|
331
|
+
* @param index - line index of one rule key inside `rules:`
|
|
332
|
+
* @param changes - migration change log appended on removal
|
|
333
|
+
* @returns Count of lines to skip, or 0 when the rule key is active or unrecognized (left for loader validation).
|
|
334
|
+
*/
|
|
335
|
+
function pruneYamlRuleEntry(section: ActiveYamlSection, lines: string[], index: number, changes: ConfigMigrationChange[]): number {
|
|
336
|
+
const ruleId = yamlMappingKey(lines[index] ?? "");
|
|
337
|
+
if (!ruleId) {
|
|
338
|
+
return 0;
|
|
339
|
+
}
|
|
340
|
+
if (!isRetiredRuleId(ruleId)) {
|
|
341
|
+
section.keptEntryCount += 1;
|
|
342
|
+
return 0;
|
|
343
|
+
}
|
|
344
|
+
section.removedEntryCount += 1;
|
|
345
|
+
const prefix = section.name === "profileRules" ? "profile.rules" : "rules";
|
|
346
|
+
changes.push({ line: index + 1, description: `${prefix}.${ruleId} removed; rule retired in 0.6.0` });
|
|
347
|
+
return indentedBlockLength(lines, index);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Drops a YAML sequence entry under `sensitiveExclusions:` when its `rule:` names a rule retired in 0.6.0.
|
|
352
|
+
*
|
|
353
|
+
* @param section - active `sensitiveExclusions` tracker updated with kept/removed counts
|
|
354
|
+
* @param lines - full YAML lines array
|
|
355
|
+
* @param index - line index of one `- ...` sequence item
|
|
356
|
+
* @param changes - migration change log appended on removal
|
|
357
|
+
* @returns Count of lines to skip, or 0 when the entry stays.
|
|
358
|
+
*/
|
|
359
|
+
function pruneYamlSensitiveExclusionEntry(section: ActiveYamlSection, lines: string[], index: number, changes: ConfigMigrationChange[]): number {
|
|
360
|
+
const line = lines[index] ?? "";
|
|
361
|
+
if (!/^\s*-\s*/u.test(line)) {
|
|
362
|
+
return 0;
|
|
363
|
+
}
|
|
364
|
+
const length = yamlSequenceItemLength(lines, index);
|
|
365
|
+
const itemLines = lines.slice(index, index + length);
|
|
366
|
+
const ruleId = yamlSequenceItemRuleId(itemLines);
|
|
367
|
+
if (ruleId && isRetiredRuleId(ruleId)) {
|
|
368
|
+
section.removedEntryCount += 1;
|
|
369
|
+
changes.push({ line: index + 1, description: `sensitiveExclusions entry for ${ruleId} removed; rule retired in 0.6.0` });
|
|
370
|
+
return length;
|
|
371
|
+
}
|
|
372
|
+
section.keptEntryCount += 1;
|
|
373
|
+
return 0;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* Extracts an unquoted or quoted YAML mapping key from one indented key line.
|
|
378
|
+
*
|
|
379
|
+
* @param line - single YAML line expected to start with a mapping key and colon
|
|
380
|
+
* @returns Unquoted key string, or undefined when the line is not a mapping key.
|
|
381
|
+
*/
|
|
382
|
+
function yamlMappingKey(line: string): string | undefined {
|
|
383
|
+
const match = line.match(/^\s+(?:"([^"]+)"|'([^']+)'|([^:#\s][^:]*?))\s*:/u);
|
|
384
|
+
const key = match?.[1] ?? match?.[2] ?? match?.[3];
|
|
385
|
+
return key?.trim();
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Extracts the `rule:` scalar from a single YAML `sensitiveExclusions:` sequence item's lines.
|
|
390
|
+
*
|
|
391
|
+
* @param itemLines - lines spanning one `- ...` item inside `sensitiveExclusions:`
|
|
392
|
+
* @returns Trimmed rule id string, or undefined when no `rule:` field is present.
|
|
393
|
+
*/
|
|
394
|
+
function yamlSequenceItemRuleId(itemLines: readonly string[]): string | undefined {
|
|
395
|
+
for (const itemLine of itemLines) {
|
|
396
|
+
const match = itemLine.match(/^\s*(?:-\s+)?(?:rule|"rule"|'rule')\s*:\s*(?:"([^"]+)"|'([^']+)'|([^#\s]+))/u);
|
|
397
|
+
const ruleId = match?.[1] ?? match?.[2] ?? match?.[3];
|
|
398
|
+
if (ruleId) {
|
|
399
|
+
return ruleId.trim();
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
return undefined;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Reports whether `ruleId` is a known retired 0.5 rule that is no longer part of the 0.6.0 rule catalogue.
|
|
407
|
+
*
|
|
408
|
+
* @param ruleId - candidate rule identifier from a 0.5 configuration
|
|
409
|
+
* @returns True when `ruleId` is retired and absent from the live catalogue; false otherwise.
|
|
410
|
+
*/
|
|
411
|
+
function isRetiredRuleId(ruleId: string): boolean {
|
|
412
|
+
return RETIRED_0_5_RULE_IDS.has(ruleId) && !isKnownRuleId(ruleId);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* Migrates a JSON config: prunes retired allowlists, rules, inline profile rules and sensitive exclusions.
|
|
417
|
+
* Stable contract: the result must pass 0.6 validation before it is returned, so the user never writes a config that will not load.
|
|
418
|
+
*
|
|
419
|
+
* @param source - BOM-stripped JSON config text
|
|
420
|
+
* @param baseDirectory - optional directory used to resolve relative `profile:` references during validation
|
|
421
|
+
* @returns Migrated JSON text and change descriptions (using line 1 for whole-document rewrites).
|
|
422
|
+
* @throws {ConfigLoadError} when the input is malformed, keys conflict, or 0.6 validation rejects the result.
|
|
423
|
+
*/
|
|
424
|
+
function migrateJsonConfig(source: string, baseDirectory?: string): ConfigMigration {
|
|
425
|
+
let parsed: Record<string, unknown> | undefined;
|
|
426
|
+
try {
|
|
427
|
+
parsed = objectValue(JSON.parse(source));
|
|
428
|
+
} catch {
|
|
429
|
+
throw new ConfigLoadError("The migration input is not valid JSON.", SUGGEST_EDIT_CONFIG);
|
|
430
|
+
}
|
|
431
|
+
if (!parsed) {
|
|
432
|
+
throw new ConfigLoadError("The migration input must be a JSON object.", SUGGEST_EDIT_CONFIG);
|
|
433
|
+
}
|
|
434
|
+
const changes: ConfigMigrationChange[] = [];
|
|
435
|
+
if (hasLegacyCommandGate(parsed)) {
|
|
436
|
+
parsed.failOn = parsed.minimumSeverity;
|
|
437
|
+
delete parsed.minimumSeverity;
|
|
438
|
+
changes.push({ line: 1, description: "Renamed the per-command minimumSeverity mapping to failOn" });
|
|
439
|
+
}
|
|
440
|
+
pruneJsonAllowlists(parsed, changes);
|
|
441
|
+
pruneJsonRules(parsed, changes);
|
|
442
|
+
pruneJsonProfileRules(parsed, changes);
|
|
443
|
+
pruneJsonSensitiveExclusions(parsed, changes);
|
|
444
|
+
if (parsed.schemaVersion !== SCHEMA_VERSION) {
|
|
445
|
+
parsed.schemaVersion = SCHEMA_VERSION;
|
|
446
|
+
changes.push({ line: 1, description: `Set schemaVersion to ${SCHEMA_VERSION}` });
|
|
447
|
+
}
|
|
448
|
+
validateParsedConfig(parsed, baseDirectory);
|
|
449
|
+
return { changes, text: changes.length > 0 ? `${JSON.stringify(parsed, null, 2)}\n` : source };
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* Removes `secretPreviews` and retired 0.5 allowlist keys from a parsed JSON config object in place.
|
|
454
|
+
*
|
|
455
|
+
* @param parsed - mutable JSON config mapping
|
|
456
|
+
* @param changes - change log appended with one entry per removed allowlist key
|
|
457
|
+
* @returns Nothing. Mutates `parsed.allowlists` and `changes` in place.
|
|
458
|
+
*/
|
|
459
|
+
function pruneJsonAllowlists(parsed: Record<string, unknown>, changes: ConfigMigrationChange[]): void {
|
|
460
|
+
const allowlists = objectValue(parsed.allowlists);
|
|
461
|
+
if (!allowlists) {
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
if (Object.hasOwn(allowlists, REMOVED_ALLOWLIST_KEY)) {
|
|
465
|
+
delete allowlists[REMOVED_ALLOWLIST_KEY];
|
|
466
|
+
changes.push({ line: 1, description: `Removed allowlists.${REMOVED_ALLOWLIST_KEY}` });
|
|
467
|
+
}
|
|
468
|
+
for (const key of Object.keys(allowlists)) {
|
|
469
|
+
if (RETIRED_ALLOWLIST_KEYS.has(key)) {
|
|
470
|
+
delete allowlists[key];
|
|
471
|
+
changes.push({ line: 1, description: `Removed allowlists.${key}; only read by rules retired in 0.6.0` });
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* Removes retired 0.5 rule entries from a parsed JSON config's `rules` mapping in place.
|
|
478
|
+
*
|
|
479
|
+
* @param parsed - mutable JSON config mapping
|
|
480
|
+
* @param changes - change log appended with one entry per removed rule id
|
|
481
|
+
* @returns Nothing. Mutates `parsed.rules` and `changes` in place.
|
|
482
|
+
*/
|
|
483
|
+
function pruneJsonRules(parsed: Record<string, unknown>, changes: ConfigMigrationChange[]): void {
|
|
484
|
+
const rules = objectValue(parsed.rules);
|
|
485
|
+
if (!rules) {
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
for (const ruleId of Object.keys(rules)) {
|
|
489
|
+
if (isRetiredRuleId(ruleId)) {
|
|
490
|
+
delete rules[ruleId];
|
|
491
|
+
changes.push({ line: 1, description: `Removed rules.${ruleId}; rule retired in 0.6.0` });
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* Removes retired 0.5 rule entries from an inline JSON `profile.rules` mapping in place.
|
|
498
|
+
*
|
|
499
|
+
* @param parsed - mutable JSON config mapping
|
|
500
|
+
* @param changes - change log appended with one entry per removed profile rule id
|
|
501
|
+
* @returns Nothing. Mutates `parsed.profile.rules` and `changes` in place.
|
|
502
|
+
*/
|
|
503
|
+
function pruneJsonProfileRules(parsed: Record<string, unknown>, changes: ConfigMigrationChange[]): void {
|
|
504
|
+
const profileRules = objectValue(objectValue(parsed.profile)?.rules);
|
|
505
|
+
// A config without an inline `profile.rules` mapping has nothing to prune here.
|
|
506
|
+
if (!profileRules) {
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
// Check each rule the inline profile configures.
|
|
510
|
+
for (const ruleId of Object.keys(profileRules)) {
|
|
511
|
+
// A rule retired in 0.6.0 is removed and reported, so the migrated file loads cleanly.
|
|
512
|
+
if (isRetiredRuleId(ruleId)) {
|
|
513
|
+
delete profileRules[ruleId];
|
|
514
|
+
changes.push({ line: 1, description: `Removed profile.rules.${ruleId}; rule retired in 0.6.0` });
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/**
|
|
520
|
+
* Removes `sensitiveExclusions` items targeting retired 0.5 rules from a parsed JSON config in place.
|
|
521
|
+
*
|
|
522
|
+
* @param parsed - mutable JSON config mapping
|
|
523
|
+
* @param changes - change log appended with one entry per removed exclusion
|
|
524
|
+
* @returns Nothing. Mutates `parsed.sensitiveExclusions` and `changes` in place.
|
|
525
|
+
*/
|
|
526
|
+
function pruneJsonSensitiveExclusions(parsed: Record<string, unknown>, changes: ConfigMigrationChange[]): void {
|
|
527
|
+
if (!Array.isArray(parsed.sensitiveExclusions)) {
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
const kept: unknown[] = [];
|
|
531
|
+
for (const entry of arrayValue(parsed.sensitiveExclusions)) {
|
|
532
|
+
const record = objectValue(entry);
|
|
533
|
+
const ruleId = isString(record?.rule) ? record.rule.trim() : undefined;
|
|
534
|
+
if (ruleId && isRetiredRuleId(ruleId)) {
|
|
535
|
+
changes.push({ line: 1, description: `Removed sensitiveExclusions entry for ${ruleId}; rule retired in 0.6.0` });
|
|
536
|
+
continue;
|
|
537
|
+
}
|
|
538
|
+
kept.push(entry);
|
|
539
|
+
}
|
|
540
|
+
parsed.sensitiveExclusions = kept;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* Tells migration whether the user set per-command gates under the old minimumSeverity key.
|
|
545
|
+
*
|
|
546
|
+
* @param parsed - parsed configuration object to inspect for legacy gate settings
|
|
547
|
+
* @returns True when `minimumSeverity` defines command threshold overrides; false otherwise.
|
|
548
|
+
* @throws {ConfigLoadError} if the two gate spellings conflict.
|
|
549
|
+
*/
|
|
550
|
+
function hasLegacyCommandGate(parsed: Record<string, unknown>): boolean {
|
|
551
|
+
const hasCommandThresholds = objectValue(parsed.minimumSeverity) !== undefined;
|
|
552
|
+
// A user who started upgrading by hand needs to reconcile both gate settings before continuing.
|
|
553
|
+
if (hasCommandThresholds && "failOn" in parsed) {
|
|
554
|
+
throw new ConfigLoadError("Both minimumSeverity and failOn define command gates.", "Combine the gates under failOn before migrating.");
|
|
555
|
+
}
|
|
556
|
+
return hasCommandThresholds;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* Counts how many lines belong to an indented YAML mapping entry (its header line plus all deeper child lines).
|
|
561
|
+
*
|
|
562
|
+
* @param lines - full YAML lines array
|
|
563
|
+
* @param index - line index of the mapping entry header
|
|
564
|
+
* @returns Number of lines covered by the entry (>= 1).
|
|
565
|
+
*/
|
|
566
|
+
function indentedBlockLength(lines: string[], index: number): number {
|
|
567
|
+
const indent = leadingSpaces(lines[index] ?? "");
|
|
568
|
+
let end = index + 1;
|
|
569
|
+
for (let child = nextContentLine(lines, end); child < lines.length; child = nextContentLine(lines, end)) {
|
|
570
|
+
if (leadingSpaces(lines[child] ?? "") <= indent) {
|
|
571
|
+
break;
|
|
572
|
+
}
|
|
573
|
+
end = child + 1;
|
|
574
|
+
}
|
|
575
|
+
return end - index;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* Counts how many lines belong to one YAML sequence item starting with `- ` at `index`, stopping before the next sibling item or dedent.
|
|
580
|
+
*
|
|
581
|
+
* @param lines - full YAML lines array
|
|
582
|
+
* @param index - line index of the `- ` sequence item opener
|
|
583
|
+
* @returns Number of lines covered by the sequence item (>= 1).
|
|
584
|
+
*/
|
|
585
|
+
function yamlSequenceItemLength(lines: string[], index: number): number {
|
|
586
|
+
const indent = leadingSpaces(lines[index] ?? "");
|
|
587
|
+
let end = index + 1;
|
|
588
|
+
for (let child = nextContentLine(lines, end); child < lines.length; child = nextContentLine(lines, end)) {
|
|
589
|
+
const childLine = lines[child] ?? "";
|
|
590
|
+
const childIndent = leadingSpaces(childLine);
|
|
591
|
+
if (childIndent < indent || (childIndent === indent && /^\s*-\s*/u.test(childLine))) {
|
|
592
|
+
break;
|
|
593
|
+
}
|
|
594
|
+
end = child + 1;
|
|
595
|
+
}
|
|
596
|
+
return end - index;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* Finds the next YAML setting or value that affects which block migration may edit.
|
|
601
|
+
*
|
|
602
|
+
* @param lines - YAML file lines to scan forward through
|
|
603
|
+
* @param index - starting line index for the forward scan
|
|
604
|
+
* @returns Index of the next non-empty, non-comment line, or `lines.length` when no settings remain.
|
|
605
|
+
*/
|
|
606
|
+
function nextContentLine(lines: string[], index: number): number {
|
|
607
|
+
// Comments and blank lines can sit inside a block without changing which setting owns it.
|
|
608
|
+
while (index < lines.length) {
|
|
609
|
+
const content = (lines[index] ?? "").trim();
|
|
610
|
+
// The first non-comment line gives migration the indentation of the user's next setting.
|
|
611
|
+
if (content.length > 0 && !content.startsWith("#")) {
|
|
612
|
+
break;
|
|
613
|
+
}
|
|
614
|
+
index += 1;
|
|
615
|
+
}
|
|
616
|
+
return index;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* Counts the indentation before a YAML key or sequence item.
|
|
621
|
+
*
|
|
622
|
+
* @param line - single YAML line whose leading indentation is measured
|
|
623
|
+
* @returns Count of leading whitespace characters before the trimmed line content.
|
|
624
|
+
*/
|
|
625
|
+
function leadingSpaces(line: string): number {
|
|
626
|
+
return line.length - line.trimStart().length;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* Reads the unquoted scalar value from a root-level `schemaVersion:` YAML line so valid unquoted configs stay untouched.
|
|
631
|
+
*
|
|
632
|
+
* @param line - single root-level YAML line starting with `schemaVersion:`
|
|
633
|
+
* @returns Trimmed scalar value with optional inline comment and matching outer quotes removed.
|
|
634
|
+
*/
|
|
635
|
+
function yamlSchemaVersionValue(line: string): string {
|
|
636
|
+
const raw = line.replace(/^\s*(?:schemaVersion|"schemaVersion"|'schemaVersion')\s*:\s*/u, "").trim();
|
|
637
|
+
// Match a quoted scalar first so an inline `#` comment after the closing quote is ignored without altering quoted text.
|
|
638
|
+
const quoted = /^"([^"]*)"(?:\s+#.*)?$|^'([^']*)'(?:\s+#.*)?$/u.exec(raw);
|
|
639
|
+
if (quoted) {
|
|
640
|
+
return quoted[1] ?? quoted[2] ?? "";
|
|
641
|
+
}
|
|
642
|
+
return raw.replace(/\s+#.*$/u, "").trim();
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/**
|
|
646
|
+
* Pin the schema version, inserting it at the top when the 0.5 file never named one.
|
|
647
|
+
* Leaves already-current unquoted or quoted `schemaVersion: gruff-ts.config.v0.1` lines unchanged so `migrate-config --dry-run` is idempotent.
|
|
648
|
+
*
|
|
649
|
+
* @param lines - migrated lines, mutated in place to insert or replace schemaVersion
|
|
650
|
+
* @param changes - the rewrite log, appended to when schemaVersion is inserted or its existing value differs from 0.6
|
|
651
|
+
* @param original - the file as written, returned unchanged when nothing needed rewriting
|
|
652
|
+
* @param rootIndent - column where root mapping keys begin
|
|
653
|
+
* @returns text and the same changes array; text is original when no rewrites were recorded
|
|
654
|
+
*/
|
|
655
|
+
function withSchemaVersion(lines: string[], changes: ConfigMigrationChange[], original: string, rootIndent: number): ConfigMigration {
|
|
656
|
+
const existing = lines.findIndex((line) => leadingSpaces(line) === rootIndent && /^\s*(?:schemaVersion|"schemaVersion"|'schemaVersion')\s*:/u.test(line));
|
|
657
|
+
const pinned = `${" ".repeat(rootIndent)}schemaVersion: "${SCHEMA_VERSION}"`;
|
|
658
|
+
|
|
659
|
+
// Older projects may have no schema key. Add one without requiring the user to format it by hand.
|
|
660
|
+
if (existing < 0) {
|
|
661
|
+
changes.push({ line: 1, description: `schemaVersion added as ${SCHEMA_VERSION}; every 0.6 loader requires it` });
|
|
662
|
+
lines.unshift(pinned);
|
|
663
|
+
// Only rewrite an existing schema line when its value differs from the current 0.6 schema version.
|
|
664
|
+
} else if (yamlSchemaVersionValue(lines[existing] ?? "") !== SCHEMA_VERSION) {
|
|
665
|
+
changes.push({ line: existing + 1, description: `schemaVersion pinned to ${SCHEMA_VERSION}` });
|
|
666
|
+
lines[existing] = pinned;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
return changes.length === 0 ? { text: original, changes } : { text: lines.join(original.includes("\r\n") ? "\r\n" : "\n"), changes };
|
|
670
|
+
}
|