@blundergoat/gruff-ts 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +82 -0
- package/CONTRIBUTING.md +32 -25
- package/README.md +49 -50
- package/SECURITY.md +18 -31
- package/UPGRADING.md +101 -0
- package/bin/gruff-ts +3 -0
- package/docs/README.md +11 -10
- package/docs/agent-hook.md +32 -35
- package/docs/ci-integration.md +38 -24
- package/docs/configuration.md +160 -89
- package/docs/dashboard.md +12 -13
- package/docs/output-formats.md +100 -25
- package/docs/philosophy.md +2 -2
- package/docs/reports-and-ci.md +14 -172
- package/docs/rules.md +126 -98
- package/package.json +10 -8
- package/src/analyser.ts +817 -323
- package/src/baseline-file.ts +867 -0
- package/src/baseline-identity.ts +463 -0
- package/src/baseline-options.ts +139 -34
- package/src/baseline.ts +62 -68
- package/src/blocks.ts +512 -336
- package/src/changed-regions.ts +380 -79
- package/src/check-ignore.ts +28 -13
- package/src/class-rules.ts +445 -436
- package/src/cli-program.ts +915 -172
- package/src/cli.ts +9 -3
- package/src/comment-rules.ts +236 -418
- package/src/comment-scanner.ts +339 -47
- package/src/complexity-metrics.ts +111 -35
- package/src/config-load-error.ts +17 -8
- package/src/config-parse.ts +291 -98
- package/src/config-preservation.ts +81 -26
- package/src/config.ts +751 -223
- package/src/constants.ts +7 -6
- package/src/context-doc-rules.ts +182 -54
- package/src/dashboard.ts +88 -23
- package/src/dead-code-rules.ts +153 -74
- package/src/discovery.ts +493 -140
- package/src/doc-rules.ts +602 -126
- package/src/duplicate-test-group-rules.ts +359 -0
- package/src/findings-helpers.ts +134 -109
- package/src/findings.ts +47 -27
- package/src/fixture-purpose-rules.ts +194 -50
- package/src/github-actions-event-guards.ts +331 -0
- package/src/github-actions-rules.ts +328 -121
- package/src/hook-contract.ts +681 -255
- package/src/init-config.ts +163 -118
- package/src/inline-suppressions.ts +340 -0
- package/src/limit-band.ts +56 -0
- package/src/line-rules.ts +331 -468
- package/src/migrate-config.ts +670 -0
- package/src/naming-pushers.ts +32 -127
- package/src/parsed-script.ts +868 -314
- package/src/pillar-summary.ts +56 -40
- package/src/profiles.ts +86 -74
- package/src/project-config-rules.ts +324 -140
- package/src/project-rules.ts +237 -115
- package/src/public-exports.ts +102 -38
- package/src/report-html.ts +217 -85
- package/src/report-renderers.ts +821 -203
- package/src/rule-list.ts +166 -46
- package/src/rules.ts +100 -104
- package/src/safety-rules.ts +191 -132
- package/src/scoring.ts +249 -55
- package/src/security-flow-rules.ts +791 -115
- package/src/selectors.ts +169 -0
- package/src/sensitive-data-rules.ts +460 -387
- package/src/sensitive-exclusions.ts +435 -0
- package/src/source-text.ts +378 -104
- package/src/static-analysis-redundant-rules.ts +298 -41
- package/src/test-block-rules.ts +343 -253
- package/src/text-scans.ts +62 -11
- package/src/types.ts +220 -71
- package/tsconfig.json +2 -1
- package/src/process-exec-metadata.ts +0 -163
- package/src/test-fixtures.ts +0 -671
package/src/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,44 +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
|
-
|
|
47
|
-
|
|
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);
|
|
48
181
|
return {
|
|
49
|
-
|
|
50
|
-
|
|
182
|
+
tool: report.tool,
|
|
183
|
+
run: machineRun(report),
|
|
184
|
+
summary: machineSummary(report, details.length, missingPaths.length, exitCode),
|
|
51
185
|
score: {
|
|
52
|
-
|
|
53
|
-
|
|
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
|
+
})),
|
|
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
|
+
}),
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
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",
|
|
54
312
|
},
|
|
55
313
|
};
|
|
56
314
|
}
|
|
57
315
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
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)))];
|
|
62
442
|
}
|
|
63
443
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
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>>;
|
|
68
460
|
}
|
|
69
461
|
|
|
70
|
-
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
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("/");
|
|
496
|
+
}
|
|
497
|
+
|
|
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;
|
|
507
|
+
}
|
|
508
|
+
|
|
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.
|
|
75
516
|
*/
|
|
76
517
|
function renderSarif(report: AnalysisReport): string {
|
|
77
518
|
const rules = ruleDescriptors().map((descriptor) => ({
|
|
@@ -85,7 +526,7 @@ function renderSarif(report: AnalysisReport): string {
|
|
|
85
526
|
tier: "v0.1",
|
|
86
527
|
defaultSeverity: descriptor.severity,
|
|
87
528
|
confidence: descriptor.confidence,
|
|
88
|
-
defaultEnabled:
|
|
529
|
+
defaultEnabled: descriptor.isEnabledByDefault !== false,
|
|
89
530
|
...(typeof descriptor.threshold === "number" ? { threshold: descriptor.threshold } : {}),
|
|
90
531
|
...(descriptor.optionKeys ? { optionKeys: descriptor.optionKeys } : {}),
|
|
91
532
|
},
|
|
@@ -103,7 +544,21 @@ function renderSarif(report: AnalysisReport): string {
|
|
|
103
544
|
rules,
|
|
104
545
|
},
|
|
105
546
|
},
|
|
106
|
-
|
|
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
|
+
],
|
|
107
562
|
properties: {
|
|
108
563
|
gruffSchemaVersion: report.schemaVersion,
|
|
109
564
|
generatedAt: report.run.generatedAt,
|
|
@@ -116,9 +571,64 @@ function renderSarif(report: AnalysisReport): string {
|
|
|
116
571
|
return `${JSON.stringify(sarif, null, 2)}\n`;
|
|
117
572
|
}
|
|
118
573
|
|
|
119
|
-
|
|
120
|
-
*
|
|
121
|
-
*
|
|
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.
|
|
122
632
|
*/
|
|
123
633
|
function sarifResult(finding: Finding, ruleIndices: Map<string, number>): Record<string, unknown> {
|
|
124
634
|
const result: Record<string, unknown> = {
|
|
@@ -130,10 +640,12 @@ function sarifResult(finding: Finding, ruleIndices: Map<string, number>): Record
|
|
|
130
640
|
physicalLocation: sarifPhysicalLocation(finding),
|
|
131
641
|
},
|
|
132
642
|
],
|
|
133
|
-
partialFingerprints: {
|
|
134
|
-
gruffFingerprint: finding.fingerprint,
|
|
135
|
-
},
|
|
136
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
|
+
}
|
|
137
649
|
const ruleIndex = ruleIndices.get(finding.ruleId);
|
|
138
650
|
if (ruleIndex !== undefined) {
|
|
139
651
|
result.ruleIndex = ruleIndex;
|
|
@@ -158,10 +670,12 @@ function sarifResult(finding: Finding, ruleIndices: Map<string, number>): Record
|
|
|
158
670
|
return result;
|
|
159
671
|
}
|
|
160
672
|
|
|
161
|
-
|
|
162
|
-
*
|
|
163
|
-
*
|
|
164
|
-
*
|
|
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.
|
|
165
679
|
*/
|
|
166
680
|
function sarifPhysicalLocation(finding: Finding): Record<string, unknown> {
|
|
167
681
|
const location: Record<string, unknown> = {
|
|
@@ -184,8 +698,13 @@ function sarifPhysicalLocation(finding: Finding): Record<string, unknown> {
|
|
|
184
698
|
return location;
|
|
185
699
|
}
|
|
186
700
|
|
|
187
|
-
|
|
188
|
-
|
|
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
|
+
*/
|
|
189
708
|
function sarifUri(filePath: string): string {
|
|
190
709
|
return filePath
|
|
191
710
|
.replaceAll("\\", "/")
|
|
@@ -195,7 +714,12 @@ function sarifUri(filePath: string): string {
|
|
|
195
714
|
.join("/");
|
|
196
715
|
}
|
|
197
716
|
|
|
198
|
-
|
|
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
|
+
*/
|
|
199
723
|
function sarifLevel(severity: Severity): "error" | "warning" | "note" {
|
|
200
724
|
switch (severity) {
|
|
201
725
|
case "error":
|
|
@@ -207,21 +731,25 @@ function sarifLevel(severity: Severity): "error" | "warning" | "note" {
|
|
|
207
731
|
}
|
|
208
732
|
}
|
|
209
733
|
|
|
210
|
-
|
|
211
|
-
*
|
|
212
|
-
*
|
|
213
|
-
*
|
|
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
|
|
214
742
|
*/
|
|
215
743
|
function renderSummary(report: AnalysisReport, elapsedMs?: number, pathLabel?: string, top = 10): string {
|
|
216
|
-
const ruleCounts = countBy(report.findings, (finding) => finding.ruleId);
|
|
217
744
|
const pillarRows = buildPillarRows(report);
|
|
218
745
|
const breakdown = severityGradeBreakdown(report.findings);
|
|
746
|
+
// FAMILY-CONTRACT section 1 keeps the masthead, composite, and finding totals ahead of port-specific summary lines.
|
|
219
747
|
const lines = [
|
|
220
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`,
|
|
221
751
|
`Path: ${pathLabel ?? report.run.projectRoot}`,
|
|
222
752
|
...(typeof elapsedMs === "number" ? [`Duration: ${formatSummaryDuration(elapsedMs)}`] : []),
|
|
223
|
-
`Composite: ${report.score.grade} (${report.score.composite.toFixed(2)} / 100)`,
|
|
224
|
-
`Findings: ${report.summary.total} total · ${report.summary.error} error · ${report.summary.warning} warning · ${report.summary.advisory} advisory`,
|
|
225
753
|
` Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
|
|
226
754
|
` Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
|
|
227
755
|
` Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
|
|
@@ -240,64 +768,50 @@ function renderSummary(report: AnalysisReport, elapsedMs?: number, pathLabel?: s
|
|
|
240
768
|
...(
|
|
241
769
|
report.score.topOffenders.length === 0
|
|
242
770
|
? ["- No file offenders."]
|
|
243
|
-
: 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
|
+
})
|
|
244
775
|
),
|
|
245
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));
|
|
246
780
|
return `${lines.join("\n")}\n`;
|
|
247
781
|
}
|
|
248
782
|
|
|
249
|
-
|
|
250
|
-
* Renders the
|
|
251
|
-
*
|
|
252
|
-
*
|
|
253
|
-
*
|
|
254
|
-
*
|
|
255
|
-
*
|
|
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.
|
|
256
790
|
*/
|
|
257
|
-
function renderSummaryJson(report: AnalysisReport,
|
|
258
|
-
|
|
259
|
-
const pillarRows = buildPillarRows(report);
|
|
260
|
-
const payload = {
|
|
261
|
-
schemaVersion: "gruff.summary.v2",
|
|
262
|
-
tool: report.tool,
|
|
263
|
-
scope: {
|
|
264
|
-
paths: pathLabel ?? report.run.projectRoot,
|
|
265
|
-
projectRoot: report.run.projectRoot,
|
|
266
|
-
analysedFiles: report.paths.analysedFiles,
|
|
267
|
-
ignoredPaths: report.paths.ignoredPaths.length,
|
|
268
|
-
missingPaths: report.paths.missingPaths.length,
|
|
269
|
-
diagnostics: report.diagnostics.length,
|
|
270
|
-
elapsedSeconds: typeof elapsedMs === "number" ? Number((elapsedMs / 1000).toFixed(3)) : undefined,
|
|
271
|
-
},
|
|
272
|
-
score: report.score,
|
|
273
|
-
findings: report.summary,
|
|
274
|
-
baseline: report.baseline,
|
|
275
|
-
pillars: pillarRows.map((row) => ({
|
|
276
|
-
pillar: row.pillar,
|
|
277
|
-
grade: row.grade,
|
|
278
|
-
score: row.score,
|
|
279
|
-
penalty: row.penalty,
|
|
280
|
-
applicable: row.isApplicable,
|
|
281
|
-
findings: row.findings,
|
|
282
|
-
advisory: row.advisory,
|
|
283
|
-
warning: row.warning,
|
|
284
|
-
error: row.error,
|
|
285
|
-
})),
|
|
286
|
-
topRules: renderRankedCountRows(ruleCounts, top),
|
|
287
|
-
topOffenders: report.score.topOffenders.slice(0, top),
|
|
288
|
-
};
|
|
289
|
-
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`;
|
|
290
793
|
}
|
|
291
794
|
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
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
|
+
*/
|
|
295
803
|
function summaryDiagnosticLine(diagnostic: AnalysisReport["diagnostics"][number]): string {
|
|
296
804
|
const location = diagnostic.filePath ? ` (${diagnostic.filePath})` : "";
|
|
297
805
|
return `- ${diagnostic.diagnosticType}: ${diagnostic.message}${location}`;
|
|
298
806
|
}
|
|
299
807
|
|
|
300
|
-
|
|
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
|
+
*/
|
|
301
815
|
function summaryBaselineLine(baseline: NonNullable<AnalysisReport["baseline"]>): string {
|
|
302
816
|
if (baseline.generated) {
|
|
303
817
|
return `Baseline: generated ${baseline.path}; current findings still shown`;
|
|
@@ -306,7 +820,13 @@ function summaryBaselineLine(baseline: NonNullable<AnalysisReport["baseline"]>):
|
|
|
306
820
|
return `Baseline: ${baseline.source} ${baseline.path}; suppressed ${baseline.suppressed} ${findingNoun}`;
|
|
307
821
|
}
|
|
308
822
|
|
|
309
|
-
|
|
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
|
+
*/
|
|
310
830
|
function formatSummaryDuration(elapsedMs: number): string {
|
|
311
831
|
const bounded = Math.max(0, elapsedMs);
|
|
312
832
|
if (bounded < 1000) {
|
|
@@ -315,24 +835,12 @@ function formatSummaryDuration(elapsedMs: number): string {
|
|
|
315
835
|
return `${(bounded / 1000).toFixed(2)}s`;
|
|
316
836
|
}
|
|
317
837
|
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
}
|
|
325
|
-
return counts;
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
/*
|
|
329
|
-
* Text renderer for the `Pillars` block in `gruff-ts summary`. Column widths are computed from the
|
|
330
|
-
* actual data (max pillar-name length, max digits per severity column) with a 3-char minimum value
|
|
331
|
-
* width so single-digit cells still leave visual breathing room before the next column. This
|
|
332
|
-
* matches the cross-port canonical byte-for-byte layout: leading "Pillars" header, 2-space row
|
|
333
|
-
* indent, pillar name padded to max-name-width + 1 space, single-letter grade, 1-space separator,
|
|
334
|
-
* score right-aligned in 6 chars with 2 decimals, then findings/advisory/warning/error cells
|
|
335
|
-
* 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.
|
|
336
844
|
*/
|
|
337
845
|
function renderPillarsBlock(rows: PillarRow[]): string[] {
|
|
338
846
|
if (rows.length === 0) {
|
|
@@ -346,7 +854,7 @@ function renderPillarsBlock(rows: PillarRow[]): string[] {
|
|
|
346
854
|
const lines = ["Pillars"];
|
|
347
855
|
for (const row of rows) {
|
|
348
856
|
const name = row.pillar.padEnd(nameWidth);
|
|
349
|
-
const score = row.score.toFixed(2).padStart(6);
|
|
857
|
+
const score = (row.score === null ? "n/a" : row.score.toFixed(2)).padStart(6);
|
|
350
858
|
const findingsCell = `findings=${String(row.findings).padEnd(findingsWidth)}`;
|
|
351
859
|
const advisoryCell = `advisory=${String(row.advisory).padEnd(advisoryWidth)}`;
|
|
352
860
|
const warningCell = `warning=${String(row.warning).padEnd(warningWidth)}`;
|
|
@@ -357,12 +865,12 @@ function renderPillarsBlock(rows: PillarRow[]): string[] {
|
|
|
357
865
|
return lines;
|
|
358
866
|
}
|
|
359
867
|
|
|
360
|
-
|
|
361
|
-
*
|
|
362
|
-
*
|
|
363
|
-
*
|
|
364
|
-
*
|
|
365
|
-
*
|
|
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.
|
|
366
874
|
*/
|
|
367
875
|
function renderRankedRuleRows(findings: Finding[], limit?: number): string[] {
|
|
368
876
|
const severities = countRuleSeverities(findings);
|
|
@@ -379,47 +887,33 @@ function renderRankedRuleRows(findings: Finding[], limit?: number): string[] {
|
|
|
379
887
|
});
|
|
380
888
|
}
|
|
381
889
|
|
|
382
|
-
|
|
383
|
-
* 60-char description budget that keeps the rule-row line under ~100 columns even with the longest
|
|
384
|
-
* ruleId and severity-split. The trailing ellipsis is a single Unicode glyph so terminals that
|
|
385
|
-
* don't render `...` still see the truncation marker.
|
|
386
|
-
*/
|
|
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.
|
|
387
891
|
const DESCRIPTION_BODY_LIMIT = 60;
|
|
388
892
|
|
|
389
|
-
|
|
390
|
-
|
|
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
|
+
*/
|
|
391
900
|
function truncateDescription(text: string): string {
|
|
392
901
|
return text.length <= DESCRIPTION_BODY_LIMIT ? text : `${text.slice(0, DESCRIPTION_BODY_LIMIT).trimEnd()}…`;
|
|
393
902
|
}
|
|
394
903
|
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
.slice(0, limit ?? counts.size)
|
|
403
|
-
.map(([key, count]) => `- ${key}: ${count}`);
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
// Structured variant of `renderRankedCounts` for JSON consumers; the same deterministic ordering.
|
|
407
|
-
function renderRankedCountRows<T extends string>(counts: Map<T, number>, limit?: number): Array<{ name: T; count: number }> {
|
|
408
|
-
return [...counts.entries()]
|
|
409
|
-
.sort(([leftKey, leftCount], [rightKey, rightCount]) => rightCount - leftCount || leftKey.localeCompare(rightKey))
|
|
410
|
-
.slice(0, limit ?? counts.size)
|
|
411
|
-
.map(([name, count]) => ({ name, count }));
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
/*
|
|
415
|
-
* Default terminal output. Findings are listed verbatim (no truncation) - the analyser keeps them
|
|
416
|
-
* 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.
|
|
417
911
|
*/
|
|
418
912
|
function renderText(report: AnalysisReport): string {
|
|
419
913
|
const breakdown = severityGradeBreakdown(report.findings);
|
|
420
914
|
const lines = [
|
|
421
915
|
`gruff-ts ${report.tool.version} analyse`,
|
|
422
|
-
|
|
916
|
+
compositeLine(report.score.composite, report.score.grade),
|
|
423
917
|
`Findings: ${report.summary.total} total · ${report.summary.error} error · ${report.summary.warning} warning · ${report.summary.advisory} advisory`,
|
|
424
918
|
` Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
|
|
425
919
|
` Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
|
|
@@ -439,27 +933,70 @@ function renderText(report: AnalysisReport): string {
|
|
|
439
933
|
if (report.findings.length >= OUTPUT_VOLUME_HINT_THRESHOLD) {
|
|
440
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.`);
|
|
441
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
|
+
}
|
|
442
941
|
return `${lines.join("\n")}\n`;
|
|
443
942
|
}
|
|
444
943
|
|
|
445
|
-
|
|
446
|
-
*
|
|
447
|
-
*
|
|
448
|
-
*
|
|
449
|
-
*
|
|
450
|
-
*
|
|
451
|
-
|
|
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.
|
|
452
973
|
*/
|
|
453
974
|
function renderMarkdown(report: AnalysisReport): string {
|
|
454
975
|
const breakdown = severityGradeBreakdown(report.findings);
|
|
455
|
-
//
|
|
976
|
+
// Keep repository text from changing the Markdown structure. An unlocated finding uses line 1 as its display anchor.
|
|
456
977
|
const findingRows = report.findings
|
|
457
978
|
.slice(0, 50)
|
|
458
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
|
+
];
|
|
459
993
|
return [
|
|
460
994
|
"# gruff-ts report",
|
|
461
995
|
"",
|
|
462
|
-
|
|
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)**`,
|
|
463
1000
|
`- Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
|
|
464
1001
|
`- Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
|
|
465
1002
|
`- Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
|
|
@@ -467,19 +1004,18 @@ function renderMarkdown(report: AnalysisReport): string {
|
|
|
467
1004
|
"",
|
|
468
1005
|
`Findings: ${report.summary.total} total · ${report.summary.error} error · ${report.summary.warning} warning · ${report.summary.advisory} advisory`,
|
|
469
1006
|
"",
|
|
1007
|
+
...diagnosticRows,
|
|
470
1008
|
...renderMarkdownPillarsTable(buildPillarRows(report)),
|
|
471
1009
|
"",
|
|
472
1010
|
...findingRows,
|
|
473
1011
|
].join("\n");
|
|
474
1012
|
}
|
|
475
1013
|
|
|
476
|
-
|
|
477
|
-
*
|
|
478
|
-
*
|
|
479
|
-
*
|
|
480
|
-
*
|
|
481
|
-
* ASC); scores render with two decimals; pipes in pillar/grade cells are escaped so a future
|
|
482
|
-
* 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.
|
|
483
1019
|
*/
|
|
484
1020
|
function renderMarkdownPillarsTable(rows: PillarRow[]): string[] {
|
|
485
1021
|
const lines = [
|
|
@@ -493,22 +1029,32 @@ function renderMarkdownPillarsTable(rows: PillarRow[]): string[] {
|
|
|
493
1029
|
return lines;
|
|
494
1030
|
}
|
|
495
1031
|
for (const row of rows) {
|
|
1032
|
+
const scoreText = row.score === null ? "n/a" : row.score.toFixed(2);
|
|
496
1033
|
lines.push(
|
|
497
|
-
`| ${escapeMarkdownCell(row.pillar)} | ${escapeMarkdownCell(row.grade)} | ${
|
|
1034
|
+
`| ${escapeMarkdownCell(row.pillar)} | ${escapeMarkdownCell(row.grade)} | ${scoreText} | ${row.findings} | ${row.advisory} | ${row.warning} | ${row.error} |`,
|
|
498
1035
|
);
|
|
499
1036
|
}
|
|
500
1037
|
return lines;
|
|
501
1038
|
}
|
|
502
1039
|
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
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
|
+
*/
|
|
506
1047
|
function escapeMarkdownCell(cell: string): string {
|
|
507
1048
|
return cell.replaceAll("|", "\\|");
|
|
508
1049
|
}
|
|
509
1050
|
|
|
510
|
-
|
|
511
|
-
|
|
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
|
+
*/
|
|
512
1058
|
function markdownInlineCode(reportLabel: string): string {
|
|
513
1059
|
const singleLineLabel = reportLabel.replace(/[\r\n]+/g, " ");
|
|
514
1060
|
// An empty analyzer label still needs content so Markdown does not merge its two fences.
|
|
@@ -520,8 +1066,13 @@ function markdownInlineCode(reportLabel: string): string {
|
|
|
520
1066
|
return `${fence}${paddedLabel}${fence}`;
|
|
521
1067
|
}
|
|
522
1068
|
|
|
523
|
-
|
|
524
|
-
|
|
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
|
+
*/
|
|
525
1076
|
function escapeMarkdownFindingMessage(findingMessage: string): string {
|
|
526
1077
|
return findingMessage
|
|
527
1078
|
.replace(/[\r\n]+/g, " ")
|
|
@@ -546,9 +1097,16 @@ interface ComplexityCluster {
|
|
|
546
1097
|
ruleIds: string[];
|
|
547
1098
|
}
|
|
548
1099
|
|
|
549
|
-
const CORRELATED_COMPLEXITY_RULE_IDS = new Set(["complexity.
|
|
1100
|
+
const CORRELATED_COMPLEXITY_RULE_IDS = new Set(["complexity.cyclomatic", "size.function-length"]);
|
|
550
1101
|
|
|
551
|
-
|
|
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
|
+
*/
|
|
552
1110
|
function renderComplexityClusterLines(findings: Finding[], limit = 10): string[] {
|
|
553
1111
|
const clusters = complexityClusters(findings).slice(0, limit);
|
|
554
1112
|
if (clusters.length === 0) {
|
|
@@ -560,7 +1118,12 @@ function renderComplexityClusterLines(findings: Finding[], limit = 10): string[]
|
|
|
560
1118
|
];
|
|
561
1119
|
}
|
|
562
1120
|
|
|
563
|
-
|
|
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
|
+
*/
|
|
564
1127
|
function renderMarkdownComplexityClusterLines(findings: Finding[]): string[] {
|
|
565
1128
|
const clusters = complexityClusters(findings);
|
|
566
1129
|
// A scan with no overlapping complexity findings should not show an empty review section.
|
|
@@ -577,7 +1140,12 @@ function renderMarkdownComplexityClusterLines(findings: Finding[]): string[] {
|
|
|
577
1140
|
];
|
|
578
1141
|
}
|
|
579
1142
|
|
|
580
|
-
|
|
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
|
+
*/
|
|
581
1149
|
function renderMarkdownComplexityClusterRow(cluster: ComplexityCluster): string {
|
|
582
1150
|
const clusterLabel = `${cluster.filePath}#${cluster.symbol}`;
|
|
583
1151
|
// Every linked rule remains its own code span so a reviewer can copy its exact identifier.
|
|
@@ -585,7 +1153,14 @@ function renderMarkdownComplexityClusterRow(cluster: ComplexityCluster): string
|
|
|
585
1153
|
return `- ${markdownInlineCode(clusterLabel)}: ${cluster.ruleIds.length} linked findings (${linkedRuleLabels})`;
|
|
586
1154
|
}
|
|
587
1155
|
|
|
588
|
-
|
|
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
|
+
*/
|
|
589
1164
|
function complexityClusters(findings: Finding[]): ComplexityCluster[] {
|
|
590
1165
|
const bySymbol = new Map<string, ComplexityCluster>();
|
|
591
1166
|
for (const finding of findings) {
|
|
@@ -605,34 +1180,77 @@ function complexityClusters(findings: Finding[]): ComplexityCluster[] {
|
|
|
605
1180
|
.sort((left, right) => right.ruleIds.length - left.ruleIds.length || left.filePath.localeCompare(right.filePath) || left.symbol.localeCompare(right.symbol));
|
|
606
1181
|
}
|
|
607
1182
|
|
|
608
|
-
|
|
609
|
-
|
|
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
|
+
*/
|
|
610
1191
|
function renderGithub(report: AnalysisReport): string {
|
|
611
|
-
return
|
|
612
|
-
.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
|
+
]
|
|
613
1196
|
.join("\n");
|
|
614
1197
|
}
|
|
615
1198
|
|
|
616
|
-
|
|
617
|
-
|
|
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
|
+
*/
|
|
618
1221
|
function githubAnnotationPath(filePath: string): string {
|
|
619
1222
|
return filePath.replaceAll("\\", "/").replace(/^(?:\.\/)+/, "");
|
|
620
1223
|
}
|
|
621
1224
|
|
|
622
|
-
|
|
623
|
-
|
|
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
|
+
*/
|
|
624
1232
|
function githubLevel(severity: Severity): "notice" | "warning" | "error" {
|
|
625
1233
|
return severity === "error" ? "error" : severity === "warning" ? "warning" : "notice";
|
|
626
1234
|
}
|
|
627
1235
|
|
|
628
|
-
|
|
629
|
-
|
|
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
|
+
*/
|
|
630
1243
|
function escapeCommand(commandText: string): string {
|
|
631
1244
|
return commandText.replaceAll("%", "%25").replaceAll("\n", "%0A").replaceAll("\r", "%0D");
|
|
632
1245
|
}
|
|
633
1246
|
|
|
634
|
-
|
|
635
|
-
|
|
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
|
+
*/
|
|
636
1254
|
function escapeCommandProperty(propertyText: string): string {
|
|
637
1255
|
return escapeCommand(propertyText).replaceAll(":", "%3A").replaceAll(",", "%2C");
|
|
638
1256
|
}
|