@blundergoat/gruff-ts 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +123 -1
- package/CONTRIBUTING.md +32 -25
- package/README.md +55 -46
- package/SECURITY.md +18 -30
- package/UPGRADING.md +101 -0
- package/bin/gruff-ts +3 -0
- package/docs/README.md +11 -13
- package/docs/agent-hook.md +33 -24
- package/docs/ci-integration.md +38 -24
- package/docs/configuration.md +173 -71
- package/docs/dashboard.md +12 -13
- package/docs/output-formats.md +100 -25
- package/docs/philosophy.md +2 -2
- package/docs/reports-and-ci.md +14 -157
- package/docs/rules.md +140 -106
- package/package.json +10 -8
- package/src/analyser.ts +886 -282
- package/src/baseline-file.ts +867 -0
- package/src/baseline-identity.ts +463 -0
- package/src/baseline-options.ts +139 -34
- package/src/baseline.ts +85 -55
- package/src/blocks.ts +579 -364
- package/src/changed-regions.ts +414 -65
- package/src/check-ignore.ts +28 -13
- package/src/class-rules.ts +461 -302
- package/src/cli-program.ts +956 -166
- package/src/cli.ts +9 -2
- package/src/comment-rules.ts +277 -414
- package/src/comment-scanner.ts +363 -44
- package/src/complexity-metrics.ts +320 -0
- package/src/config-load-error.ts +17 -8
- package/src/config-parse.ts +291 -98
- package/src/config-preservation.ts +81 -26
- package/src/config.ts +778 -210
- package/src/constants.ts +7 -6
- package/src/context-doc-rules.ts +188 -61
- package/src/dashboard.ts +88 -23
- package/src/dead-code-rules.ts +153 -74
- package/src/discovery.ts +521 -148
- package/src/doc-rules.ts +592 -147
- package/src/duplicate-test-group-rules.ts +359 -0
- package/src/findings-helpers.ts +240 -89
- package/src/findings.ts +48 -24
- package/src/fixture-purpose-rules.ts +226 -48
- package/src/github-actions-event-guards.ts +331 -0
- package/src/github-actions-rules.ts +336 -106
- package/src/hook-contract.ts +708 -211
- package/src/init-config.ts +169 -114
- package/src/inline-suppressions.ts +340 -0
- package/src/limit-band.ts +56 -0
- package/src/line-rules.ts +331 -419
- package/src/migrate-config.ts +670 -0
- package/src/naming-pushers.ts +33 -107
- package/src/parsed-script.ts +1206 -0
- package/src/pillar-summary.ts +56 -40
- package/src/profiles.ts +97 -71
- package/src/project-config-rules.ts +335 -146
- package/src/project-rules.ts +237 -115
- package/src/public-exports.ts +284 -0
- package/src/report-html.ts +217 -85
- package/src/report-renderers.ts +864 -195
- package/src/rule-list.ts +166 -46
- package/src/rules.ts +100 -104
- package/src/safety-rules.ts +191 -132
- package/src/scoring.ts +255 -52
- package/src/security-flow-rules.ts +930 -109
- package/src/selectors.ts +169 -0
- package/src/sensitive-data-rules.ts +502 -375
- package/src/sensitive-exclusions.ts +435 -0
- package/src/source-text.ts +380 -148
- package/src/static-analysis-redundant-rules.ts +298 -41
- package/src/test-block-rules.ts +422 -228
- package/src/text-scans.ts +67 -9
- package/src/types.ts +222 -71
- package/tsconfig.json +2 -1
- package/src/process-exec-metadata.ts +0 -153
- package/src/test-fixtures.ts +0 -668
package/src/report-renderers.ts
CHANGED
|
@@ -1,24 +1,32 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
import
|
|
1
|
+
// Turns scan results into terminal output, shareable reports, and formats consumed by CI.
|
|
2
|
+
//
|
|
3
|
+
// Use JSON for individual findings, summary JSON for totals, and hotspot JSON for the highest-priority files.
|
|
4
|
+
// Converts report paths to project-relative form so a reader can compare output from different machines.
|
|
5
|
+
import { findingIdentities } from "./baseline-identity.ts";
|
|
6
|
+
import { isAbsolute, relative } from "node:path";
|
|
7
|
+
import type { AnalysisReport, Finding, OutputFormat, ScanSurfaceNote, Severity, SkippedPath, SuppressionSummary } from "./types.ts";
|
|
6
8
|
import { OUTPUT_VOLUME_HINT_THRESHOLD } from "./constants.ts";
|
|
9
|
+
import { MINIFIED_FILE_PATTERN } from "./discovery.ts";
|
|
7
10
|
import { countRuleSeverities } from "./findings-helpers.ts";
|
|
8
11
|
import { buildPillarRows, type PillarRow } from "./pillar-summary.ts";
|
|
9
12
|
import { ruleDescriptors } from "./rules.ts";
|
|
10
13
|
import { renderHtml } from "./report-html.ts";
|
|
11
|
-
import { severityGradeBreakdown } from "./scoring.ts";
|
|
14
|
+
import { compositeLine, exitFor, severityGradeBreakdown } from "./scoring.ts";
|
|
15
|
+
import { totalSuppressedFindings } from "./sensitive-exclusions.ts";
|
|
12
16
|
|
|
13
|
-
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
+
/**
|
|
18
|
+
* Renders the result in the format the user selected, including the compact hotspot view for prioritizing fixes.
|
|
19
|
+
*
|
|
20
|
+
* @param report - Native analysis report supplying the data for the selected format.
|
|
21
|
+
* @param format - Selects the human-readable renderer or machine output projection.
|
|
22
|
+
* @param exitCode - decided status for JSON. Omit it when rendering directly to use the run's severity threshold.
|
|
23
|
+
* @returns Rendered report text.
|
|
24
|
+
* Hotspot JSON uses the stable gruff.hotspot.v1 schema, with up to ten top offenders and every scan diagnostic, such as a deep-scan budget notice.
|
|
17
25
|
*/
|
|
18
|
-
function renderReport(report: AnalysisReport, format: OutputFormat): string {
|
|
26
|
+
function renderReport(report: AnalysisReport, format: OutputFormat, exitCode?: number): string {
|
|
19
27
|
switch (format) {
|
|
20
28
|
case "json":
|
|
21
|
-
return JSON.stringify(toJsonReport(report), null, 2);
|
|
29
|
+
return JSON.stringify(toJsonReport(report, exitCode), null, 2);
|
|
22
30
|
case "html":
|
|
23
31
|
return renderHtml(report);
|
|
24
32
|
case "markdown":
|
|
@@ -26,7 +34,17 @@ function renderReport(report: AnalysisReport, format: OutputFormat): string {
|
|
|
26
34
|
case "github":
|
|
27
35
|
return renderGithub(report);
|
|
28
36
|
case "hotspot":
|
|
29
|
-
return JSON.stringify(
|
|
37
|
+
return JSON.stringify(
|
|
38
|
+
{
|
|
39
|
+
schemaVersion: "gruff.hotspot.v1",
|
|
40
|
+
tool: report.tool,
|
|
41
|
+
score: report.score.composite,
|
|
42
|
+
files: report.score.topOffenders.slice(0, 10),
|
|
43
|
+
diagnostics: report.diagnostics.map((diagnostic) => machineDiagnostic(diagnostic, report.run.projectRoot)),
|
|
44
|
+
},
|
|
45
|
+
null,
|
|
46
|
+
2,
|
|
47
|
+
);
|
|
30
48
|
case "sarif":
|
|
31
49
|
return renderSarif(report);
|
|
32
50
|
case "text":
|
|
@@ -34,43 +52,467 @@ function renderReport(report: AnalysisReport, format: OutputFormat): string {
|
|
|
34
52
|
}
|
|
35
53
|
}
|
|
36
54
|
|
|
37
|
-
type
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
55
|
+
type MachineFinding = Omit<Finding, "filePath" | "line" | "endLine" | "column" | "symbol" | "remediation" | "metadata"> & {
|
|
56
|
+
file: string;
|
|
57
|
+
line: number;
|
|
58
|
+
endLine?: number;
|
|
59
|
+
column?: number;
|
|
60
|
+
symbol?: string;
|
|
61
|
+
remediation: string;
|
|
62
|
+
metadata: Record<string, unknown>;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Canonical machine record for one skipped path.
|
|
67
|
+
*
|
|
68
|
+
* Invariant: `pattern` is present only for a `config` source; reason values use the family vocabulary.
|
|
69
|
+
*/
|
|
70
|
+
interface MachinePathDetail {
|
|
71
|
+
path: string;
|
|
72
|
+
reason: "vcs" | "dependency" | "build-output" | "local-tooling" | "generated" | "gitignored" | "config-ignore";
|
|
73
|
+
source: SkippedPath["source"];
|
|
74
|
+
pattern?: string;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Canonical machine diagnostic with omission-based optional location fields.
|
|
79
|
+
*
|
|
80
|
+
* Invariant: `invalidatesRun` is the schema-required field name and always carries an explicit boolean.
|
|
81
|
+
*/
|
|
82
|
+
interface MachineDiagnostic {
|
|
83
|
+
type: string;
|
|
84
|
+
message: string;
|
|
85
|
+
"invalidatesRun": boolean;
|
|
86
|
+
file?: string;
|
|
87
|
+
line?: number;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
type MachineSuppression = Omit<SuppressionSummary, "paths" | "symbol"> & {
|
|
91
|
+
paths: string[];
|
|
92
|
+
symbol?: string;
|
|
42
93
|
};
|
|
43
94
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
95
|
+
/**
|
|
96
|
+
* Fields shared byte-for-byte by analysis and summary v3 envelopes.
|
|
97
|
+
*
|
|
98
|
+
* Invariant: summary changes only `schemaVersion` and omits the top-level findings array.
|
|
99
|
+
*/
|
|
100
|
+
interface MachineEnvelopeCore {
|
|
101
|
+
tool: AnalysisReport["tool"];
|
|
102
|
+
run: {
|
|
103
|
+
failOn: AnalysisReport["run"]["failOn"];
|
|
104
|
+
format: AnalysisReport["run"]["format"];
|
|
105
|
+
inputs: string[];
|
|
106
|
+
projectRoot: ".";
|
|
107
|
+
config?: string;
|
|
108
|
+
includeIgnored?: true;
|
|
109
|
+
};
|
|
110
|
+
summary: {
|
|
111
|
+
analysedFiles: number;
|
|
112
|
+
diagnostics: number;
|
|
113
|
+
exitCode: number;
|
|
114
|
+
findings: AnalysisReport["summary"];
|
|
115
|
+
findingsByPillar: Record<string, number>;
|
|
116
|
+
ignoredPaths: number;
|
|
117
|
+
missingPaths: number;
|
|
118
|
+
skippedFiles: number;
|
|
119
|
+
suppressedFindings?: number;
|
|
120
|
+
};
|
|
121
|
+
score: {
|
|
122
|
+
composite: { grade: string | null; score: number | null };
|
|
123
|
+
/** Ratified scoring denominator and the pillar set the composite averaged over. */
|
|
124
|
+
evaluatedFiles: number;
|
|
125
|
+
scoredPillars: AnalysisReport["score"]["scoredPillars"];
|
|
126
|
+
clusters: AnalysisReport["score"]["clusters"];
|
|
127
|
+
ruleAttribution: AnalysisReport["score"]["ruleAttribution"];
|
|
128
|
+
pillars: AnalysisReport["score"]["pillars"];
|
|
129
|
+
topOffenders: Array<{ file: string; score: number | null; penalty: number; findings: number }>;
|
|
130
|
+
};
|
|
131
|
+
diagnostics: MachineDiagnostic[];
|
|
132
|
+
paths: { analysedFiles: number; details: MachinePathDetail[]; ignoredPaths: string[]; missingPaths: string[] };
|
|
133
|
+
suppressions: MachineSuppression[];
|
|
134
|
+
baseline?: { applied: boolean; generated: boolean; path?: string; source: string; suppressedFindings: number; entries: number; newFindings: number; unchangedFindings: number; resolvedFindings: number };
|
|
135
|
+
diff?: { enabled: true; filteredFindings: number; mode: "changed-regions" };
|
|
136
|
+
extensions?: { ts: { topLevel: { notes: ScanSurfaceNote[] } } };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
type JsonAnalysisReport = MachineEnvelopeCore & { schemaVersion: "gruff.analysis.v3"; findings: MachineFinding[] };
|
|
140
|
+
type JsonSummaryReport = MachineEnvelopeCore & { schemaVersion: "gruff.summary.v3" };
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Builds the JSON report for readers who need the run details and each individual finding.
|
|
144
|
+
* Invariant: the result is the exact v3 envelope, without legacy aliases or volatile timestamps.
|
|
145
|
+
*
|
|
146
|
+
* @param report - Native analysis report supplying run metadata, scores, diagnostics, and findings.
|
|
147
|
+
* @param exitCode - Decided CLI exit status; omit to derive it from the report's fail-on threshold.
|
|
148
|
+
* @returns The gruff.analysis.v3 JSON envelope with project-relative findings.
|
|
149
|
+
*/
|
|
150
|
+
function toJsonReport(report: AnalysisReport, exitCode?: number): JsonAnalysisReport {
|
|
151
|
+
return {
|
|
152
|
+
schemaVersion: "gruff.analysis.v3",
|
|
153
|
+
...machineEnvelopeCore(report, exitCode),
|
|
154
|
+
findings: report.findings.map((finding) => machineFinding(finding, report.run.projectRoot)),
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Builds the JSON summary for automation that needs the outcome and totals without each finding.
|
|
160
|
+
* Invariant: summary v3 has the same run details as analysis v3 and omits the individual finding list.
|
|
161
|
+
*
|
|
162
|
+
* @param report - Native analysis report supplying run details, totals, scores, and diagnostics.
|
|
163
|
+
* @param exitCode - Decided CLI exit status; omit to derive it from the report's fail-on threshold.
|
|
164
|
+
* @returns The gruff.summary.v3 JSON envelope without the top-level findings list.
|
|
165
|
+
*/
|
|
166
|
+
function toJsonSummary(report: AnalysisReport, exitCode?: number): JsonSummaryReport {
|
|
167
|
+
return { schemaVersion: "gruff.summary.v3", ...machineEnvelopeCore(report, exitCode) };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Shares run details and totals between analyse and summary JSON so both report the same exit outcome.
|
|
172
|
+
* Invariant: a missing baseline, change selection, or note list leaves that section out of the result.
|
|
173
|
+
*
|
|
174
|
+
* @param report - Native analysis report supplying run, score, path, diagnostic, and suppression data.
|
|
175
|
+
* @param exitCode - Exit code recorded in the summary block; defaults to the threshold exit code for the run.
|
|
176
|
+
* @returns Shared v3 machine envelope with project-relative paths and optional baseline, diff, and note sections.
|
|
177
|
+
*/
|
|
178
|
+
function machineEnvelopeCore(report: AnalysisReport, exitCode = exitFor(report, report.run.failOn)): MachineEnvelopeCore {
|
|
179
|
+
const { details, ignoredPaths } = machinePathProjection(report);
|
|
180
|
+
const missingPaths = machinePaths(report.paths.missingPaths, report.run.projectRoot);
|
|
47
181
|
return {
|
|
48
|
-
|
|
49
|
-
|
|
182
|
+
tool: report.tool,
|
|
183
|
+
run: machineRun(report),
|
|
184
|
+
summary: machineSummary(report, details.length, missingPaths.length, exitCode),
|
|
50
185
|
score: {
|
|
51
|
-
|
|
52
|
-
|
|
186
|
+
composite: { grade: report.score.grade, score: report.score.composite },
|
|
187
|
+
evaluatedFiles: report.score.evaluatedFiles,
|
|
188
|
+
scoredPillars: report.score.scoredPillars,
|
|
189
|
+
clusters: report.score.clusters,
|
|
190
|
+
ruleAttribution: report.score.ruleAttribution,
|
|
191
|
+
pillars: report.score.pillars,
|
|
192
|
+
topOffenders: report.score.topOffenders.map((offender) => ({
|
|
193
|
+
file: machinePath(offender.filePath, report.run.projectRoot),
|
|
194
|
+
score: offender.score,
|
|
195
|
+
penalty: offender.penalty,
|
|
196
|
+
findings: offender.findings,
|
|
197
|
+
})),
|
|
53
198
|
},
|
|
199
|
+
diagnostics: report.diagnostics.map((diagnostic) => machineDiagnostic(diagnostic, report.run.projectRoot)),
|
|
200
|
+
paths: {
|
|
201
|
+
analysedFiles: report.paths.analysedFiles,
|
|
202
|
+
details,
|
|
203
|
+
ignoredPaths,
|
|
204
|
+
missingPaths,
|
|
205
|
+
},
|
|
206
|
+
suppressions: report.suppressions.map((suppression) => machineSuppression(suppression, report.run.projectRoot)),
|
|
207
|
+
// Include review details only when the user applied or generated a baseline.
|
|
208
|
+
...(report.baseline === undefined ? {} : {
|
|
209
|
+
baseline: {
|
|
210
|
+
applied: !report.baseline.generated,
|
|
211
|
+
generated: report.baseline.generated,
|
|
212
|
+
...optionalMachinePath("path", report.baseline.path, report.run.projectRoot),
|
|
213
|
+
source: report.baseline.source,
|
|
214
|
+
suppressedFindings: report.baseline.suppressed,
|
|
215
|
+
// Generating a baseline does not compare reviews yet, so comparison counts start at zero.
|
|
216
|
+
entries: report.baseline.entries ?? 0,
|
|
217
|
+
newFindings: report.baseline.newFindings ?? 0,
|
|
218
|
+
unchangedFindings: report.baseline.unchangedFindings ?? 0,
|
|
219
|
+
resolvedFindings: report.baseline.resolvedFindings ?? 0,
|
|
220
|
+
},
|
|
221
|
+
}),
|
|
222
|
+
...(report.suppressedCount === undefined ? {} : {
|
|
223
|
+
diff: { enabled: true as const, filteredFindings: report.suppressedCount, mode: "changed-regions" as const },
|
|
224
|
+
}),
|
|
225
|
+
...(report.notes === undefined ? {} : {
|
|
226
|
+
extensions: { ts: { topLevel: { notes: report.notes.map((note) => {
|
|
227
|
+
const path = machinePath(note.path, report.run.projectRoot);
|
|
228
|
+
return { ...note, path, message: note.message.replace(note.path, () => path) };
|
|
229
|
+
}) } } },
|
|
230
|
+
}),
|
|
54
231
|
};
|
|
55
232
|
}
|
|
56
233
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
234
|
+
/**
|
|
235
|
+
* Return stable machine run settings from the native report, with project-relative paths and a portable dot for the root.
|
|
236
|
+
* Missing inputs default to the project directory. Missing or out-of-project config paths are omitted.
|
|
237
|
+
* Publish includeIgnored only when enabled.
|
|
238
|
+
*
|
|
239
|
+
* @param report - Native analysis report supplying run configuration, inputs, and project root.
|
|
240
|
+
* @returns Normalized run metadata for the v3 machine envelope.
|
|
241
|
+
*/
|
|
242
|
+
function machineRun(report: AnalysisReport): MachineEnvelopeCore["run"] {
|
|
243
|
+
return {
|
|
244
|
+
failOn: report.run.failOn,
|
|
245
|
+
format: report.run.format,
|
|
246
|
+
inputs: machinePaths(report.run.inputs ?? ["."], report.run.projectRoot),
|
|
247
|
+
projectRoot: ".",
|
|
248
|
+
...(report.run.config === undefined ? {} : optionalMachinePath("config", report.run.config, report.run.projectRoot)),
|
|
249
|
+
...(report.run.includeIgnored === true ? { includeIgnored: true as const } : {}),
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Summarizes the visible findings and path counts while preserving the exit status decided by the CLI.
|
|
255
|
+
* Invariant: skipped and ignored counts both reflect the published path details. Empty pillars have no finding-count entry.
|
|
256
|
+
*
|
|
257
|
+
* @param report - Native analysis report supplying findings, diagnostics, summary totals, and analysed file count.
|
|
258
|
+
* @param skippedFiles - Count of skipped path entries published as both skippedFiles and ignoredPaths.
|
|
259
|
+
* @param missingPaths - Count of normalized missing input paths.
|
|
260
|
+
* @param exitCode - Decided CLI exit status preserved in the summary block.
|
|
261
|
+
* @returns Summary counts and sorted per-pillar finding totals for the machine envelope.
|
|
262
|
+
*/
|
|
263
|
+
function machineSummary(report: AnalysisReport, skippedFiles: number, missingPaths: number, exitCode: number): MachineEnvelopeCore["summary"] {
|
|
264
|
+
const pillarCounts = new Map<string, number>();
|
|
265
|
+
// Count displayed findings so drill-down filters and pillar totals describe the same set.
|
|
266
|
+
report.findings.forEach((finding) => pillarCounts.set(finding.pillar, (pillarCounts.get(finding.pillar) ?? 0) + 1));
|
|
267
|
+
return {
|
|
268
|
+
analysedFiles: report.paths.analysedFiles,
|
|
269
|
+
diagnostics: report.diagnostics.length,
|
|
270
|
+
exitCode,
|
|
271
|
+
findings: report.summary,
|
|
272
|
+
findingsByPillar: Object.fromEntries([...pillarCounts.entries()].sort(([left], [right]) => left.localeCompare(right))),
|
|
273
|
+
ignoredPaths: skippedFiles,
|
|
274
|
+
missingPaths,
|
|
275
|
+
skippedFiles,
|
|
276
|
+
...(report.suppressedCount === undefined ? {} : { suppressedFindings: report.suppressedCount }),
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Return a new machine finding with the native fingerprint and stable identity unchanged and the path relative to projectRoot.
|
|
282
|
+
* Missing or invalid lines use 1. Missing or invalid columns are omitted and give line-only precision. Missing remediation becomes empty text.
|
|
283
|
+
* Omit end lines without a valid position and symbols that are absent or empty.
|
|
284
|
+
*
|
|
285
|
+
* @param finding - Native finding to project into the v3 machine schema.
|
|
286
|
+
* @param projectRoot - Root directory used to normalize the finding's file path.
|
|
287
|
+
* @returns Normalized machine finding record preserving fingerprint, stable identity, and location precision metadata.
|
|
288
|
+
*/
|
|
289
|
+
function machineFinding(finding: Finding, projectRoot: string): MachineFinding {
|
|
290
|
+
const line = positiveInteger(finding.line) ?? 1;
|
|
291
|
+
const column = positiveInteger(finding.column);
|
|
292
|
+
const endLine = positiveInteger(finding.endLine);
|
|
293
|
+
return {
|
|
294
|
+
ruleId: finding.ruleId,
|
|
295
|
+
message: finding.message,
|
|
296
|
+
file: machinePath(finding.filePath, projectRoot),
|
|
297
|
+
line,
|
|
298
|
+
...(endLine === undefined ? {} : { endLine }),
|
|
299
|
+
...(column === undefined ? {} : { column }),
|
|
300
|
+
severity: finding.severity,
|
|
301
|
+
pillar: finding.pillar,
|
|
302
|
+
secondaryPillars: finding.secondaryPillars,
|
|
303
|
+
tier: finding.tier,
|
|
304
|
+
confidence: finding.confidence,
|
|
305
|
+
...(finding.symbol === undefined || finding.symbol.length === 0 ? {} : { symbol: finding.symbol }),
|
|
306
|
+
remediation: finding.remediation ?? "",
|
|
307
|
+
fingerprint: finding.fingerprint,
|
|
308
|
+
stableIdentity: finding.stableIdentity,
|
|
309
|
+
metadata: {
|
|
310
|
+
...finding.metadata,
|
|
311
|
+
locationPrecision: column === undefined ? "line-only" : "scanner-pinpointed",
|
|
312
|
+
},
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Formats a diagnostic for CI readers. A scan-budget notice can leave the run valid even though some checks were skipped.
|
|
318
|
+
*
|
|
319
|
+
* Invariant: defaults to invalidating the run. Missing or external file paths and missing line numbers have no location field.
|
|
320
|
+
* An absolute in-project path inside the message is rewritten project-relative, so host folders never reach CI logs.
|
|
321
|
+
*
|
|
322
|
+
* @param diagnostic - Native scan diagnostic supplying type, message, validity flag, and optional source location.
|
|
323
|
+
* @param projectRoot - Root directory used to resolve an in-project diagnostic file path.
|
|
324
|
+
* @returns Canonical machine diagnostic record for the v3 envelope.
|
|
325
|
+
*/
|
|
326
|
+
function machineDiagnostic(
|
|
327
|
+
diagnostic: AnalysisReport["diagnostics"][number],
|
|
328
|
+
projectRoot: string,
|
|
329
|
+
): MachineDiagnostic {
|
|
330
|
+
const line = positiveInteger(diagnostic.line);
|
|
331
|
+
const fileEntry = diagnostic.filePath === undefined ? {} : optionalMachinePath("file", diagnostic.filePath, projectRoot);
|
|
332
|
+
const message = diagnostic.filePath !== undefined && fileEntry.file !== undefined && diagnostic.filePath !== fileEntry.file
|
|
333
|
+
? diagnostic.message.replaceAll(diagnostic.filePath, fileEntry.file)
|
|
334
|
+
: diagnostic.message;
|
|
335
|
+
return {
|
|
336
|
+
type: diagnostic.diagnosticType,
|
|
337
|
+
message,
|
|
338
|
+
invalidatesRun: diagnostic.invalidatesRun !== false,
|
|
339
|
+
...fileEntry,
|
|
340
|
+
...(line === undefined ? {} : { line }),
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Returns a machine suppression from suppression, normalizing its paths relative to projectRoot.
|
|
346
|
+
* Null or empty symbols and an absent source are omitted.
|
|
347
|
+
*
|
|
348
|
+
* @param suppression - Native suppression summary record to normalize.
|
|
349
|
+
* @param projectRoot - Root directory used to convert covered paths to project-relative POSIX form.
|
|
350
|
+
* @returns Normalized machine suppression entry for the v3 envelope.
|
|
351
|
+
*/
|
|
352
|
+
function machineSuppression(suppression: SuppressionSummary, projectRoot: string): MachineSuppression {
|
|
353
|
+
return {
|
|
354
|
+
index: suppression.index,
|
|
355
|
+
rule: suppression.rule,
|
|
356
|
+
paths: machinePaths(suppression.paths, projectRoot),
|
|
357
|
+
...(suppression.symbol === null || suppression.symbol.length === 0 ? {} : { symbol: suppression.symbol }),
|
|
358
|
+
reason: suppression.reason,
|
|
359
|
+
suppressed: suppression.suppressed,
|
|
360
|
+
// Built-in, inline, and duplicate rows retain their source; configured rows omit it.
|
|
361
|
+
...(suppression.source === undefined ? {} : { source: suppression.source }),
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Returns report's normalized skip details and ignored paths, resolving paths against report.run.projectRoot.
|
|
367
|
+
* The ignored path list must exactly match the detail paths in order.
|
|
368
|
+
*
|
|
369
|
+
* @param report - Native analysis report supplying skipped path records, ignored paths, and project root.
|
|
370
|
+
* @returns Normalized skip details and matching ignored paths.
|
|
371
|
+
* @throws {Error} Normalized ignored paths and skip-detail paths differ in length, value, or order.
|
|
372
|
+
*/
|
|
373
|
+
function machinePathProjection(report: AnalysisReport): { details: MachinePathDetail[]; ignoredPaths: string[] } {
|
|
374
|
+
const details = report.paths.skipped.map((skipped) => machinePathDetail(skipped, report.run.projectRoot));
|
|
375
|
+
const ignoredPaths = machinePaths(report.paths.ignoredPaths, report.run.projectRoot);
|
|
376
|
+
if (ignoredPaths.length !== details.length || ignoredPaths.some((path, index) => path !== details[index]?.path)) {
|
|
377
|
+
throw new Error("Machine ignored paths must be the exact projection of path details.");
|
|
378
|
+
}
|
|
379
|
+
return { details, ignoredPaths };
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Returns a machine path detail for skipped, making its path relative to projectRoot and mapping its ignore reason.
|
|
384
|
+
* Only config-sourced records include their matching pattern.
|
|
385
|
+
*
|
|
386
|
+
* @param skipped - Skipped path entry with its path, source, and matching pattern.
|
|
387
|
+
* @param projectRoot - Root directory used to normalize the skipped path.
|
|
388
|
+
* @returns Canonical machine path detail with normalized path, reason, source, and optional pattern.
|
|
389
|
+
*/
|
|
390
|
+
function machinePathDetail(skipped: SkippedPath, projectRoot: string): MachinePathDetail {
|
|
391
|
+
return {
|
|
392
|
+
path: machinePath(skipped.path, projectRoot),
|
|
393
|
+
reason: machineIgnoreReason(skipped),
|
|
394
|
+
source: skipped.source,
|
|
395
|
+
...(skipped.source === "config" ? { pattern: skipped.pattern } : {}),
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// The family reason for each directory name TypeScript skips by default (FAMILY-CONTRACT.md section 7).
|
|
400
|
+
const DEFAULT_DIRECTORY_REASONS: ReadonlyMap<string, MachinePathDetail["reason"]> = new Map([
|
|
401
|
+
[".git", "vcs"], [".hg", "vcs"], [".svn", "vcs"],
|
|
402
|
+
["node_modules", "dependency"], ["vendor", "dependency"], ["vendors", "dependency"], ["third_party", "dependency"],
|
|
403
|
+
["third-party", "dependency"], ["bower_components", "dependency"],
|
|
404
|
+
["build", "build-output"], ["coverage", "build-output"], ["dist", "build-output"],
|
|
405
|
+
[".fleet", "local-tooling"], [".idea", "local-tooling"], [".vscode", "local-tooling"],
|
|
406
|
+
]);
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Returns the canonical ignore reason for skipped, using its source and matched default pattern.
|
|
410
|
+
*
|
|
411
|
+
* @param skipped - Skipped path record whose source and pattern determine the reason classification.
|
|
412
|
+
* @returns Canonical reason label from the machine path detail vocabulary.
|
|
413
|
+
* @throws {Error} A default pattern is neither the minified-file pattern nor one with a recognized final directory component.
|
|
414
|
+
*/
|
|
415
|
+
function machineIgnoreReason(skipped: SkippedPath): MachinePathDetail["reason"] {
|
|
416
|
+
if (skipped.source === "config") {
|
|
417
|
+
return "config-ignore";
|
|
418
|
+
}
|
|
419
|
+
if (skipped.source === "gitignore") {
|
|
420
|
+
return "gitignored";
|
|
421
|
+
}
|
|
422
|
+
if (skipped.pattern === MINIFIED_FILE_PATTERN) {
|
|
423
|
+
return "generated";
|
|
424
|
+
}
|
|
425
|
+
const component = skipped.pattern.replace(/\/+$/u, "").split("/").at(-1) ?? "";
|
|
426
|
+
const reason = DEFAULT_DIRECTORY_REASONS.get(component);
|
|
427
|
+
if (reason === undefined) {
|
|
428
|
+
throw new Error(`Default ignored path has no canonical reason: ${skipped.pattern}`);
|
|
429
|
+
}
|
|
430
|
+
return reason;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Returns values as unique project-relative POSIX paths in first-occurrence order, resolving absolute paths against projectRoot.
|
|
435
|
+
*
|
|
436
|
+
* @param values - Candidate file or directory paths to normalize and deduplicate.
|
|
437
|
+
* @param projectRoot - Root directory against which absolute paths are resolved.
|
|
438
|
+
* @returns Deduplicated project-relative POSIX path list preserving first-occurrence order.
|
|
439
|
+
*/
|
|
440
|
+
function machinePaths(values: readonly string[], projectRoot: string): string[] {
|
|
441
|
+
return [...new Set(values.map((value) => machinePath(value, projectRoot)))];
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Includes a portable path when a report can point to a file inside the selected project.
|
|
446
|
+
* An empty object omits an external path, such as a config the user keeps in a sibling project.
|
|
447
|
+
*
|
|
448
|
+
* @param key - Property name assigned to the normalized path when it resolves inside projectRoot.
|
|
449
|
+
* @param pathValue - Candidate file path to resolve relative to projectRoot.
|
|
450
|
+
* @param projectRoot - Root directory that bounds whether the path can be published.
|
|
451
|
+
* @returns Single-property record keyed by key for in-project paths, or empty when external.
|
|
452
|
+
*/
|
|
453
|
+
function optionalMachinePath<Key extends string>(key: Key, pathValue: string, projectRoot: string): Partial<Record<Key, string>> {
|
|
454
|
+
const relativeValue = (isAbsolute(pathValue) ? relative(projectRoot, pathValue) : pathValue).replaceAll("\\", "/");
|
|
455
|
+
// An external settings file can affect the run without appearing as a location in its JSON.
|
|
456
|
+
if (isAbsolute(relativeValue) || relativeValue === ".." || relativeValue.startsWith("../")) {
|
|
457
|
+
return {};
|
|
458
|
+
}
|
|
459
|
+
return { [key]: machinePath(pathValue, projectRoot) } as Partial<Record<Key, string>>;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* Converts a report location to a project-relative path with slash separators. The project root is shown as ".".
|
|
464
|
+
*
|
|
465
|
+
* @param pathValue - File or directory path to normalize inside the project.
|
|
466
|
+
* @param projectRoot - Project root directory used to resolve absolute paths.
|
|
467
|
+
* @returns Normalized project-relative POSIX path, or "." when it resolves to projectRoot.
|
|
468
|
+
* @throws {Error} When a required location is empty or cannot be written as a path inside the project.
|
|
469
|
+
*/
|
|
470
|
+
function machinePath(pathValue: string, projectRoot: string): string {
|
|
471
|
+
const nativeRelative = isAbsolute(pathValue) ? relative(projectRoot, pathValue) : pathValue;
|
|
472
|
+
const relativeValue = nativeRelative.replaceAll("\\", "/");
|
|
473
|
+
// An input such as an absolute path on another drive must resolve inside the project before it can appear as a report location.
|
|
474
|
+
if (pathValue.length === 0 || relativeValue.startsWith("/") || /^[A-Za-z]:/u.test(relativeValue)) {
|
|
475
|
+
throw new Error(`Machine path must be project-relative: ${JSON.stringify(pathValue)}`);
|
|
476
|
+
}
|
|
477
|
+
const parts: string[] = [];
|
|
478
|
+
// Normalize each path segment so readers see the same file regardless of how the target was typed.
|
|
479
|
+
for (const part of relativeValue.split("/")) {
|
|
480
|
+
// Repeated slashes and explicit current-directory segments do not add a directory to the reported path.
|
|
481
|
+
if (part.length === 0 || part === ".") {
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
// A user can type a path containing ".." as long as it stays inside the selected project.
|
|
485
|
+
if (part === "..") {
|
|
486
|
+
// Moving above the selected project leaves no valid link for a consumer to follow.
|
|
487
|
+
if (parts.length === 0) {
|
|
488
|
+
throw new Error(`Machine path must stay inside the project root: ${JSON.stringify(pathValue)}`);
|
|
489
|
+
}
|
|
490
|
+
parts.pop();
|
|
491
|
+
continue;
|
|
492
|
+
}
|
|
493
|
+
parts.push(part);
|
|
494
|
+
}
|
|
495
|
+
return parts.length === 0 ? "." : parts.join("/");
|
|
61
496
|
}
|
|
62
497
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
498
|
+
/**
|
|
499
|
+
* Returns integerValue if it is a positive integer, or undefined for an absent or invalid location value.
|
|
500
|
+
* Callers omit optional coordinates and use line 1 when a finding has no valid start line.
|
|
501
|
+
*
|
|
502
|
+
* @param integerValue - Candidate coordinate value to validate as a positive integer.
|
|
503
|
+
* @returns Validated positive integer, or undefined when absent, non-integer, or non-positive.
|
|
504
|
+
*/
|
|
505
|
+
function positiveInteger(integerValue: number | undefined): number | undefined {
|
|
506
|
+
return integerValue !== undefined && Number.isInteger(integerValue) && integerValue > 0 ? integerValue : undefined;
|
|
67
507
|
}
|
|
68
508
|
|
|
69
|
-
|
|
70
|
-
* SARIF 2.1.0
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
*
|
|
509
|
+
/**
|
|
510
|
+
* Renders SARIF 2.1.0 for GitHub code-scanning uploads.
|
|
511
|
+
* The stable partialFingerprints.gruffFingerprint uses a baseline or computed identity to preserve cross-run alert matching.
|
|
512
|
+
* Results with no identity omit the field.
|
|
513
|
+
*
|
|
514
|
+
* @param report - Supplies findings, suppressions, diagnostics and run metadata.
|
|
515
|
+
* @returns Newline-terminated SARIF JSON.
|
|
74
516
|
*/
|
|
75
517
|
function renderSarif(report: AnalysisReport): string {
|
|
76
518
|
const rules = ruleDescriptors().map((descriptor) => ({
|
|
@@ -84,7 +526,7 @@ function renderSarif(report: AnalysisReport): string {
|
|
|
84
526
|
tier: "v0.1",
|
|
85
527
|
defaultSeverity: descriptor.severity,
|
|
86
528
|
confidence: descriptor.confidence,
|
|
87
|
-
defaultEnabled:
|
|
529
|
+
defaultEnabled: descriptor.isEnabledByDefault !== false,
|
|
88
530
|
...(typeof descriptor.threshold === "number" ? { threshold: descriptor.threshold } : {}),
|
|
89
531
|
...(descriptor.optionKeys ? { optionKeys: descriptor.optionKeys } : {}),
|
|
90
532
|
},
|
|
@@ -102,7 +544,21 @@ function renderSarif(report: AnalysisReport): string {
|
|
|
102
544
|
rules,
|
|
103
545
|
},
|
|
104
546
|
},
|
|
105
|
-
|
|
547
|
+
invocations: [
|
|
548
|
+
{
|
|
549
|
+
executionSuccessful: !report.diagnostics.some((diagnostic) => diagnostic.invalidatesRun !== false),
|
|
550
|
+
toolExecutionNotifications: report.diagnostics.map((diagnostic) => sarifDiagnostic(diagnostic, report.run.projectRoot)),
|
|
551
|
+
},
|
|
552
|
+
],
|
|
553
|
+
results: [
|
|
554
|
+
...report.findings.map((finding) => sarifResult(finding, ruleIndices)),
|
|
555
|
+
// A finding another tool's comment or a repeated claim removed stays a result marked suppressed, so a
|
|
556
|
+
// code-scanning tool shows it as suppressed rather than fixed (FAMILY-CONTRACT.md section 13c).
|
|
557
|
+
...(report.suppressedFindings ?? []).map(({ finding, justification }) => ({
|
|
558
|
+
...sarifResult(finding, ruleIndices),
|
|
559
|
+
suppressions: [{ kind: "inSource", justification }],
|
|
560
|
+
})),
|
|
561
|
+
],
|
|
106
562
|
properties: {
|
|
107
563
|
gruffSchemaVersion: report.schemaVersion,
|
|
108
564
|
generatedAt: report.run.generatedAt,
|
|
@@ -115,9 +571,64 @@ function renderSarif(report: AnalysisReport): string {
|
|
|
115
571
|
return `${JSON.stringify(sarif, null, 2)}\n`;
|
|
116
572
|
}
|
|
117
573
|
|
|
118
|
-
|
|
119
|
-
*
|
|
120
|
-
*
|
|
574
|
+
/**
|
|
575
|
+
* Return a SARIF invocation notification from the analysis diagnostic with a file anchor when a path is available.
|
|
576
|
+
*
|
|
577
|
+
* The severity contract treats an explicit non-invalidating flag as a note. An absent or true flag marks the run invalid and emits an error.
|
|
578
|
+
* A path without a line gives a file-level location, and in-project absolute paths are made relative to `projectRoot`.
|
|
579
|
+
*
|
|
580
|
+
* @param diagnostic - Analysis diagnostic supplying type, message, validity flag, and optional location.
|
|
581
|
+
* @param projectRoot - Project root used to normalize in-project file paths in both the artifact URI and message text.
|
|
582
|
+
* @returns SARIF toolExecutionNotification entry with level, message, properties, and optional location.
|
|
583
|
+
*/
|
|
584
|
+
function sarifDiagnostic(
|
|
585
|
+
diagnostic: AnalysisReport["diagnostics"][number],
|
|
586
|
+
projectRoot: string,
|
|
587
|
+
): Record<string, unknown> {
|
|
588
|
+
const fileEntry = diagnostic.filePath === undefined ? {} : optionalMachinePath("file", diagnostic.filePath, projectRoot);
|
|
589
|
+
// A path outside the project is left out, as in JSON, so the user's host folders never reach a SARIF upload.
|
|
590
|
+
const normalizedPath = fileEntry.file;
|
|
591
|
+
const message = diagnostic.filePath !== undefined && fileEntry.file !== undefined && diagnostic.filePath !== fileEntry.file
|
|
592
|
+
? diagnostic.message.replaceAll(diagnostic.filePath, fileEntry.file)
|
|
593
|
+
: diagnostic.message;
|
|
594
|
+
return {
|
|
595
|
+
descriptor: { id: diagnostic.diagnosticType },
|
|
596
|
+
level: diagnostic.invalidatesRun === false ? "note" : "error",
|
|
597
|
+
message: { text: message },
|
|
598
|
+
...(normalizedPath
|
|
599
|
+
? {
|
|
600
|
+
locations: [{
|
|
601
|
+
physicalLocation: {
|
|
602
|
+
artifactLocation: { uri: sarifUri(normalizedPath) },
|
|
603
|
+
...(diagnostic.line === undefined ? {} : { region: { startLine: diagnostic.line } }),
|
|
604
|
+
},
|
|
605
|
+
}],
|
|
606
|
+
}
|
|
607
|
+
: {}),
|
|
608
|
+
properties: { invalidatesRun: diagnostic.invalidatesRun !== false },
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* Preserve the stable alert identity because the analyser considers every finding together when assigning declaration ordinals.
|
|
614
|
+
*
|
|
615
|
+
* @param finding - Finding whose baseline identity is reused when present. Otherwise derive an identity from this finding alone.
|
|
616
|
+
* @returns A gruffFingerprint record, or undefined for a sensitive or unnameable finding so SARIF omits the fingerprint.
|
|
617
|
+
*/
|
|
618
|
+
function sarifPartialFingerprints(finding: Finding): Record<string, string> | undefined {
|
|
619
|
+
if (finding.baselineIdentity !== undefined) {
|
|
620
|
+
return { gruffFingerprint: finding.baselineIdentity };
|
|
621
|
+
}
|
|
622
|
+
const named = findingIdentities([finding])[0];
|
|
623
|
+
return named === undefined ? undefined : { gruffFingerprint: named.identity };
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* Build the SARIF result with the stable alert identity used by GitHub code scanning when available.
|
|
628
|
+
*
|
|
629
|
+
* @param finding - Native finding supplying the result message, location, severity, and properties.
|
|
630
|
+
* @param ruleIndices - Index of rule IDs in the SARIF rule list. An unknown ID leaves ruleIndex absent.
|
|
631
|
+
* @returns A SARIF result object with optional properties populated from the finding when available.
|
|
121
632
|
*/
|
|
122
633
|
function sarifResult(finding: Finding, ruleIndices: Map<string, number>): Record<string, unknown> {
|
|
123
634
|
const result: Record<string, unknown> = {
|
|
@@ -129,10 +640,12 @@ function sarifResult(finding: Finding, ruleIndices: Map<string, number>): Record
|
|
|
129
640
|
physicalLocation: sarifPhysicalLocation(finding),
|
|
130
641
|
},
|
|
131
642
|
],
|
|
132
|
-
partialFingerprints: {
|
|
133
|
-
gruffFingerprint: finding.fingerprint,
|
|
134
|
-
},
|
|
135
643
|
};
|
|
644
|
+
const fingerprints = sarifPartialFingerprints(finding);
|
|
645
|
+
// Leave the alert without a durable fingerprint when the finding is sensitive or cannot be named.
|
|
646
|
+
if (fingerprints !== undefined) {
|
|
647
|
+
result.partialFingerprints = fingerprints;
|
|
648
|
+
}
|
|
136
649
|
const ruleIndex = ruleIndices.get(finding.ruleId);
|
|
137
650
|
if (ruleIndex !== undefined) {
|
|
138
651
|
result.ruleIndex = ruleIndex;
|
|
@@ -157,10 +670,12 @@ function sarifResult(finding: Finding, ruleIndices: Map<string, number>): Record
|
|
|
157
670
|
return result;
|
|
158
671
|
}
|
|
159
672
|
|
|
160
|
-
|
|
161
|
-
*
|
|
162
|
-
*
|
|
163
|
-
*
|
|
673
|
+
/**
|
|
674
|
+
* Returns the stable SARIF location for the finding's file.
|
|
675
|
+
* With a line, the region includes any supplied column and end line. Without a line, the location identifies only the artifact.
|
|
676
|
+
*
|
|
677
|
+
* @param finding - Finding supplying the file path and optional line, column, and end line.
|
|
678
|
+
* @returns SARIF physicalLocation record with artifactLocation and optional region.
|
|
164
679
|
*/
|
|
165
680
|
function sarifPhysicalLocation(finding: Finding): Record<string, unknown> {
|
|
166
681
|
const location: Record<string, unknown> = {
|
|
@@ -183,8 +698,13 @@ function sarifPhysicalLocation(finding: Finding): Record<string, unknown> {
|
|
|
183
698
|
return location;
|
|
184
699
|
}
|
|
185
700
|
|
|
186
|
-
|
|
187
|
-
|
|
701
|
+
/**
|
|
702
|
+
* Returns a URI-encoded artifact path from filePath, replacing backslashes and stripping leading ./ segments.
|
|
703
|
+
* Encodes segments separately to preserve path separators; absolute and parent-relative paths are not rejected.
|
|
704
|
+
*
|
|
705
|
+
* @param filePath - Finding or diagnostic file path to convert to a SARIF artifact URI.
|
|
706
|
+
* @returns Slash-separated URI with each path segment percent-encoded.
|
|
707
|
+
*/
|
|
188
708
|
function sarifUri(filePath: string): string {
|
|
189
709
|
return filePath
|
|
190
710
|
.replaceAll("\\", "/")
|
|
@@ -194,7 +714,12 @@ function sarifUri(filePath: string): string {
|
|
|
194
714
|
.join("/");
|
|
195
715
|
}
|
|
196
716
|
|
|
197
|
-
|
|
717
|
+
/**
|
|
718
|
+
* Maps a gruff severity to its SARIF result level: error and warning are unchanged, and advisory returns note.
|
|
719
|
+
*
|
|
720
|
+
* @param severity - Native finding severity to translate into a SARIF level.
|
|
721
|
+
* @returns Matching SARIF notification/result level ("error", "warning", or "note").
|
|
722
|
+
*/
|
|
198
723
|
function sarifLevel(severity: Severity): "error" | "warning" | "note" {
|
|
199
724
|
switch (severity) {
|
|
200
725
|
case "error":
|
|
@@ -206,21 +731,25 @@ function sarifLevel(severity: Severity): "error" | "warning" | "note" {
|
|
|
206
731
|
}
|
|
207
732
|
}
|
|
208
733
|
|
|
209
|
-
|
|
210
|
-
*
|
|
211
|
-
*
|
|
212
|
-
*
|
|
734
|
+
/**
|
|
735
|
+
* Render a terminal digest; callers needing a stable machine contract use analyse --format=json.
|
|
736
|
+
*
|
|
737
|
+
* @param report - findings, scores, diagnostics, baseline, and suppression data to summarize
|
|
738
|
+
* @param elapsedMs - optional elapsed duration; omitted leaves out the Duration line
|
|
739
|
+
* @param pathLabel - path shown in the digest; omitted uses the report's project root
|
|
740
|
+
* @param top - number of leading clusters, rules, and file offenders to display; defaults to 10
|
|
741
|
+
* @returns terminal summary text followed by a newline
|
|
213
742
|
*/
|
|
214
743
|
function renderSummary(report: AnalysisReport, elapsedMs?: number, pathLabel?: string, top = 10): string {
|
|
215
|
-
const ruleCounts = countBy(report.findings, (finding) => finding.ruleId);
|
|
216
744
|
const pillarRows = buildPillarRows(report);
|
|
217
745
|
const breakdown = severityGradeBreakdown(report.findings);
|
|
746
|
+
// FAMILY-CONTRACT section 1 keeps the masthead, composite, and finding totals ahead of port-specific summary lines.
|
|
218
747
|
const lines = [
|
|
219
748
|
`gruff-ts ${report.tool.version} summary`,
|
|
749
|
+
compositeLine(report.score.composite, report.score.grade),
|
|
750
|
+
`Findings: ${report.summary.total} total · ${report.summary.error} error · ${report.summary.warning} warning · ${report.summary.advisory} advisory`,
|
|
220
751
|
`Path: ${pathLabel ?? report.run.projectRoot}`,
|
|
221
752
|
...(typeof elapsedMs === "number" ? [`Duration: ${formatSummaryDuration(elapsedMs)}`] : []),
|
|
222
|
-
`Composite: ${report.score.grade} (${report.score.composite.toFixed(2)} / 100)`,
|
|
223
|
-
`Findings: ${report.summary.total} total · ${report.summary.error} error · ${report.summary.warning} warning · ${report.summary.advisory} advisory`,
|
|
224
753
|
` Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
|
|
225
754
|
` Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
|
|
226
755
|
` Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
|
|
@@ -239,64 +768,50 @@ function renderSummary(report: AnalysisReport, elapsedMs?: number, pathLabel?: s
|
|
|
239
768
|
...(
|
|
240
769
|
report.score.topOffenders.length === 0
|
|
241
770
|
? ["- No file offenders."]
|
|
242
|
-
: report.score.topOffenders.slice(0, top).map((offender) =>
|
|
771
|
+
: report.score.topOffenders.slice(0, top).map((offender) => {
|
|
772
|
+
const quality = offender.score === null ? "n/a" : `${offender.score.toFixed(1)}/100`;
|
|
773
|
+
return `- ${offender.filePath}: ${offender.findings} findings, quality ${quality}`;
|
|
774
|
+
})
|
|
243
775
|
),
|
|
244
776
|
);
|
|
777
|
+
// FAMILY-CONTRACT.md section 13a requires a suppression audit on each surface that applies sensitive exclusions.
|
|
778
|
+
// Keep this extension below the canonical block; machine counts belong to the v3 summary projection.
|
|
779
|
+
lines.push(...renderTextSuppressionLines(report));
|
|
245
780
|
return `${lines.join("\n")}\n`;
|
|
246
781
|
}
|
|
247
782
|
|
|
248
|
-
|
|
249
|
-
* Renders the
|
|
250
|
-
*
|
|
251
|
-
*
|
|
252
|
-
*
|
|
253
|
-
*
|
|
254
|
-
*
|
|
783
|
+
/**
|
|
784
|
+
* Renders the JSON digest used by scripts that need the summary totals and exit outcome.
|
|
785
|
+
* Invariant: the digest uses gruff.summary.v3 and carries no individual finding list.
|
|
786
|
+
*
|
|
787
|
+
* @param report - Native analysis report supplying the common machine envelope.
|
|
788
|
+
* @param exitCode - gate result before filtering. Omit it to use the run's severity threshold.
|
|
789
|
+
* @returns indented summary JSON with a trailing newline. A scan with no findings still includes its run details.
|
|
255
790
|
*/
|
|
256
|
-
function renderSummaryJson(report: AnalysisReport,
|
|
257
|
-
|
|
258
|
-
const pillarRows = buildPillarRows(report);
|
|
259
|
-
const payload = {
|
|
260
|
-
schemaVersion: "gruff.summary.v2",
|
|
261
|
-
tool: report.tool,
|
|
262
|
-
scope: {
|
|
263
|
-
paths: pathLabel ?? report.run.projectRoot,
|
|
264
|
-
projectRoot: report.run.projectRoot,
|
|
265
|
-
analysedFiles: report.paths.analysedFiles,
|
|
266
|
-
ignoredPaths: report.paths.ignoredPaths.length,
|
|
267
|
-
missingPaths: report.paths.missingPaths.length,
|
|
268
|
-
diagnostics: report.diagnostics.length,
|
|
269
|
-
elapsedSeconds: typeof elapsedMs === "number" ? Number((elapsedMs / 1000).toFixed(3)) : undefined,
|
|
270
|
-
},
|
|
271
|
-
score: report.score,
|
|
272
|
-
findings: report.summary,
|
|
273
|
-
baseline: report.baseline,
|
|
274
|
-
pillars: pillarRows.map((row) => ({
|
|
275
|
-
pillar: row.pillar,
|
|
276
|
-
grade: row.grade,
|
|
277
|
-
score: row.score,
|
|
278
|
-
penalty: row.penalty,
|
|
279
|
-
applicable: row.isApplicable,
|
|
280
|
-
findings: row.findings,
|
|
281
|
-
advisory: row.advisory,
|
|
282
|
-
warning: row.warning,
|
|
283
|
-
error: row.error,
|
|
284
|
-
})),
|
|
285
|
-
topRules: renderRankedCountRows(ruleCounts, top),
|
|
286
|
-
topOffenders: report.score.topOffenders.slice(0, top),
|
|
287
|
-
};
|
|
288
|
-
return `${JSON.stringify(payload, null, 2)}\n`;
|
|
791
|
+
function renderSummaryJson(report: AnalysisReport, exitCode?: number): string {
|
|
792
|
+
return `${JSON.stringify(toJsonSummary(report, exitCode), null, 2)}\n`;
|
|
289
793
|
}
|
|
290
794
|
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
795
|
+
/**
|
|
796
|
+
* Returns a diagnostic row shared by terminal summaries and text reports, with type and message from diagnostic.
|
|
797
|
+
* Appends the parenthesized filePath only when present; otherwise the row has no location suffix.
|
|
798
|
+
* Keep this shared shape stable for scripts that grep both output surfaces.
|
|
799
|
+
*
|
|
800
|
+
* @param diagnostic - Scan diagnostic providing diagnosticType, message, and optional filePath.
|
|
801
|
+
* @returns Formatted single-line diagnostic bullet for terminal output.
|
|
802
|
+
*/
|
|
294
803
|
function summaryDiagnosticLine(diagnostic: AnalysisReport["diagnostics"][number]): string {
|
|
295
804
|
const location = diagnostic.filePath ? ` (${diagnostic.filePath})` : "";
|
|
296
805
|
return `- ${diagnostic.diagnosticType}: ${diagnostic.message}${location}`;
|
|
297
806
|
}
|
|
298
807
|
|
|
299
|
-
|
|
808
|
+
/**
|
|
809
|
+
* Return the summary line from the report's baseline metadata under the baseline contract.
|
|
810
|
+
* A generated baseline leaves current findings visible. An applied baseline reports its source and suppression count.
|
|
811
|
+
*
|
|
812
|
+
* @param baseline - Applied or generated baseline metadata attached to the analysis report.
|
|
813
|
+
* @returns Single-line human-readable baseline status summary.
|
|
814
|
+
*/
|
|
300
815
|
function summaryBaselineLine(baseline: NonNullable<AnalysisReport["baseline"]>): string {
|
|
301
816
|
if (baseline.generated) {
|
|
302
817
|
return `Baseline: generated ${baseline.path}; current findings still shown`;
|
|
@@ -305,7 +820,13 @@ function summaryBaselineLine(baseline: NonNullable<AnalysisReport["baseline"]>):
|
|
|
305
820
|
return `Baseline: ${baseline.source} ${baseline.path}; suppressed ${baseline.suppressed} ${findingNoun}`;
|
|
306
821
|
}
|
|
307
822
|
|
|
308
|
-
|
|
823
|
+
/**
|
|
824
|
+
* Returns elapsedMs as a summary duration, rounding to whole milliseconds below one second and two-decimal seconds otherwise.
|
|
825
|
+
* Negative durations display as 0ms.
|
|
826
|
+
*
|
|
827
|
+
* @param elapsedMs - Measured run duration in milliseconds.
|
|
828
|
+
* @returns Human-readable duration formatted in milliseconds or seconds.
|
|
829
|
+
*/
|
|
309
830
|
function formatSummaryDuration(elapsedMs: number): string {
|
|
310
831
|
const bounded = Math.max(0, elapsedMs);
|
|
311
832
|
if (bounded < 1000) {
|
|
@@ -314,23 +835,12 @@ function formatSummaryDuration(elapsedMs: number): string {
|
|
|
314
835
|
return `${(bounded / 1000).toFixed(2)}s`;
|
|
315
836
|
}
|
|
316
837
|
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
return counts;
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
/*
|
|
327
|
-
* Text renderer for the `Pillars` block in `gruff-ts summary`. Column widths are computed from the
|
|
328
|
-
* actual data (max pillar-name length, max digits per severity column) with a 3-char minimum value
|
|
329
|
-
* width so single-digit cells still leave visual breathing room before the next column. This
|
|
330
|
-
* matches the cross-port canonical byte-for-byte layout: leading "Pillars" header, 2-space row
|
|
331
|
-
* indent, pillar name padded to max-name-width + 1 space, single-letter grade, 1-space separator,
|
|
332
|
-
* score right-aligned in 6 chars with 2 decimals, then findings/advisory/warning/error cells
|
|
333
|
-
* separated by 3 spaces and trimmed of trailing whitespace on the final column.
|
|
838
|
+
/**
|
|
839
|
+
* Render the terminal Pillars block with a two-space row indent and three spaces between count cells.
|
|
840
|
+
* Names and counts expand to fit; count cells use at least three characters and scores use two decimals in at least six (or `n/a` when unevaluated).
|
|
841
|
+
*
|
|
842
|
+
* @param rows - pillar summaries to display in their supplied order; an empty list renders a `(none)` placeholder
|
|
843
|
+
* @returns Heading and formatted rows, or a heading and `(none)` marker when rows is empty.
|
|
334
844
|
*/
|
|
335
845
|
function renderPillarsBlock(rows: PillarRow[]): string[] {
|
|
336
846
|
if (rows.length === 0) {
|
|
@@ -344,7 +854,7 @@ function renderPillarsBlock(rows: PillarRow[]): string[] {
|
|
|
344
854
|
const lines = ["Pillars"];
|
|
345
855
|
for (const row of rows) {
|
|
346
856
|
const name = row.pillar.padEnd(nameWidth);
|
|
347
|
-
const score = row.score.toFixed(2).padStart(6);
|
|
857
|
+
const score = (row.score === null ? "n/a" : row.score.toFixed(2)).padStart(6);
|
|
348
858
|
const findingsCell = `findings=${String(row.findings).padEnd(findingsWidth)}`;
|
|
349
859
|
const advisoryCell = `advisory=${String(row.advisory).padEnd(advisoryWidth)}`;
|
|
350
860
|
const warningCell = `warning=${String(row.warning).padEnd(warningWidth)}`;
|
|
@@ -355,12 +865,12 @@ function renderPillarsBlock(rows: PillarRow[]): string[] {
|
|
|
355
865
|
return lines;
|
|
356
866
|
}
|
|
357
867
|
|
|
358
|
-
|
|
359
|
-
*
|
|
360
|
-
*
|
|
361
|
-
*
|
|
362
|
-
*
|
|
363
|
-
*
|
|
868
|
+
/**
|
|
869
|
+
* Show severity counts and short descriptions so operators can triage the most frequent rules first.
|
|
870
|
+
*
|
|
871
|
+
* @param findings - Findings to group by rule and tally by severity.
|
|
872
|
+
* @param limit - Cap on ranked rows. Omit it to show every rule with findings.
|
|
873
|
+
* @returns Stable bullets by descending count then ascending rule ID. No findings give a placeholder. Unknown rules have blank descriptions.
|
|
364
874
|
*/
|
|
365
875
|
function renderRankedRuleRows(findings: Finding[], limit?: number): string[] {
|
|
366
876
|
const severities = countRuleSeverities(findings);
|
|
@@ -377,45 +887,33 @@ function renderRankedRuleRows(findings: Finding[], limit?: number): string[] {
|
|
|
377
887
|
});
|
|
378
888
|
}
|
|
379
889
|
|
|
380
|
-
|
|
381
|
-
* 60-char description budget that keeps the rule-row line under ~100 columns even with the longest
|
|
382
|
-
* ruleId and severity-split. The trailing ellipsis is a single Unicode glyph so terminals that
|
|
383
|
-
* don't render `...` still see the truncation marker.
|
|
384
|
-
*/
|
|
890
|
+
// 60-char description budget that keeps the rule-row line compact even with long rule IDs; uses a single Unicode ellipsis glyph on truncation.
|
|
385
891
|
const DESCRIPTION_BODY_LIMIT = 60;
|
|
386
892
|
|
|
387
|
-
|
|
388
|
-
|
|
893
|
+
/**
|
|
894
|
+
* Returns the rule description text unchanged when it fits DESCRIPTION_BODY_LIMIT.
|
|
895
|
+
* Longer text is cut to that many UTF-16 code units, trimmed at the end, and given an ellipsis; row width remains variable.
|
|
896
|
+
*
|
|
897
|
+
* @param text - Raw rule description text to fit within the summary row budget.
|
|
898
|
+
* @returns Original description or a trimmed prefix followed by a single ellipsis character.
|
|
899
|
+
*/
|
|
389
900
|
function truncateDescription(text: string): string {
|
|
390
901
|
return text.length <= DESCRIPTION_BODY_LIMIT ? text : `${text.slice(0, DESCRIPTION_BODY_LIMIT).trimEnd()}…`;
|
|
391
902
|
}
|
|
392
903
|
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
.map(([key, count]) => `- ${key}: ${count}`);
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
function renderRankedCountRows<T extends string>(counts: Map<T, number>, limit?: number): Array<{ name: T; count: number }> {
|
|
404
|
-
return [...counts.entries()]
|
|
405
|
-
.sort(([leftKey, leftCount], [rightKey, rightCount]) => rightCount - leftCount || leftKey.localeCompare(rightKey))
|
|
406
|
-
.slice(0, limit ?? counts.size)
|
|
407
|
-
.map(([name, count]) => ({ name, count }));
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
/*
|
|
411
|
-
* Default terminal output. Findings are listed verbatim (no truncation) - the analyser keeps them
|
|
412
|
-
* sorted into the stable order, so piping into `grep` produces deterministic results.
|
|
904
|
+
/**
|
|
905
|
+
* Returns the supplied analysis report as newline-terminated terminal text.
|
|
906
|
+
* Lists full finding messages in the supplied stable order so that grep sees consistent rows.
|
|
907
|
+
* A finding with no source line is displayed at line 1.
|
|
908
|
+
*
|
|
909
|
+
* @param report - Native analysis report supplying scores, diagnostics, notes, findings, suppressions, and baseline metadata.
|
|
910
|
+
* @returns Complete terminal report text ending with a newline.
|
|
413
911
|
*/
|
|
414
912
|
function renderText(report: AnalysisReport): string {
|
|
415
913
|
const breakdown = severityGradeBreakdown(report.findings);
|
|
416
914
|
const lines = [
|
|
417
915
|
`gruff-ts ${report.tool.version} analyse`,
|
|
418
|
-
|
|
916
|
+
compositeLine(report.score.composite, report.score.grade),
|
|
419
917
|
`Findings: ${report.summary.total} total · ${report.summary.error} error · ${report.summary.warning} warning · ${report.summary.advisory} advisory`,
|
|
420
918
|
` Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
|
|
421
919
|
` Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
|
|
@@ -435,23 +933,70 @@ function renderText(report: AnalysisReport): string {
|
|
|
435
933
|
if (report.findings.length >= OUTPUT_VOLUME_HINT_THRESHOLD) {
|
|
436
934
|
lines.push("", `Tip: ${report.findings.length} findings is more than a flat list usefully shows. Try \`gruff-ts summary --top=20\` for a per-rule digest.`);
|
|
437
935
|
}
|
|
936
|
+
lines.push(...renderTextSuppressionLines(report));
|
|
937
|
+
// Under ADR-006, name the applied baseline and its selection source so hidden findings never read as a clean scan.
|
|
938
|
+
if (report.baseline !== undefined && !report.baseline.generated) {
|
|
939
|
+
lines.push("", summaryBaselineLine(report.baseline));
|
|
940
|
+
}
|
|
438
941
|
return `${lines.join("\n")}\n`;
|
|
439
942
|
}
|
|
440
943
|
|
|
441
|
-
|
|
442
|
-
*
|
|
443
|
-
*
|
|
444
|
-
*
|
|
445
|
-
*
|
|
446
|
-
*
|
|
447
|
-
|
|
944
|
+
/**
|
|
945
|
+
* Render the suppression summary using the stable text contract in gruff-rs/src/render/text.rs.
|
|
946
|
+
* Each positive row shows the exclusion label, rule, count, and rationale without printing matched evidence.
|
|
947
|
+
*
|
|
948
|
+
* @param report - Analysis report whose suppression rows supply the total and details.
|
|
949
|
+
* @returns A separator and one summary line when the total is positive, or an empty list when nothing was suppressed.
|
|
950
|
+
*/
|
|
951
|
+
function renderTextSuppressionLines(report: AnalysisReport): string[] {
|
|
952
|
+
const total = totalSuppressedFindings(report.suppressions);
|
|
953
|
+
// Nothing suppressed means no line at all, matching the reference renderer.
|
|
954
|
+
if (total === 0) {
|
|
955
|
+
return [];
|
|
956
|
+
}
|
|
957
|
+
const details = report.suppressions
|
|
958
|
+
.filter((summary) => summary.suppressed > 0)
|
|
959
|
+
// Built-in and section 13c rows put the first covered path in the label brackets. A missing path leaves the brackets empty.
|
|
960
|
+
.map((summary) => (summary.source === undefined
|
|
961
|
+
? `sensitiveExclusions[${summary.index}] ${summary.rule}: ${summary.suppressed} (${summary.reason})`
|
|
962
|
+
: `${summary.source === "built-in" ? "builtInTestPath" : summary.source}[${summary.paths[0] ?? ""}] ${summary.rule}: ${summary.suppressed} (${summary.reason})`))
|
|
963
|
+
.join("; ");
|
|
964
|
+
return ["", `Suppressed findings: ${total} via ${details}`];
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
/**
|
|
968
|
+
* Keep the Pillars table ahead of individual findings so readers see the breakdown in a report preview.
|
|
969
|
+
* Use the shared pillar rows to preserve deterministic order across formats.
|
|
970
|
+
*
|
|
971
|
+
* @param report - Native analysis report supplying the score, diagnostics, pillars, and findings in display order.
|
|
972
|
+
* @returns Markdown with diagnostics when present and at most the first 50 individual findings.
|
|
448
973
|
*/
|
|
449
974
|
function renderMarkdown(report: AnalysisReport): string {
|
|
450
975
|
const breakdown = severityGradeBreakdown(report.findings);
|
|
976
|
+
// Keep repository text from changing the Markdown structure. An unlocated finding uses line 1 as its display anchor.
|
|
977
|
+
const findingRows = report.findings
|
|
978
|
+
.slice(0, 50)
|
|
979
|
+
.map((finding) => `- ${markdownInlineCode(finding.ruleId)} ${markdownInlineCode(finding.filePath)}:${finding.line ?? 1} - ${escapeMarkdownFindingMessage(finding.message)}`);
|
|
980
|
+
const diagnosticRows = report.diagnostics.length === 0
|
|
981
|
+
? []
|
|
982
|
+
: [
|
|
983
|
+
"## Diagnostics",
|
|
984
|
+
"",
|
|
985
|
+
...report.diagnostics.map((diagnostic) => {
|
|
986
|
+
const diagnosticLocation = diagnostic.filePath
|
|
987
|
+
? `${markdownInlineCode(diagnostic.filePath)}:${diagnostic.line ?? 1} `
|
|
988
|
+
: "";
|
|
989
|
+
return `- ${markdownInlineCode(diagnostic.diagnosticType)} ${diagnosticLocation}- ${escapeMarkdownFindingMessage(diagnostic.message)}`;
|
|
990
|
+
}),
|
|
991
|
+
"",
|
|
992
|
+
];
|
|
451
993
|
return [
|
|
452
994
|
"# gruff-ts report",
|
|
453
995
|
"",
|
|
454
|
-
|
|
996
|
+
// A missing composite score or grade uses the same nothing-evaluated wording as the text report.
|
|
997
|
+
report.score.composite === null || report.score.grade === null
|
|
998
|
+
? "Composite: **n/a (nothing evaluated)**"
|
|
999
|
+
: `Composite: **${report.score.grade} (${report.score.composite.toFixed(2)} / 100)**`,
|
|
455
1000
|
`- Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
|
|
456
1001
|
`- Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
|
|
457
1002
|
`- Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
|
|
@@ -459,19 +1004,18 @@ function renderMarkdown(report: AnalysisReport): string {
|
|
|
459
1004
|
"",
|
|
460
1005
|
`Findings: ${report.summary.total} total · ${report.summary.error} error · ${report.summary.warning} warning · ${report.summary.advisory} advisory`,
|
|
461
1006
|
"",
|
|
1007
|
+
...diagnosticRows,
|
|
462
1008
|
...renderMarkdownPillarsTable(buildPillarRows(report)),
|
|
463
1009
|
"",
|
|
464
|
-
...
|
|
1010
|
+
...findingRows,
|
|
465
1011
|
].join("\n");
|
|
466
1012
|
}
|
|
467
1013
|
|
|
468
|
-
|
|
469
|
-
*
|
|
470
|
-
*
|
|
471
|
-
*
|
|
472
|
-
*
|
|
473
|
-
* ASC); scores render with two decimals; pipes in pillar/grade cells are escaped so a future
|
|
474
|
-
* pillar/grade name containing `|` cannot break the table.
|
|
1014
|
+
/**
|
|
1015
|
+
* Preserve the shared seven-column Markdown table contract, including two-decimal scores and escaped cell pipes.
|
|
1016
|
+
*
|
|
1017
|
+
* @param rows - Pillar rows in caller order. buildPillarRows supplies findings DESC, then pillar ASC.
|
|
1018
|
+
* @returns Table lines including a placeholder row when there are no pillars to list.
|
|
475
1019
|
*/
|
|
476
1020
|
function renderMarkdownPillarsTable(rows: PillarRow[]): string[] {
|
|
477
1021
|
const lines = [
|
|
@@ -485,20 +1029,67 @@ function renderMarkdownPillarsTable(rows: PillarRow[]): string[] {
|
|
|
485
1029
|
return lines;
|
|
486
1030
|
}
|
|
487
1031
|
for (const row of rows) {
|
|
1032
|
+
const scoreText = row.score === null ? "n/a" : row.score.toFixed(2);
|
|
488
1033
|
lines.push(
|
|
489
|
-
`| ${escapeMarkdownCell(row.pillar)} | ${escapeMarkdownCell(row.grade)} | ${
|
|
1034
|
+
`| ${escapeMarkdownCell(row.pillar)} | ${escapeMarkdownCell(row.grade)} | ${scoreText} | ${row.findings} | ${row.advisory} | ${row.warning} | ${row.error} |`,
|
|
490
1035
|
);
|
|
491
1036
|
}
|
|
492
1037
|
return lines;
|
|
493
1038
|
}
|
|
494
1039
|
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
1040
|
+
/**
|
|
1041
|
+
* Returns cell with pipe characters escaped for a Markdown table cell.
|
|
1042
|
+
* Callers supply single-line pillar and grade labels; this helper does not escape other Markdown syntax.
|
|
1043
|
+
*
|
|
1044
|
+
* @param cell - Single-line label placed inside a Markdown table column.
|
|
1045
|
+
* @returns Escaped cell text with literal pipe characters prefixed by a backslash.
|
|
1046
|
+
*/
|
|
498
1047
|
function escapeMarkdownCell(cell: string): string {
|
|
499
1048
|
return cell.replaceAll("|", "\\|");
|
|
500
1049
|
}
|
|
501
1050
|
|
|
1051
|
+
/**
|
|
1052
|
+
* Wraps a repository-controlled label in a CommonMark code span for PR and issue reports.
|
|
1053
|
+
* A fence longer than the label's longest backtick run keeps the label inside one span.
|
|
1054
|
+
*
|
|
1055
|
+
* @param reportLabel - Rule ID, diagnostic type, or file path label to wrap in inline code.
|
|
1056
|
+
* @returns Single-line CommonMark inline code span safely fenced around the label.
|
|
1057
|
+
*/
|
|
1058
|
+
function markdownInlineCode(reportLabel: string): string {
|
|
1059
|
+
const singleLineLabel = reportLabel.replace(/[\r\n]+/g, " ");
|
|
1060
|
+
// An empty analyzer label still needs content so Markdown does not merge its two fences.
|
|
1061
|
+
const visibleLabel = singleLineLabel.length === 0 ? " " : singleLineLabel;
|
|
1062
|
+
const fenceLength = Math.max(1, ...Array.from(visibleLabel.matchAll(/`+/g), (match) => match[0].length + 1));
|
|
1063
|
+
const fence = "`".repeat(fenceLength);
|
|
1064
|
+
// Edge backticks need padding so CommonMark can distinguish label content from the fence.
|
|
1065
|
+
const paddedLabel = visibleLabel.startsWith("`") || visibleLabel.endsWith("`") ? ` ${visibleLabel} ` : visibleLabel;
|
|
1066
|
+
return `${fence}${paddedLabel}${fence}`;
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
/**
|
|
1070
|
+
* Escapes finding and diagnostic messages to preserve the Markdown report's stable entry layout.
|
|
1071
|
+
* Line breaks collapse so a message cannot start a new heading, list, or HTML block.
|
|
1072
|
+
*
|
|
1073
|
+
* @param findingMessage - Raw finding or diagnostic message text to sanitize for Markdown output.
|
|
1074
|
+
* @returns Single-line message with HTML entities and Markdown control characters escaped.
|
|
1075
|
+
*/
|
|
1076
|
+
function escapeMarkdownFindingMessage(findingMessage: string): string {
|
|
1077
|
+
return findingMessage
|
|
1078
|
+
.replace(/[\r\n]+/g, " ")
|
|
1079
|
+
.replaceAll("&", "&")
|
|
1080
|
+
.replaceAll("<", "<")
|
|
1081
|
+
.replaceAll(">", ">")
|
|
1082
|
+
.replaceAll("\\", "\\\\")
|
|
1083
|
+
.replaceAll("`", "\\`")
|
|
1084
|
+
.replaceAll("*", "\\*")
|
|
1085
|
+
.replaceAll("_", "\\_")
|
|
1086
|
+
.replaceAll("[", "\\[")
|
|
1087
|
+
.replaceAll("]", "\\]")
|
|
1088
|
+
.replaceAll("|", "\\|")
|
|
1089
|
+
.replaceAll("#", "\\#")
|
|
1090
|
+
.replaceAll("~", "\\~");
|
|
1091
|
+
}
|
|
1092
|
+
|
|
502
1093
|
// Render-only summary of overlapping complexity findings for one function symbol.
|
|
503
1094
|
interface ComplexityCluster {
|
|
504
1095
|
filePath: string;
|
|
@@ -506,9 +1097,16 @@ interface ComplexityCluster {
|
|
|
506
1097
|
ruleIds: string[];
|
|
507
1098
|
}
|
|
508
1099
|
|
|
509
|
-
const CORRELATED_COMPLEXITY_RULE_IDS = new Set(["complexity.
|
|
1100
|
+
const CORRELATED_COMPLEXITY_RULE_IDS = new Set(["complexity.cyclomatic", "size.function-length"]);
|
|
510
1101
|
|
|
511
|
-
|
|
1102
|
+
/**
|
|
1103
|
+
* Returns a text heading and one line per selected complexity cluster from the supplied findings, in stable rank order.
|
|
1104
|
+
* The limit is the end position in that list and defaults to 10. An empty selection returns no heading or rows.
|
|
1105
|
+
*
|
|
1106
|
+
* @param findings - Analysis findings inspected for overlapping complexity rules on the same symbol.
|
|
1107
|
+
* @param limit - Maximum number of clusters to render; defaults to 10.
|
|
1108
|
+
* @returns Heading and cluster bullet lines, or empty when no symbol has overlapping complexity findings.
|
|
1109
|
+
*/
|
|
512
1110
|
function renderComplexityClusterLines(findings: Finding[], limit = 10): string[] {
|
|
513
1111
|
const clusters = complexityClusters(findings).slice(0, limit);
|
|
514
1112
|
if (clusters.length === 0) {
|
|
@@ -520,21 +1118,49 @@ function renderComplexityClusterLines(findings: Finding[], limit = 10): string[]
|
|
|
520
1118
|
];
|
|
521
1119
|
}
|
|
522
1120
|
|
|
523
|
-
|
|
1121
|
+
/**
|
|
1122
|
+
* Returns the Markdown heading and rows for all clusters in the supplied findings, using the same grouping contract as text output.
|
|
1123
|
+
*
|
|
1124
|
+
* @param findings - Analysis findings inspected for overlapping complexity rules on the same symbol.
|
|
1125
|
+
* @returns Markdown section heading and bullet lines, or empty when no clusters exist.
|
|
1126
|
+
*/
|
|
524
1127
|
function renderMarkdownComplexityClusterLines(findings: Finding[]): string[] {
|
|
525
1128
|
const clusters = complexityClusters(findings);
|
|
1129
|
+
// A scan with no overlapping complexity findings should not show an empty review section.
|
|
526
1130
|
if (clusters.length === 0) {
|
|
527
1131
|
return [];
|
|
528
1132
|
}
|
|
1133
|
+
// Repository paths and symbols stay inside one code span in the reviewer's cluster list.
|
|
1134
|
+
const clusterRows = clusters.map(renderMarkdownComplexityClusterRow);
|
|
529
1135
|
return [
|
|
530
1136
|
"",
|
|
531
1137
|
"## Correlated Complexity Clusters",
|
|
532
1138
|
"",
|
|
533
|
-
...
|
|
1139
|
+
...clusterRows,
|
|
534
1140
|
];
|
|
535
1141
|
}
|
|
536
1142
|
|
|
537
|
-
|
|
1143
|
+
/**
|
|
1144
|
+
* Formats one correlated cluster for the Markdown list a reviewer sees in pull-request output.
|
|
1145
|
+
*
|
|
1146
|
+
* @param cluster - Correlated complexity cluster identifying a file, symbol, and linked rule IDs.
|
|
1147
|
+
* @returns Markdown list item showing the inline-coded symbol anchor, finding count, and rule IDs.
|
|
1148
|
+
*/
|
|
1149
|
+
function renderMarkdownComplexityClusterRow(cluster: ComplexityCluster): string {
|
|
1150
|
+
const clusterLabel = `${cluster.filePath}#${cluster.symbol}`;
|
|
1151
|
+
// Every linked rule remains its own code span so a reviewer can copy its exact identifier.
|
|
1152
|
+
const linkedRuleLabels = cluster.ruleIds.map((ruleId) => markdownInlineCode(ruleId)).join(", ");
|
|
1153
|
+
return `- ${markdownInlineCode(clusterLabel)}: ${cluster.ruleIds.length} linked findings (${linkedRuleLabels})`;
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
/**
|
|
1157
|
+
* Returns stable clusters from the supplied complexity findings so that renderers explain overlaps consistently.
|
|
1158
|
+
* A file and symbol qualify only when at least two distinct correlated rules fired there. Otherwise no cluster is emitted for that pair.
|
|
1159
|
+
* The list is empty without a qualifying overlap. Clusters rank by descending rule count, then path and symbol, with sorted rule IDs.
|
|
1160
|
+
*
|
|
1161
|
+
* @param findings - Findings to group by file path and symbol across correlated complexity rules.
|
|
1162
|
+
* @returns Ranked list of complexity clusters with sorted rule IDs, or empty when none qualify.
|
|
1163
|
+
*/
|
|
538
1164
|
function complexityClusters(findings: Finding[]): ComplexityCluster[] {
|
|
539
1165
|
const bySymbol = new Map<string, ComplexityCluster>();
|
|
540
1166
|
for (const finding of findings) {
|
|
@@ -554,34 +1180,77 @@ function complexityClusters(findings: Finding[]): ComplexityCluster[] {
|
|
|
554
1180
|
.sort((left, right) => right.ruleIds.length - left.ruleIds.length || left.filePath.localeCompare(right.filePath) || left.symbol.localeCompare(right.symbol));
|
|
555
1181
|
}
|
|
556
1182
|
|
|
557
|
-
|
|
558
|
-
|
|
1183
|
+
/**
|
|
1184
|
+
* Returns newline-separated GitHub Actions annotations for report diagnostics and findings; missing finding lines use line 1.
|
|
1185
|
+
* File paths are normalized, and file and title values must be command-escaped because commas and colons are delimiters.
|
|
1186
|
+
* Returns an empty string when the report has neither diagnostics nor findings.
|
|
1187
|
+
*
|
|
1188
|
+
* @param report - Native analysis report supplying diagnostics and findings to annotate.
|
|
1189
|
+
* @returns Newline-joined GitHub workflow command lines, or an empty string when there is nothing to report.
|
|
1190
|
+
*/
|
|
559
1191
|
function renderGithub(report: AnalysisReport): string {
|
|
560
|
-
return
|
|
561
|
-
.map(
|
|
1192
|
+
return [
|
|
1193
|
+
...report.diagnostics.map(githubDiagnostic),
|
|
1194
|
+
...report.findings.map((finding) => `::${githubLevel(finding.severity)} file=${escapeCommandProperty(githubAnnotationPath(finding.filePath))},line=${finding.line ?? 1},title=${escapeCommandProperty(finding.ruleId)}::${escapeCommand(finding.message)}`),
|
|
1195
|
+
]
|
|
562
1196
|
.join("\n");
|
|
563
1197
|
}
|
|
564
1198
|
|
|
565
|
-
|
|
566
|
-
|
|
1199
|
+
/**
|
|
1200
|
+
* Returns a GitHub Actions annotation for the supplied run diagnostic. The level contract uses notice only when invalidatesRun is false.
|
|
1201
|
+
* Without a file path the annotation has no location. With a file path and no line, it defaults to line 1.
|
|
1202
|
+
*
|
|
1203
|
+
* @param diagnostic - Analysis diagnostic supplying type, message, validity flag, and optional location.
|
|
1204
|
+
* @returns Single GitHub Actions workflow command for the diagnostic.
|
|
1205
|
+
*/
|
|
1206
|
+
function githubDiagnostic(diagnostic: AnalysisReport["diagnostics"][number]): string {
|
|
1207
|
+
const level = diagnostic.invalidatesRun === false ? "notice" : "error";
|
|
1208
|
+
const location = diagnostic.filePath
|
|
1209
|
+
? ` file=${escapeCommandProperty(githubAnnotationPath(diagnostic.filePath))},line=${diagnostic.line ?? 1},`
|
|
1210
|
+
: " ";
|
|
1211
|
+
return `::${level}${location}title=${escapeCommandProperty(diagnostic.diagnosticType)}::${escapeCommand(diagnostic.message)}`;
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
/**
|
|
1215
|
+
* Returns filePath for a GitHub annotation with forward slashes and without leading dot-slash segments.
|
|
1216
|
+
* Equivalent slash and dot-prefix spellings share one path. Absolute paths and parent segments are preserved.
|
|
1217
|
+
*
|
|
1218
|
+
* @param filePath - Raw file path from a finding or diagnostic.
|
|
1219
|
+
* @returns Normalized forward-slash path stripped of leading dot-slash prefixes.
|
|
1220
|
+
*/
|
|
567
1221
|
function githubAnnotationPath(filePath: string): string {
|
|
568
1222
|
return filePath.replaceAll("\\", "/").replace(/^(?:\.\/)+/, "");
|
|
569
1223
|
}
|
|
570
1224
|
|
|
571
|
-
|
|
572
|
-
|
|
1225
|
+
/**
|
|
1226
|
+
* Three GitHub annotation levels - gruff's "advisory" collapses to "notice" because Actions has
|
|
1227
|
+
* no fourth tier and "notice" is the documented soft-warning level.
|
|
1228
|
+
*
|
|
1229
|
+
* @param severity - Native finding severity to map onto GitHub Actions annotation levels.
|
|
1230
|
+
* @returns Corresponding GitHub annotation command name ("error", "warning", or "notice").
|
|
1231
|
+
*/
|
|
573
1232
|
function githubLevel(severity: Severity): "notice" | "warning" | "error" {
|
|
574
1233
|
return severity === "error" ? "error" : severity === "warning" ? "warning" : "notice";
|
|
575
1234
|
}
|
|
576
1235
|
|
|
577
|
-
|
|
578
|
-
|
|
1236
|
+
/**
|
|
1237
|
+
* Returns commandText with the base GitHub Actions escapes for messages and property values. % must be first, otherwise the
|
|
1238
|
+
* %0A replacement would itself be re-encoded.
|
|
1239
|
+
*
|
|
1240
|
+
* @param commandText - Raw message or property value emitted in a GitHub workflow command.
|
|
1241
|
+
* @returns Percent-escaped text safe for GitHub Actions workflow command payloads.
|
|
1242
|
+
*/
|
|
579
1243
|
function escapeCommand(commandText: string): string {
|
|
580
1244
|
return commandText.replaceAll("%", "%25").replaceAll("\n", "%0A").replaceAll("\r", "%0D");
|
|
581
1245
|
}
|
|
582
1246
|
|
|
583
|
-
|
|
584
|
-
|
|
1247
|
+
/**
|
|
1248
|
+
* Returns propertyText with the base command escapes plus colon and comma escapes because GitHub workflow
|
|
1249
|
+
* commands use commas between properties and double colons around the command header.
|
|
1250
|
+
*
|
|
1251
|
+
* @param propertyText - Raw property value such as a file path or rule title for a workflow command.
|
|
1252
|
+
* @returns Escaped property value safe for key-value pairs inside a GitHub Actions command header.
|
|
1253
|
+
*/
|
|
585
1254
|
function escapeCommandProperty(propertyText: string): string {
|
|
586
1255
|
return escapeCommand(propertyText).replaceAll(":", "%3A").replaceAll(",", "%2C");
|
|
587
1256
|
}
|