Skip to content

Commit 398fe85

Browse files
sonar-fabrik[bot]Fabrik
andcommitted
CLI-1703 Extract shared stats rendering helpers
Preserve summary-card and section output while exposing reusable stats-local renderers. Add helper boundaries and baseline-verified snapshots. Co-Authored-By: Fabrik <fabrik@sonarsource.com>
1 parent 8577922 commit 398fe85

4 files changed

Lines changed: 492 additions & 228 deletions

File tree

Lines changed: 254 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,254 @@
1+
/*
2+
* SonarQube CLI
3+
* Copyright (C) SonarSource Sàrl
4+
* mailto:info AT sonarsource DOT com
5+
*
6+
* This program is free software; you can redistribute it and/or
7+
* modify it under the terms of the GNU Lesser General Public
8+
* License as published by the Free Software Foundation; either
9+
* version 3 of the License, or (at your option) any later version.
10+
*
11+
* This program is distributed in the hope that it will be useful,
12+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14+
* Lesser General Public License for more details.
15+
*
16+
* You should have received a copy of the GNU Lesser General Public License
17+
* along with this program; if not, write to the Free Software Foundation,
18+
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19+
*/
20+
21+
import { VORTEX_PRODUCT_URL } from '@/core/config-constants.ts';
22+
import type { StatsSinceChoice, StatsSummary } from '@/core/stats/stats-queries.ts';
23+
import { bold, dim, softBlue } from '@/core/ui/colors.ts';
24+
import type { Console } from '@/core/ui/console.ts';
25+
import { columnFormatting } from '@/core/ui/formatter/column-formatting.ts';
26+
27+
import type { StatsEntitlement } from './entitlement.ts';
28+
29+
const SPARKLINE_BLOCKS = '▁▂▃▄▅▆▇█';
30+
const SPARKLINE_MAX_LEVEL = SPARKLINE_BLOCKS.length - 2;
31+
32+
export function sparkline(values: readonly number[]): string {
33+
if (values.length === 0) return '';
34+
const max = Math.max(...values);
35+
if (max === 0) return softBlue(SPARKLINE_BLOCKS[0].repeat(values.length));
36+
const line = values
37+
.map((v) => SPARKLINE_BLOCKS[Math.round((v / max) * SPARKLINE_MAX_LEVEL)])
38+
.join('');
39+
return softBlue(line);
40+
}
41+
42+
const MAX_SPARKLINE_COLUMNS = 30;
43+
44+
function resolveBucketDays(totalDays: number): number {
45+
return totalDays > MAX_SPARKLINE_COLUMNS ? Math.ceil(totalDays / MAX_SPARKLINE_COLUMNS) : 1;
46+
}
47+
48+
function downsampleSum(values: readonly number[], bucketDays: number): number[] {
49+
if (bucketDays <= 1) return [...values];
50+
const buckets: number[] = [];
51+
for (let i = 0; i < values.length; i += bucketDays) {
52+
buckets.push(values.slice(i, i + bucketDays).reduce((sum, v) => sum + v, 0));
53+
}
54+
return buckets;
55+
}
56+
57+
export const BAR_WIDTH = 18;
58+
const BAR_FILLED = '▓';
59+
const BAR_EMPTY = '░';
60+
61+
export function bar(fraction: number): string {
62+
const filled = Math.round(Math.min(Math.max(fraction, 0), 1) * BAR_WIDTH);
63+
return softBlue(BAR_FILLED.repeat(filled)) + dim(BAR_EMPTY.repeat(BAR_WIDTH - filled));
64+
}
65+
66+
const CARD_METRIC_LABELS = ['Analyses run', 'Issues caught'] as const;
67+
const CARD_TOTAL_LABELS = ['Secrets blocked', 'Dependency risks'] as const;
68+
69+
const VORTEX_NOT_ENTITLED_LABEL = 'vortex analysis';
70+
const VORTEX_NOT_ENTITLED_MESSAGE = 'not available on this plan';
71+
const DEPENDENCY_RISKS_NOT_ENABLED_LABEL = 'dependency risks';
72+
const DEPENDENCY_RISKS_NOT_ENABLED_MESSAGE = 'not enabled for this organization';
73+
74+
interface StatsMetricRow {
75+
label: string;
76+
windowValue: number;
77+
dailySeries: readonly number[];
78+
allTimeValue: number;
79+
}
80+
81+
interface StatsPlaceholderRow {
82+
label: string;
83+
message: string;
84+
ctaUrl?: string;
85+
}
86+
87+
function buildPlaceholderRows(entitlement: StatsEntitlement): StatsPlaceholderRow[] {
88+
const rows: StatsPlaceholderRow[] = [];
89+
if (entitlement.vortex === 'not_entitled') {
90+
rows.push({
91+
label: VORTEX_NOT_ENTITLED_LABEL,
92+
message: VORTEX_NOT_ENTITLED_MESSAGE,
93+
ctaUrl: VORTEX_PRODUCT_URL,
94+
});
95+
}
96+
if (entitlement.sca === 'not_enabled') {
97+
rows.push({
98+
label: DEPENDENCY_RISKS_NOT_ENABLED_LABEL,
99+
message: DEPENDENCY_RISKS_NOT_ENABLED_MESSAGE,
100+
});
101+
}
102+
return rows;
103+
}
104+
105+
const PLACEHOLDER_CTA_INDENT = ' ';
106+
const PLACEHOLDER_CTA_ACTION = 'Learn more:';
107+
108+
function formatPlaceholderLines(row: StatsPlaceholderRow, labelWidth: number): string[] {
109+
const base = `${row.label.padEnd(labelWidth)} ${dim('-')} ${dim(row.message)}`;
110+
if (!row.ctaUrl) return [base];
111+
const ctaLabel = dim(`→ ${PLACEHOLDER_CTA_ACTION}`);
112+
return [base, `${PLACEHOLDER_CTA_INDENT}${ctaLabel} ${softBlue(row.ctaUrl)}`];
113+
}
114+
115+
function formatDate(ms: number): string {
116+
return new Date(ms).toISOString().slice(0, 10);
117+
}
118+
119+
const SINCE_WINDOW_DAYS: Record<Exclude<StatsSinceChoice, 'all'>, number> = {
120+
'7d': 7,
121+
'14d': 14,
122+
'30d': 30,
123+
};
124+
125+
const HEADER_COLUMN_GAP_WIDTH = 12;
126+
127+
export function printSummaryCard(
128+
summary: StatsSummary,
129+
since: StatsSinceChoice,
130+
entitlement: StatsEntitlement,
131+
console: Console,
132+
): void {
133+
const secretsBlockedTotal =
134+
since === 'all'
135+
? summary.allTime.secretsBlockedTotal
136+
: summary.stopped.reduce((sum, entry) => sum + entry.count, 0);
137+
const dependencyRisksTotal =
138+
summary.analyzers.find((a) => a.analyzer === 'sca-scanner-cli')?.findings ?? 0;
139+
140+
const dailyRuns = summary.daily.map((d) => d.runs);
141+
const dailyFindings = summary.daily.map((d) => d.findings);
142+
const dailySecretsBlocked = summary.dailySecretsBlocked.map((d) => d.count);
143+
const dailyDependencyRisks = summary.dailyDependencyRisks.map((d) => d.count);
144+
145+
const bucketDays = resolveBucketDays(dailyRuns.length);
146+
const columnLabel = bucketDays === 1 ? 'day' : `${bucketDays} days`;
147+
148+
const metricRows: StatsMetricRow[] = [
149+
{
150+
label: CARD_METRIC_LABELS[0],
151+
windowValue: summary.totalRuns,
152+
dailySeries: dailyRuns,
153+
allTimeValue: summary.allTime.totalRuns,
154+
},
155+
{
156+
label: CARD_METRIC_LABELS[1],
157+
windowValue: summary.totalFindings,
158+
dailySeries: dailyFindings,
159+
allTimeValue: summary.allTime.totalFindings,
160+
},
161+
{
162+
label: CARD_TOTAL_LABELS[0],
163+
windowValue: secretsBlockedTotal,
164+
dailySeries: dailySecretsBlocked,
165+
allTimeValue: summary.allTime.secretsBlockedTotal,
166+
},
167+
...(entitlement.sca === 'not_enabled'
168+
? []
169+
: [
170+
{
171+
label: CARD_TOTAL_LABELS[1],
172+
windowValue: dependencyRisksTotal,
173+
dailySeries: dailyDependencyRisks,
174+
allTimeValue: summary.allTime.dependencyRisksTotal,
175+
},
176+
]),
177+
];
178+
const placeholderRows = buildPlaceholderRows(entitlement);
179+
180+
const [labelWidth] = columnFormatting([
181+
[...metricRows.map((row) => row.label), ...placeholderRows.map((row) => row.label)],
182+
]);
183+
const [numberWidth] = columnFormatting([metricRows.map((row) => String(row.windowValue))]);
184+
185+
if (since === 'all') {
186+
console.note([
187+
`◆ sonar stats · since ${formatDate(summary.firstSeenMs ?? Date.now())}`,
188+
` one column per ${columnLabel}`,
189+
'',
190+
...metricRows.map(
191+
(row) =>
192+
`${row.label.padEnd(labelWidth)} ${String(row.windowValue).padStart(numberWidth)} ${sparkline(downsampleSum(row.dailySeries, bucketDays))}`,
193+
),
194+
...placeholderRows.flatMap((row) => formatPlaceholderLines(row, labelWidth)),
195+
]);
196+
return;
197+
}
198+
199+
const windowDaysLabel = `last ${SINCE_WINDOW_DAYS[since]} days`;
200+
const ALL_TIME_LABEL = 'all time';
201+
202+
const allTimeFormatted = metricRows.map((row) => row.allTimeValue.toLocaleString('en-US'));
203+
const [allTimeWidth] = columnFormatting([[ALL_TIME_LABEL, ...allTimeFormatted]]);
204+
205+
const secondLinePrefix = `${windowDaysLabel} · one column per ${columnLabel}`;
206+
const secondLineIndent = ' '.repeat(labelWidth);
207+
const columnsShown = Math.ceil(dailyRuns.length / bucketDays);
208+
209+
const rowPrefixVisibleLength = labelWidth + 2 + numberWidth + 2 + columnsShown;
210+
const header2PrefixVisibleLength = labelWidth + secondLinePrefix.length;
211+
const allTimeColumnStart =
212+
Math.max(rowPrefixVisibleLength, header2PrefixVisibleLength) + HEADER_COLUMN_GAP_WIDTH;
213+
214+
function metricLine(row: StatsMetricRow, allTimeFormattedValue: string): string {
215+
const gap = allTimeColumnStart - rowPrefixVisibleLength;
216+
return `${row.label.padEnd(labelWidth)} ${String(row.windowValue).padStart(numberWidth)} ${sparkline(downsampleSum(row.dailySeries, bucketDays))}${' '.repeat(gap)}${allTimeFormattedValue.padStart(allTimeWidth)}`;
217+
}
218+
219+
const header2Gap = allTimeColumnStart - header2PrefixVisibleLength;
220+
console.note([
221+
`◆ sonar stats · since ${formatDate(summary.firstSeenMs ?? Date.now())}`,
222+
`${secondLineIndent}${secondLinePrefix}${' '.repeat(header2Gap)}${ALL_TIME_LABEL.padStart(allTimeWidth)}`,
223+
'',
224+
...metricRows.map((row, i) => metricLine(row, allTimeFormatted[i])),
225+
...placeholderRows.flatMap((row) => formatPlaceholderLines(row, labelWidth)),
226+
]);
227+
}
228+
229+
const MIN_HEADING_GAP_WIDTH = 2;
230+
231+
export const BASE_COLUMN_GAP_WIDTH = 3;
232+
233+
interface AlignedTotalsLayout {
234+
headingLine: string;
235+
rowGap: string;
236+
}
237+
238+
export function computeAlignedTotalsLayout(
239+
heading: string,
240+
totalCount: number,
241+
naturalRowEndColumn: number,
242+
): AlignedTotalsLayout {
243+
const numberLabel = totalCount.toLocaleString('en-US');
244+
const desiredRowEndColumn = Math.max(
245+
naturalRowEndColumn,
246+
heading.length + MIN_HEADING_GAP_WIDTH + numberLabel.length,
247+
);
248+
const headingGapWidth = desiredRowEndColumn - heading.length - numberLabel.length;
249+
const rowGapWidth = BASE_COLUMN_GAP_WIDTH + (desiredRowEndColumn - naturalRowEndColumn);
250+
return {
251+
headingLine: `${bold(heading)}${' '.repeat(headingGapWidth)}${numberLabel} total`,
252+
rowGap: ' '.repeat(rowGapWidth),
253+
};
254+
}

0 commit comments

Comments
 (0)