@blundergoat/gruff-ts 0.1.1 → 0.3.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 +55 -19
- package/README.md +103 -35
- package/docs/README.md +2 -0
- package/docs/agent-hook.md +80 -0
- package/docs/ci-integration.md +16 -0
- package/docs/configuration.md +60 -3
- package/docs/dashboard.md +7 -0
- package/docs/output-formats.md +11 -1
- package/docs/philosophy.md +21 -0
- package/docs/releasing.md +12 -11
- package/docs/reports-and-ci.md +5 -2
- package/docs/rules.md +24 -15
- package/package.json +5 -5
- package/scripts/bump-version.sh +20 -4
- package/scripts/preflight-checks.sh +4 -41
- package/src/analyser.ts +47 -34
- package/src/blocks.ts +82 -75
- package/src/changed-regions.ts +390 -0
- package/src/check-ignore.ts +49 -0
- package/src/class-rules.ts +80 -33
- package/src/cli-program.ts +209 -51
- package/src/comment-rules.ts +4 -0
- package/src/config-load-error.ts +18 -0
- package/src/config-parse.ts +458 -0
- package/src/config-preservation.ts +64 -0
- package/src/config.ts +311 -428
- package/src/constants.ts +10 -2
- package/src/context-doc-rules.ts +2 -4
- package/src/dashboard.ts +8 -5
- package/src/dead-code-rules.ts +60 -14
- package/src/discovery.ts +88 -32
- package/src/doc-rules.ts +3 -3
- package/src/findings-helpers.ts +58 -5
- package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
- package/src/init-config.ts +94 -31
- package/src/line-rules.ts +58 -4
- package/src/naming-pushers.ts +42 -7
- package/src/pillar-summary.ts +129 -0
- package/src/profiles.ts +232 -0
- package/src/project-config-rules.ts +5 -5
- package/src/project-rules.ts +2 -1
- package/src/report-html.ts +404 -0
- package/src/report-renderers.ts +210 -397
- package/src/rule-list.ts +85 -1
- package/src/rules.ts +28 -27
- package/src/safety-rules.ts +22 -7
- package/src/scoring.ts +78 -8
- package/src/security-flow-rules.ts +533 -0
- package/src/sensitive-data-rules.ts +138 -2
- package/src/test-block-rules.ts +140 -7
- package/src/test-fixtures.ts +59 -13
- package/src/types.ts +108 -5
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// `check-ignore` command core: classify each path through the shared discovery ignore engine and
|
|
2
|
+
// render the verdict. No analysis is performed - this is an O(1)-per-path config/gitignore/default
|
|
3
|
+
// lookup that mirrors `git check-ignore` exit semantics, so a coding-agent hook can ask "will gruff
|
|
4
|
+
// skip this changed file?" before running a scan. Single source of truth: `classifyPathIgnore` is the
|
|
5
|
+
// exact engine `analyse` discovery uses; this module only loads config and formats the output.
|
|
6
|
+
import { cwd } from "node:process";
|
|
7
|
+
import { loadConfig } from "./config.ts";
|
|
8
|
+
import { classifyPathIgnore, type PathIgnoreClassification } from "./discovery.ts";
|
|
9
|
+
import type { AnalysisOptions } from "./types.ts";
|
|
10
|
+
|
|
11
|
+
/** Output encodings supported by the `check-ignore` command. */
|
|
12
|
+
export type CheckIgnoreFormat = "text" | "json";
|
|
13
|
+
|
|
14
|
+
// Resolves config exactly as `analyse` does (`--config` / `--no-config`), then classifies each input
|
|
15
|
+
// path. Config `paths.ignore` is authoritative; default and gitignore matches are reported with their
|
|
16
|
+
// source too so the caller sees why a path would be skipped.
|
|
17
|
+
export function checkIgnore(inputs: string[], options: AnalysisOptions): PathIgnoreClassification[] {
|
|
18
|
+
const projectRoot = cwd();
|
|
19
|
+
const config = loadConfig(projectRoot, options);
|
|
20
|
+
return inputs.map((input) => classifyPathIgnore(projectRoot, input, options, config));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Mirrors `git check-ignore`: exit 0 when at least one path is ignored, 1 when none are. Exit 2 is
|
|
24
|
+
// reserved for config/usage errors and is set by the CLI layer via `runWithConfigErrorHandling`.
|
|
25
|
+
export function checkIgnoreExitCode(results: PathIgnoreClassification[]): number {
|
|
26
|
+
return results.some((result) => result.isIgnored) ? 0 : 1;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// JSON is the agent-facing contract: every input path as `{ path, ignored, source, pattern }`, with
|
|
30
|
+
// `source`/`pattern` null when the path is not ignored. Text lists only the ignored paths as
|
|
31
|
+
// `<path>\t<source>:<pattern>`, matching `git check-ignore`'s "print the matches" behaviour.
|
|
32
|
+
export function renderCheckIgnore(results: PathIgnoreClassification[], format: CheckIgnoreFormat): string {
|
|
33
|
+
if (format === "json") {
|
|
34
|
+
return JSON.stringify(
|
|
35
|
+
results.map((result) => ({
|
|
36
|
+
path: result.path,
|
|
37
|
+
ignored: result.isIgnored,
|
|
38
|
+
source: result.source ?? null,
|
|
39
|
+
pattern: result.pattern ?? null,
|
|
40
|
+
})),
|
|
41
|
+
null,
|
|
42
|
+
2,
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
return results
|
|
46
|
+
.filter((result) => result.isIgnored)
|
|
47
|
+
.map((result) => `${result.path}\t${result.source}:${result.pattern}`)
|
|
48
|
+
.join("\n");
|
|
49
|
+
}
|
package/src/class-rules.ts
CHANGED
|
@@ -7,7 +7,7 @@ import { type ExportedDeclaration, exportedDeclarations, pushMissingPublicDocFin
|
|
|
7
7
|
import { type SourceFile } from "./discovery.ts";
|
|
8
8
|
import { makeFinding } from "./findings.ts";
|
|
9
9
|
import { fileBaseName, finding, normalizedIdentifier } from "./findings-helpers.ts";
|
|
10
|
-
import { pushBooleanPrefixAt, pushNegativeBooleanAt } from "./naming-pushers.ts";
|
|
10
|
+
import { pushBooleanPrefixAt, pushNegativeBooleanAt, type NamingSurface } from "./naming-pushers.ts";
|
|
11
11
|
import { byteLine } from "./text-scans.ts";
|
|
12
12
|
import type { Config, Finding } from "./types.ts";
|
|
13
13
|
|
|
@@ -16,6 +16,7 @@ import type { Config, Finding } from "./types.ts";
|
|
|
16
16
|
interface DeclaredIdentifier {
|
|
17
17
|
name: string;
|
|
18
18
|
line: number;
|
|
19
|
+
surface: NamingSurface;
|
|
19
20
|
}
|
|
20
21
|
|
|
21
22
|
// Aggregates `const`/`let`/`var` declarations, callable parameters, and interface fields into a
|
|
@@ -23,24 +24,24 @@ interface DeclaredIdentifier {
|
|
|
23
24
|
export function collectDeclaredIdentifiers(source: string, codeSource: string, blocks: FunctionBlock[]): DeclaredIdentifier[] {
|
|
24
25
|
const inventory: DeclaredIdentifier[] = [];
|
|
25
26
|
const seen = new Set<string>();
|
|
26
|
-
const push = (name: string, line: number): void => {
|
|
27
|
+
const push = (name: string, line: number, surface: NamingSurface): void => {
|
|
27
28
|
if (!name) return;
|
|
28
|
-
const key = `${name}@${line}`;
|
|
29
|
+
const key = `${name}@${line}@${surface}`;
|
|
29
30
|
if (seen.has(key)) return;
|
|
30
31
|
seen.add(key);
|
|
31
|
-
inventory.push({ name, line });
|
|
32
|
+
inventory.push({ name, line, surface });
|
|
32
33
|
};
|
|
33
34
|
|
|
34
35
|
for (const match of codeSource.matchAll(/\b(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g)) {
|
|
35
|
-
push(match[1] ?? "", byteLine(source, match.index ?? 0));
|
|
36
|
+
push(match[1] ?? "", byteLine(source, match.index ?? 0), "declaration");
|
|
36
37
|
}
|
|
37
38
|
for (const block of blocks) {
|
|
38
39
|
for (const parameter of parameterNames(block.params)) {
|
|
39
|
-
push(parameter.name, block.declarationLine);
|
|
40
|
+
push(parameter.name, block.declarationLine, "parameter");
|
|
40
41
|
}
|
|
41
42
|
}
|
|
42
43
|
for (const fieldMatch of collectInterfaceFieldDeclarations(source, codeSource)) {
|
|
43
|
-
push(fieldMatch.name, fieldMatch.line);
|
|
44
|
+
push(fieldMatch.name, fieldMatch.line, "interface-field");
|
|
44
45
|
}
|
|
45
46
|
return inventory;
|
|
46
47
|
}
|
|
@@ -52,23 +53,36 @@ function collectInterfaceFieldDeclarations(source: string, codeSource: string):
|
|
|
52
53
|
const out: DeclaredIdentifier[] = [];
|
|
53
54
|
for (const { lineIndex, sourceLine } of walkInterfaceBodyLines(source, codeSource)) {
|
|
54
55
|
const name = sourceLine.match(fieldRegex)?.[1] ?? "";
|
|
55
|
-
if (name) out.push({ name, line: lineIndex + 1 });
|
|
56
|
+
if (name) out.push({ name, line: lineIndex + 1, surface: "interface-field" });
|
|
56
57
|
}
|
|
57
58
|
return out;
|
|
58
59
|
}
|
|
59
60
|
|
|
60
|
-
// Strips separators
|
|
61
|
+
// Strips separators only so `userId`, `user_id`, and `userID` collapse, while `adr013` and
|
|
62
|
+
// `adr020` remain distinct domain tokens instead of fake casing variants.
|
|
61
63
|
// Two names sharing this key but differing in original form are the casing-drift signal.
|
|
62
64
|
function casingCanonicalKey(name: string): string {
|
|
63
|
-
return name.toLowerCase().replace(/[_\-
|
|
65
|
+
return name.toLowerCase().replace(/[_\-]/g, "");
|
|
64
66
|
}
|
|
65
67
|
|
|
66
68
|
/*
|
|
67
|
-
* Groups identifiers by
|
|
68
|
-
*
|
|
69
|
-
*
|
|
69
|
+
* Groups identifiers by canonical key, then filters out boundary surfaces before reporting. The
|
|
70
|
+
* split helper flow is intentional: the rule must preserve same-scope drift signal while refusing
|
|
71
|
+
* to command rewrites of constants, DTO fields, or intentionally-unused `_` names. Error behavior:
|
|
72
|
+
* never throws; it reports drift by appending findings only.
|
|
70
73
|
*/
|
|
71
74
|
export function analyseInconsistentCasing(file: SourceFile, inventory: DeclaredIdentifier[], findings: Finding[]): void {
|
|
75
|
+
for (const entries of declaredIdentifierGroups(inventory).values()) {
|
|
76
|
+
const candidate = inconsistentCasingCandidate(entries);
|
|
77
|
+
if (!candidate) {
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
findings.push(inconsistentCasingFinding(file, candidate));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Builds canonical-key groups once so the reporting pass can stay focused on rule semantics.
|
|
85
|
+
function declaredIdentifierGroups(inventory: DeclaredIdentifier[]): Map<string, DeclaredIdentifier[]> {
|
|
72
86
|
const groups = new Map<string, DeclaredIdentifier[]>();
|
|
73
87
|
for (const entry of inventory) {
|
|
74
88
|
const key = casingCanonicalKey(entry.name);
|
|
@@ -77,27 +91,60 @@ export function analyseInconsistentCasing(file: SourceFile, inventory: DeclaredI
|
|
|
77
91
|
list.push(entry);
|
|
78
92
|
groups.set(key, list);
|
|
79
93
|
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
filePath: file.displayPath,
|
|
91
|
-
line: second.line,
|
|
92
|
-
severity: "advisory",
|
|
93
|
-
pillar: "naming",
|
|
94
|
-
confidence: "medium",
|
|
95
|
-
symbol: second.name,
|
|
96
|
-
remediation: "Choose one form and use it consistently within the file.",
|
|
97
|
-
metadata: { variants: [...surfaces].sort() },
|
|
98
|
-
}),
|
|
99
|
-
);
|
|
94
|
+
return groups;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Invariant: returns the exact variant pair to report after boundary-aware suppression has run.
|
|
98
|
+
function inconsistentCasingCandidate(entries: DeclaredIdentifier[]): { first: DeclaredIdentifier; second: DeclaredIdentifier; surfaces: string[] } | undefined {
|
|
99
|
+
const reportableEntries = casingReportableEntries(entries);
|
|
100
|
+
const sameSurfaceEntries = sameCasingSurfaceEntries(reportableEntries);
|
|
101
|
+
const surfaces = [...new Set(sameSurfaceEntries.map((entry) => entry.name))].sort();
|
|
102
|
+
if (surfaces.length < 2) {
|
|
103
|
+
return undefined;
|
|
100
104
|
}
|
|
105
|
+
const sorted = [...sameSurfaceEntries].sort((a, b) => a.line - b.line);
|
|
106
|
+
const first = sorted[0];
|
|
107
|
+
const second = sorted.find((entry, index) => index > 0 && entry.name !== first?.name);
|
|
108
|
+
return first && second ? { first, second, surfaces } : undefined;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Builds the stable finding after candidate selection so fingerprint shape stays in one place.
|
|
112
|
+
function inconsistentCasingFinding(file: SourceFile, candidate: { first: DeclaredIdentifier; second: DeclaredIdentifier; surfaces: string[] }): Finding {
|
|
113
|
+
return makeFinding({
|
|
114
|
+
ruleId: "naming.inconsistent-casing",
|
|
115
|
+
message: `Identifier \`${candidate.second.name}\` shares a canonical key with \`${candidate.first.name}\` in the same file.`,
|
|
116
|
+
filePath: file.displayPath,
|
|
117
|
+
line: candidate.second.line,
|
|
118
|
+
severity: "advisory",
|
|
119
|
+
pillar: "naming",
|
|
120
|
+
confidence: "medium",
|
|
121
|
+
symbol: candidate.second.name,
|
|
122
|
+
remediation: "Choose one form and use it consistently within the file.",
|
|
123
|
+
metadata: { variants: candidate.surfaces },
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// `_event` is the standard intentionally-unused spelling; comparing it with `event` would tell an
|
|
128
|
+
// agent to remove useful boundary information rather than fix casing drift.
|
|
129
|
+
function casingReportableEntries(entries: DeclaredIdentifier[]): DeclaredIdentifier[] {
|
|
130
|
+
return entries.filter((entry) => !entry.name.startsWith("_"));
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Contract fields and SCREAMING_SNAKE constants are boundary surfaces; remove only those entries so
|
|
134
|
+
// they do not mask real local drift elsewhere in the same canonical group.
|
|
135
|
+
function sameCasingSurfaceEntries(entries: DeclaredIdentifier[]): DeclaredIdentifier[] {
|
|
136
|
+
const hasLocalSurface = entries.some((entry) => entry.surface !== "interface-field" && !isScreamingConstant(entry.name));
|
|
137
|
+
return entries.filter((entry) => {
|
|
138
|
+
if (hasLocalSurface && entry.surface === "interface-field") {
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
return !(hasLocalSurface && isScreamingConstant(entry.name));
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Recognises constant-style identifiers without stripping digits, so `V110` remains one token.
|
|
146
|
+
function isScreamingConstant(name: string): boolean {
|
|
147
|
+
return /^[A-Z][A-Z0-9_]*$/.test(name) && /[A-Z]/.test(name);
|
|
101
148
|
}
|
|
102
149
|
|
|
103
150
|
// Splits camelCase, PascalCase, snake_case, and kebab-case into tokens. The regex preserves
|
package/src/cli-program.ts
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
// Commander CLI shell wiring that keeps option normalization and stdout behavior outside the analyzer.
|
|
2
2
|
import { Command, Help, InvalidArgumentError } from "commander";
|
|
3
|
-
import { writeFileSync } from "node:fs";
|
|
3
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { resolve } from "node:path";
|
|
5
5
|
import { performance } from "node:perf_hooks";
|
|
6
|
+
import { cwd } from "node:process";
|
|
6
7
|
import { DEFAULT_BASELINE } from "./baseline.ts";
|
|
8
|
+
import { checkIgnore, checkIgnoreExitCode, renderCheckIgnore, type CheckIgnoreFormat } from "./check-ignore.ts";
|
|
9
|
+
import { ConfigLoadError } from "./config-load-error.ts";
|
|
10
|
+
import { loadConfig, minimumSeverityFor } from "./config.ts";
|
|
7
11
|
import { VERSION } from "./constants.ts";
|
|
8
12
|
import { startDashboard } from "./dashboard.ts";
|
|
9
13
|
import { promptYesNo, shouldPromptForInit, writeDefaultConfig } from "./init-config.ts";
|
|
10
14
|
import { renderReport, renderSummary, renderSummaryJson } from "./report-renderers.ts";
|
|
11
|
-
import { completionShell, renderCompletionScript, renderConsoleList, renderRuleList, type RuleListFormat } from "./rule-list.ts";
|
|
15
|
+
import { completionShell, getRuleDescriptor, renderCompletionScript, renderConsoleList, renderProfileList, renderRuleDetail, renderRuleList, type RuleListFormat } from "./rule-list.ts";
|
|
12
16
|
import { exitFor } from "./scoring.ts";
|
|
13
|
-
import type { AnalysisOptions, AnalysisReport } from "./types.ts";
|
|
17
|
+
import type { AnalysisOptions, AnalysisReport, MinimumSeverityCommand } from "./types.ts";
|
|
14
18
|
|
|
15
19
|
type AnalyseRunner = (options: AnalysisOptions) => AnalysisReport;
|
|
16
20
|
|
|
@@ -20,6 +24,10 @@ interface NormalizeContext {
|
|
|
20
24
|
shouldAllowBaselineFlag: boolean;
|
|
21
25
|
}
|
|
22
26
|
|
|
27
|
+
// Shared `--profile` flag help for analyse/report/summary/dashboard. The value is a built-in profile
|
|
28
|
+
// name or a profile file path; it overrides any config-file `profile:` block (CLI wins, per ADR-010).
|
|
29
|
+
const PROFILE_OPTION_DESCRIPTION = "Apply a built-in profile (gruff.minimal, gruff.recommended, gruff.strict) or a profile file path. Overrides a config-file profile:.";
|
|
30
|
+
|
|
23
31
|
// Honours `--silent`/`--quiet` before writing to stdout. Always appends a trailing newline so piped
|
|
24
32
|
// callers (e.g., `gruff-ts analyse | jq`) see a complete line even when a renderer forgot one.
|
|
25
33
|
function writeCommandOutput(program: Command, output: string): void {
|
|
@@ -98,10 +106,12 @@ export function buildProgram(runAnalyse: AnalyseRunner): Command {
|
|
|
98
106
|
const program = new Command();
|
|
99
107
|
configureRootProgram(program);
|
|
100
108
|
registerAnalyseCommand(program, runAnalyse);
|
|
109
|
+
registerCheckIgnoreCommand(program);
|
|
101
110
|
registerCompletionCommand(program);
|
|
102
111
|
registerDashboardCommand(program, runAnalyse);
|
|
103
112
|
registerInitCommand(program);
|
|
104
113
|
registerListCommand(program);
|
|
114
|
+
registerListProfilesCommand(program);
|
|
105
115
|
registerListRulesCommand(program);
|
|
106
116
|
registerReportCommand(program, runAnalyse);
|
|
107
117
|
registerSummaryCommand(program, runAnalyse);
|
|
@@ -156,7 +166,10 @@ function rootHelpText(program: Command, command: Command, helper: Help): string
|
|
|
156
166
|
}
|
|
157
167
|
|
|
158
168
|
// The primary entry point. Sets `process.exitCode` (not `process.exit`) so async writers in the
|
|
159
|
-
// renderer get a chance to flush before Node tears down.
|
|
169
|
+
// renderer get a chance to flush before Node tears down. The default fail-on is `advisory` because
|
|
170
|
+
// the project's gating philosophy is "show everything, fail on anything"; CI flows that want the
|
|
171
|
+
// old `error`-only behaviour pass `--fail-on=error` explicitly or pin `minimumSeverity.analyse:
|
|
172
|
+
// error` in `.gruff-ts.yaml`. See ADR-004.
|
|
160
173
|
function registerAnalyseCommand(program: Command, runAnalyse: AnalyseRunner): void {
|
|
161
174
|
program
|
|
162
175
|
.command("analyse")
|
|
@@ -164,23 +177,69 @@ function registerAnalyseCommand(program: Command, runAnalyse: AnalyseRunner): vo
|
|
|
164
177
|
.argument("[paths...]", "Files or directories to analyse.")
|
|
165
178
|
.option("--config <path>", "Path to a gruff YAML config file.")
|
|
166
179
|
.option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
|
|
180
|
+
.option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
|
|
167
181
|
.option("--format <format>", "Output format: text, json, html, markdown, github, hotspot, or sarif.", "text")
|
|
168
|
-
.option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", "
|
|
182
|
+
.option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", "advisory")
|
|
169
183
|
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
170
|
-
.option("--
|
|
184
|
+
.option("--changed-ranges <ranges>", "Filter findings to changed regions, for example 3-3,8-10.")
|
|
185
|
+
.option("--since <ref>", "Filter findings to regions changed against a git base ref.")
|
|
186
|
+
.option("--diff [mode]", "Filter findings to changed regions. Use working-tree, staged, unstaged, a base ref, or - for unified diff on stdin.")
|
|
187
|
+
.option("--changed-scope <scope>", "Changed-region scope: symbol or hunk.", "symbol")
|
|
171
188
|
.option("--history-file <path>", "Append score trend history to this JSON file.")
|
|
172
189
|
.option("--baseline [path]", "Suppress findings that match a gruff baseline JSON file.")
|
|
173
190
|
.option("--generate-baseline [path]", "Write current findings to a gruff baseline JSON file.")
|
|
174
191
|
.option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
|
|
192
|
+
.action(async (paths: string[], rawOptions: Record<string, unknown>, command: Command) => {
|
|
193
|
+
await runWithConfigErrorHandling(async () => {
|
|
194
|
+
const baseOptions = normalizeOptions(paths, rawOptions, { shouldAllowBaselineFlag: true });
|
|
195
|
+
const options = applyMinimumSeverityPrecedence(baseOptions, "analyse", command);
|
|
196
|
+
await maybePromptInitConfig(program, process.cwd(), promptOptionsFromAnalysis(options));
|
|
197
|
+
const report = runAnalyse(options);
|
|
198
|
+
writeCommandOutput(program, renderReport(report, options.format));
|
|
199
|
+
process.exitCode = exitFor(report, options.failOn);
|
|
200
|
+
});
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// Reports whether gruff would exclude each path from analysis, with the matching ignore source and
|
|
205
|
+
// pattern, using the exact engine `analyse` uses (no second glob implementation) and performing no
|
|
206
|
+
// analysis. Built for coding-agent hooks: gate the changed-file list before scanning. Exit codes
|
|
207
|
+
// mirror `git check-ignore` (0 = at least one ignored, 1 = none); a config error surfaces as 2 via
|
|
208
|
+
// `runWithConfigErrorHandling`.
|
|
209
|
+
function registerCheckIgnoreCommand(program: Command): void {
|
|
210
|
+
program
|
|
211
|
+
.command("check-ignore")
|
|
212
|
+
.description("Report whether gruff would ignore each path (config, gitignore, or default), with the matching source and pattern. Runs no analysis.")
|
|
213
|
+
.argument("<paths...>", "Paths to check against the ignore rules.")
|
|
214
|
+
.option("--config <path>", "Path to a gruff YAML config file.")
|
|
215
|
+
.option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
|
|
216
|
+
.option("--format <format>", "Output format: text or json.", parseSummaryFormat, "text")
|
|
175
217
|
.action(async (paths: string[], rawOptions: Record<string, unknown>) => {
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
218
|
+
await runWithConfigErrorHandling(() => {
|
|
219
|
+
const results = checkIgnore(paths, checkIgnoreOptions(paths, rawOptions));
|
|
220
|
+
const format: CheckIgnoreFormat = rawOptions.format === "json" ? "json" : "text";
|
|
221
|
+
writeCommandOutput(program, renderCheckIgnore(results, format));
|
|
222
|
+
process.exitCode = checkIgnoreExitCode(results);
|
|
223
|
+
});
|
|
181
224
|
});
|
|
182
225
|
}
|
|
183
226
|
|
|
227
|
+
// Minimal AnalysisOptions for `check-ignore`: only the fields `loadConfig` and the ignore engine
|
|
228
|
+
// read. `--config` / `--no-config` resolve identically to `analyse`; `shouldIncludeIgnored` is false
|
|
229
|
+
// so default and gitignore matches are reported (config `paths.ignore` is reported regardless).
|
|
230
|
+
function checkIgnoreOptions(paths: string[], rawOptions: Record<string, unknown>): AnalysisOptions {
|
|
231
|
+
return {
|
|
232
|
+
paths,
|
|
233
|
+
...configOption(rawOptions),
|
|
234
|
+
shouldSkipConfig: rawOptions.config === false || rawOptions.noConfig === true,
|
|
235
|
+
format: "json",
|
|
236
|
+
failOn: "none",
|
|
237
|
+
shouldIncludeIgnored: false,
|
|
238
|
+
changedScope: "symbol",
|
|
239
|
+
shouldSkipBaseline: true,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
184
243
|
// Emits the static completion script for the requested shell. Does not touch the filesystem or
|
|
185
244
|
// run a scan - callers pipe the output into their shell config themselves.
|
|
186
245
|
function registerCompletionCommand(program: Command): void {
|
|
@@ -202,10 +261,12 @@ function registerDashboardCommand(program: Command, runAnalyse: AnalyseRunner):
|
|
|
202
261
|
.option("--host <host>", "Host to bind.", "127.0.0.1")
|
|
203
262
|
.option("--port <port>", "Port to bind.", "8767")
|
|
204
263
|
.option("--project-root <path>", "Default project root.", ".")
|
|
264
|
+
.option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
|
|
205
265
|
.action(async (rawOptions: Record<string, unknown>) => {
|
|
206
266
|
const projectRoot = resolve(String(rawOptions.projectRoot ?? "."));
|
|
207
267
|
await maybePromptInitConfig(program, projectRoot, { shouldSkipConfig: false, hasExplicitConfig: false });
|
|
208
|
-
|
|
268
|
+
const profile = typeof rawOptions.profile === "string" ? rawOptions.profile : undefined;
|
|
269
|
+
startDashboard(String(rawOptions.host ?? "127.0.0.1"), Number(rawOptions.port ?? 8767), projectRoot, runAnalyse, !outputSuppressed(program), profile);
|
|
209
270
|
});
|
|
210
271
|
}
|
|
211
272
|
|
|
@@ -237,7 +298,7 @@ function initSuccessMessage(verb: "Wrote" | "Overwrote", configPath: string): st
|
|
|
237
298
|
"Next: generate an adoption baseline with:",
|
|
238
299
|
" gruff-ts analyse . --generate-baseline gruff-baseline.json --fail-on=none",
|
|
239
300
|
"Then gate new findings with:",
|
|
240
|
-
" gruff-ts analyse . --baseline gruff-baseline.json --fail-on=
|
|
301
|
+
" gruff-ts analyse . --baseline gruff-baseline.json --fail-on=advisory",
|
|
241
302
|
].join("\n");
|
|
242
303
|
}
|
|
243
304
|
|
|
@@ -252,16 +313,42 @@ function registerListCommand(program: Command): void {
|
|
|
252
313
|
});
|
|
253
314
|
}
|
|
254
315
|
|
|
316
|
+
// Read-only profile catalogue dump mirroring `list-rules`: text for humans, JSON for docs and audits.
|
|
317
|
+
// `--format` is validated by `parseSummaryFormat`, so an unsupported value fails fast as a usage error
|
|
318
|
+
// instead of silently coercing - the half-and-half coercion trap documented in footguns/schema-and-cli.md.
|
|
319
|
+
function registerListProfilesCommand(program: Command): void {
|
|
320
|
+
program
|
|
321
|
+
.command("list-profiles")
|
|
322
|
+
.description("List the built-in gruff profiles with their rule-count summary.")
|
|
323
|
+
.option("--format <format>", "Output format: text or json.", parseSummaryFormat, "text")
|
|
324
|
+
.action((rawOptions: Record<string, unknown>) => {
|
|
325
|
+
const format: RuleListFormat = rawOptions.format === "json" ? "json" : "text";
|
|
326
|
+
writeCommandOutput(program, renderProfileList(format));
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
|
|
255
330
|
// Read-only catalogue dump. JSON is the canonical form consumed by docs builds; text is for humans.
|
|
256
331
|
// `--format` is validated by `parseSummaryFormat`; unsupported values fail fast as a usage error.
|
|
332
|
+
// Optional `<ruleId>` positional switches to single-rule detail mode (M08): no-arg behaviour stays
|
|
333
|
+
// byte-identical to the prior version.
|
|
257
334
|
function registerListRulesCommand(program: Command): void {
|
|
258
335
|
program
|
|
259
336
|
.command("list-rules")
|
|
260
|
-
.description("List gruff rule metadata.")
|
|
337
|
+
.description("List gruff rule metadata. Pass a rule id to print details for one rule.")
|
|
338
|
+
.argument("[ruleId]", "Optional rule id to print details for.")
|
|
261
339
|
.option("--format <format>", "Output format: text or json.", parseSummaryFormat, "text")
|
|
262
|
-
.action((rawOptions: Record<string, unknown>) => {
|
|
340
|
+
.action((ruleId: string | undefined, rawOptions: Record<string, unknown>) => {
|
|
263
341
|
const format: RuleListFormat = rawOptions.format === "json" ? "json" : "text";
|
|
264
|
-
|
|
342
|
+
if (ruleId === undefined) {
|
|
343
|
+
writeCommandOutput(program, renderRuleList(format));
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
const descriptor = getRuleDescriptor(ruleId);
|
|
347
|
+
if (!descriptor) {
|
|
348
|
+
program.error(`unknown rule "${ruleId}". Run \`gruff-ts list-rules\` to see all rules.`, { exitCode: 2 });
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
writeCommandOutput(program, renderRuleDetail(descriptor, format));
|
|
265
352
|
});
|
|
266
353
|
}
|
|
267
354
|
|
|
@@ -277,21 +364,25 @@ function registerReportCommand(program: Command, runAnalyse: AnalyseRunner): voi
|
|
|
277
364
|
.option("--output <path>", "Write report to a file.")
|
|
278
365
|
.option("--config <path>", "Path to a gruff YAML config file.")
|
|
279
366
|
.option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
|
|
367
|
+
.option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
|
|
280
368
|
.option("--fail-on <severity>", "Finding severity that fails the run.", "none")
|
|
281
369
|
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
282
370
|
.option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
|
|
283
|
-
.action(async (paths: string[], rawOptions: Record<string, unknown
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
371
|
+
.action(async (paths: string[], rawOptions: Record<string, unknown>, command: Command) => {
|
|
372
|
+
await runWithConfigErrorHandling(async () => {
|
|
373
|
+
const format = rawOptions.format === "json" ? "json" : "html";
|
|
374
|
+
const baseOptions = normalizeOptions(paths, { ...rawOptions, format }, { shouldAllowBaselineFlag: false });
|
|
375
|
+
const options = applyMinimumSeverityPrecedence(baseOptions, "report", command);
|
|
376
|
+
await maybePromptInitConfig(program, process.cwd(), promptOptionsFromAnalysis(options));
|
|
377
|
+
const report = runAnalyse(options);
|
|
378
|
+
const rendered = renderReport(report, format);
|
|
379
|
+
if (typeof rawOptions.output === "string") {
|
|
380
|
+
writeFileSync(rawOptions.output, rendered);
|
|
381
|
+
} else {
|
|
382
|
+
writeCommandOutput(program, rendered);
|
|
383
|
+
}
|
|
384
|
+
process.exitCode = exitFor(report, options.failOn);
|
|
385
|
+
});
|
|
295
386
|
});
|
|
296
387
|
}
|
|
297
388
|
|
|
@@ -305,29 +396,33 @@ function registerSummaryCommand(program: Command, runAnalyse: AnalyseRunner): vo
|
|
|
305
396
|
.argument("[paths...]", "Files or directories to analyse.")
|
|
306
397
|
.option("--config <path>", "Path to a gruff YAML config file.")
|
|
307
398
|
.option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
|
|
399
|
+
.option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
|
|
308
400
|
.option("--format <format>", "Output format: text or json.", parseSummaryFormat, "text")
|
|
309
401
|
.option("--top <n>", "How many top rules and file offenders to list.", parseNonNegativeInteger, 10)
|
|
310
|
-
.option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", "
|
|
402
|
+
.option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", "advisory")
|
|
311
403
|
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
312
404
|
.option("--diff [mode]", "Filter findings to changed files. Use working-tree, staged, unstaged, or a base ref.")
|
|
313
405
|
.option("--history-file <path>", "Append score trend history to this JSON file.")
|
|
314
406
|
.option("--baseline [path]", "Suppress findings that match a gruff baseline JSON file.")
|
|
315
407
|
.option("--generate-baseline [path]", "Write current findings to a gruff baseline JSON file.")
|
|
316
408
|
.option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
|
|
317
|
-
.action(async (paths: string[], rawOptions: Record<string, unknown
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
409
|
+
.action(async (paths: string[], rawOptions: Record<string, unknown>, command: Command) => {
|
|
410
|
+
await runWithConfigErrorHandling(async () => {
|
|
411
|
+
const baseOptions = normalizeOptions(paths, { ...rawOptions, format: "text" }, { shouldAllowBaselineFlag: true });
|
|
412
|
+
const options = applyMinimumSeverityPrecedence(baseOptions, "summary", command);
|
|
413
|
+
const summaryFormat = rawOptions.format === "json" ? "json" : "text";
|
|
414
|
+
const top = typeof rawOptions.top === "number" ? rawOptions.top : 10;
|
|
415
|
+
await maybePromptInitConfig(program, process.cwd(), promptOptionsFromAnalysis(options));
|
|
416
|
+
const startedAt = performance.now();
|
|
417
|
+
const report = runAnalyse(options);
|
|
418
|
+
const elapsedMs = performance.now() - startedAt;
|
|
419
|
+
const pathLabel = summaryPathLabel(options.paths, report.run.projectRoot);
|
|
420
|
+
const rendered = summaryFormat === "json"
|
|
421
|
+
? renderSummaryJson(report, elapsedMs, pathLabel, top)
|
|
422
|
+
: renderSummary(report, elapsedMs, pathLabel, top);
|
|
423
|
+
writeCommandOutput(program, rendered);
|
|
424
|
+
process.exitCode = exitFor(report, options.failOn);
|
|
425
|
+
});
|
|
331
426
|
});
|
|
332
427
|
}
|
|
333
428
|
|
|
@@ -369,22 +464,27 @@ function summaryPathLabel(paths: string[], projectRoot: string): string {
|
|
|
369
464
|
// adding new fields here without folding them into that hash is a deterministic-output regression.
|
|
370
465
|
function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>, context: NormalizeContext): AnalysisOptions {
|
|
371
466
|
const format = stringChoice(rawOptions.format, ["text", "json", "html", "markdown", "github", "hotspot", "sarif"], "text");
|
|
372
|
-
const failOn = stringChoice(rawOptions.failOn, ["none", "advisory", "warning", "error"], "
|
|
467
|
+
const failOn = stringChoice(rawOptions.failOn, ["none", "advisory", "warning", "error"], "advisory");
|
|
468
|
+
const diffInput = diffOption(paths, rawOptions);
|
|
373
469
|
const baselineValue = rawOptions.baseline;
|
|
374
470
|
const shouldSkipBaseline =
|
|
375
471
|
!context.shouldAllowBaselineFlag ||
|
|
376
472
|
baselineValue === false ||
|
|
377
473
|
rawOptions.noBaseline === true;
|
|
378
474
|
return {
|
|
379
|
-
paths,
|
|
475
|
+
paths: diffInput.paths,
|
|
380
476
|
...configOption(rawOptions),
|
|
477
|
+
...profileOption(rawOptions),
|
|
381
478
|
shouldSkipConfig:
|
|
382
479
|
rawOptions.config === false ||
|
|
383
480
|
rawOptions.noConfig === true,
|
|
384
481
|
format,
|
|
385
482
|
failOn,
|
|
386
483
|
shouldIncludeIgnored: rawOptions.includeIgnored === true,
|
|
387
|
-
|
|
484
|
+
changedScope: stringChoice(rawOptions.changedScope, ["symbol", "hunk"], "symbol"),
|
|
485
|
+
...diffInput.options,
|
|
486
|
+
...changedRangesOption(rawOptions),
|
|
487
|
+
...sinceOption(rawOptions),
|
|
388
488
|
...historyFileOption(rawOptions),
|
|
389
489
|
...baselineOption(baselineValue, context),
|
|
390
490
|
...generateBaselineOption(rawOptions),
|
|
@@ -398,13 +498,34 @@ function configOption(rawOptions: Record<string, unknown>): Partial<Pick<Analysi
|
|
|
398
498
|
return typeof rawOptions.config === "string" ? { config: rawOptions.config } : {};
|
|
399
499
|
}
|
|
400
500
|
|
|
401
|
-
//
|
|
402
|
-
//
|
|
403
|
-
function
|
|
501
|
+
// Same conditional-spread discipline for `--profile`: an absent flag must stay absent (not undefined)
|
|
502
|
+
// so `loadConfig` falls back to the config-file `profile:` block rather than seeing an explicit CLI value.
|
|
503
|
+
function profileOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "profile">> {
|
|
504
|
+
return typeof rawOptions.profile === "string" ? { profile: rawOptions.profile } : {};
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// `--diff` without an argument means "working-tree". `--diff -` is accepted even when Commander
|
|
508
|
+
// treats `-` as a positional path, so stdin-diff callers can use the documented spacing form.
|
|
509
|
+
function diffOption(paths: string[], rawOptions: Record<string, unknown>): { paths: string[]; options: Partial<Pick<AnalysisOptions, "diff" | "diffPatch">> } {
|
|
404
510
|
if (typeof rawOptions.diff === "string") {
|
|
405
|
-
return
|
|
511
|
+
return rawOptions.diff === "-"
|
|
512
|
+
? { paths, options: { diff: "-", diffPatch: readFileSync(0, "utf8") } }
|
|
513
|
+
: { paths, options: { diff: rawOptions.diff } };
|
|
406
514
|
}
|
|
407
|
-
|
|
515
|
+
if (rawOptions.diff === true && paths[0] === "-") {
|
|
516
|
+
return { paths: paths.slice(1), options: { diff: "-", diffPatch: readFileSync(0, "utf8") } };
|
|
517
|
+
}
|
|
518
|
+
return rawOptions.diff === true ? { paths, options: { diff: "working-tree" } } : { paths, options: {} };
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// Preserves absence for `changedRanges`; setting it to undefined would change exact optional typing.
|
|
522
|
+
function changedRangesOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "changedRanges">> {
|
|
523
|
+
return typeof rawOptions.changedRanges === "string" ? { changedRanges: rawOptions.changedRanges } : {};
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
// Preserves absence for `since` so direct callers can distinguish no ref from an explicit ref.
|
|
527
|
+
function sinceOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "since">> {
|
|
528
|
+
return typeof rawOptions.since === "string" ? { since: rawOptions.since } : {};
|
|
408
529
|
}
|
|
409
530
|
|
|
410
531
|
// Conditional spread keeps `historyFile` absent rather than `undefined` under exactOptionalPropertyTypes.
|
|
@@ -437,3 +558,40 @@ function generateBaselineOption(rawOptions: Record<string, unknown>): Partial<Pi
|
|
|
437
558
|
function stringChoice<T extends string>(value: unknown, choices: readonly T[], fallback: T): T {
|
|
438
559
|
return typeof value === "string" && choices.includes(value as T) ? (value as T) : fallback;
|
|
439
560
|
}
|
|
561
|
+
|
|
562
|
+
/*
|
|
563
|
+
* Precedence wiring for `--fail-on`: when the user did NOT pass `--fail-on` explicitly, the
|
|
564
|
+
* `.gruff-ts.yaml` `minimumSeverity.<cmd>` value wins over the binary default. CLI flag always
|
|
565
|
+
* wins when explicitly set. Commander's `getOptionValueSource("failOn")` returns `"cli"` for
|
|
566
|
+
* explicit invocations and `"default"` otherwise, so the source check drives the precedence
|
|
567
|
+
* chain. Throws `ConfigLoadError` on malformed config; CLI action handlers catch and format that
|
|
568
|
+
* cleanly via `runWithConfigErrorHandling`.
|
|
569
|
+
*/
|
|
570
|
+
function applyMinimumSeverityPrecedence(options: AnalysisOptions, command: MinimumSeverityCommand, commanderCommand: Command): AnalysisOptions {
|
|
571
|
+
if (commanderCommand.getOptionValueSource("failOn") === "cli") {
|
|
572
|
+
return options;
|
|
573
|
+
}
|
|
574
|
+
const config = loadConfig(cwd(), options);
|
|
575
|
+
const configuredFailOn = minimumSeverityFor(config, command);
|
|
576
|
+
return configuredFailOn === undefined ? options : { ...options, failOn: configuredFailOn };
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/*
|
|
580
|
+
* Wraps an async command action so a malformed `.gruff-ts.yaml` surfaces as a clean stderr message
|
|
581
|
+
* and exit code 2, not a raw Node stack trace. Catches `ConfigLoadError` (user-actionable config
|
|
582
|
+
* bug) and reports it via formatted stderr; rethrows every other exception so an analyser/code
|
|
583
|
+
* bug still surfaces its stack for debugging. The exit code matches the existing diagnostic
|
|
584
|
+
* convention in `exitFor` so CI scripts that already handle exit 2 keep working.
|
|
585
|
+
*/
|
|
586
|
+
async function runWithConfigErrorHandling(action: () => Promise<void> | void): Promise<void> {
|
|
587
|
+
try {
|
|
588
|
+
await action();
|
|
589
|
+
} catch (error) {
|
|
590
|
+
if (error instanceof ConfigLoadError) {
|
|
591
|
+
process.stderr.write(`gruff-ts: config error\n ${error.message}\n\nSuggested fix:\n ${error.suggestion}\n`);
|
|
592
|
+
process.exitCode = 2;
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
throw error;
|
|
596
|
+
}
|
|
597
|
+
}
|