Skip to content

Commit c34799d

Browse files
Hotelllayershifter
andauthored
feat(monosize): unify reporters API and behaviours (#42)
* feat(monosize): unify reporters API and behaviours * change files --------- Co-authored-by: Oleksandr Fediashov <olfedias@microsoft.com>
1 parent 9723aab commit c34799d

File tree

8 files changed

+125
-57
lines changed

8 files changed

+125
-57
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"type": "minor",
3+
"comment": "feat(monosize): unify reporters API and behaviours",
4+
"packageName": "monosize",
5+
"email": "hochelmartin@gmail.com",
6+
"dependentChangeType": "patch"
7+
}

packages/monosize/src/commands/compareReports.mts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,14 +48,18 @@ async function compareReports(options: CompareReportsOptions) {
4848
}
4949
}
5050

51-
const result = compareResultsInReports(localReport, remoteReport);
51+
const reportsComparisonResult = compareResultsInReports(localReport, remoteReport);
5252

5353
switch (output) {
5454
case 'cli':
55-
await cliReporter(result);
55+
cliReporter(reportsComparisonResult, { commitSHA, repository: config.repository, showUnchanged: false });
5656
break;
5757
case 'markdown':
58-
await markdownReporter(result, commitSHA, config.repository, quiet);
58+
markdownReporter(reportsComparisonResult, {
59+
commitSHA,
60+
repository: config.repository,
61+
showUnchanged: true,
62+
});
5963
break;
6064
}
6165

packages/monosize/src/commands/compareReports.test.mts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ describe('compareReports', () => {
3232

3333
expect(getRemoteReport).toHaveBeenCalledWith(branchName);
3434
expect(compareResultsInReports).toHaveBeenCalledWith(sampleReport, sampleReport);
35-
expect(cliReporter).toHaveBeenCalledWith(sampleComparedReport);
35+
expect(cliReporter).toHaveBeenCalledWith(sampleComparedReport, {
36+
commitSHA: 'test',
37+
repository: undefined,
38+
showUnchanged: false,
39+
});
3640
});
3741
});

packages/monosize/src/reporters/cliReporter.mts

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import pc from 'picocolors';
44
import { getChangedEntriesInReport } from '../utils/getChangedEntriesInReport.mjs';
55
import { formatBytes } from '../utils/helpers.mjs';
66
import type { DiffByMetric } from '../utils/calculateDiffByMetric.mjs';
7-
import type { ComparedReport } from '../utils/compareResultsInReports.mjs';
7+
import type { Reporter } from './shared.mjs';
88

99
function getDirectionSymbol(value: number): string {
1010
if (value < 0) {
@@ -28,12 +28,21 @@ function formatDelta(diff: DiffByMetric): string {
2828
return colorFn(diff.percent + getDirectionSymbol(diff.delta));
2929
}
3030

31-
export async function cliReporter(report: ComparedReport): Promise<void> {
32-
const result = new Table({
31+
export const cliReporter: Reporter = (report, options) => {
32+
const { commitSHA, repository } = options;
33+
const footer = `🤖 This report was generated against '${repository}/commit/${commitSHA}'`;
34+
35+
const { changedEntries } = getChangedEntriesInReport(report);
36+
37+
const reportOutput = new Table({
3338
colAligns: ['left', 'right', 'right'],
3439
head: ['Fixture', 'Before', 'After (minified/GZIP)'],
3540
});
36-
const { changedEntries } = getChangedEntriesInReport(report);
41+
42+
if (changedEntries.length === 0) {
43+
console.log(`${pc.green('[✔]')} No changes found`);
44+
return;
45+
}
3746

3847
changedEntries.forEach(entry => {
3948
const { diff, gzippedSize, minifiedSize, name, packageName } = entry;
@@ -49,13 +58,10 @@ export async function cliReporter(report: ComparedReport): Promise<void> {
4958
const afterColumn =
5059
formatDelta(diff.minified) + ' ' + minifiedAfter + '\n' + formatDelta(diff.gzip) + ' ' + gzippedAfter;
5160

52-
result.push([fixtureColumn, beforeColumn, afterColumn]);
61+
reportOutput.push([fixtureColumn, beforeColumn, afterColumn]);
5362
});
5463

55-
if (result.length > 0) {
56-
console.log(result.toString());
57-
return;
58-
}
59-
60-
console.log(`${pc.green('[✔]')} No changes found`);
61-
}
64+
console.log(reportOutput.toString());
65+
console.log('');
66+
console.log(footer);
67+
};

packages/monosize/src/reporters/cliReporter.test.mts

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,24 @@ expect.addSnapshotSerializer({
2222
});
2323

2424
describe('cliReporter', () => {
25-
it('renders a report to CLI output', async () => {
25+
const options = {
26+
repository: 'https://github.com/microsoft/monosize',
27+
commitSHA: 'commit-hash',
28+
showUnchanged: false,
29+
};
30+
31+
it('wont render anything if there is nothing to compare', () => {
2632
const log = vitest.spyOn(console, 'log').mockImplementation(noop);
27-
await cliReporter(sampleComparedReport);
33+
34+
cliReporter([], options);
35+
36+
expect(log.mock.calls[0][0]).toMatchInlineSnapshot('[✔] No changes found');
37+
});
38+
39+
it('renders a report to CLI output', () => {
40+
const log = vitest.spyOn(console, 'log').mockImplementation(noop);
41+
42+
cliReporter(sampleComparedReport, options);
2843

2944
expect(log.mock.calls[0][0]).toMatchInlineSnapshot(`
3045
┌────────────────────┬────────┬───────────────────────┐

packages/monosize/src/reporters/markdownReporter.mts

Lines changed: 40 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ import { findPackageRoot } from 'workspace-tools';
33

44
import { getChangedEntriesInReport } from '../utils/getChangedEntriesInReport.mjs';
55
import { formatBytes } from '../utils/helpers.mjs';
6-
import type { ComparedReport } from '../utils/compareResultsInReports.mjs';
76
import type { DiffByMetric } from '../utils/calculateDiffByMetric.mjs';
7+
import type { Reporter } from './shared.mjs';
88

99
const icons = { increase: 'increase.png', decrease: 'decrease.png' };
1010

@@ -31,29 +31,25 @@ function formatDelta(diff: DiffByMetric): string {
3131
return `\`${formatBytes(diff.delta)}\` ${getDirectionSymbol(diff.delta)}`;
3232
}
3333

34-
export async function markdownReporter(result: ComparedReport, commitSHA: string, repository: string, quiet: boolean) {
35-
const dirname = fileURLToPath(new URL('.', import.meta.url));
36-
const packageRoot = findPackageRoot(dirname);
34+
export const markdownReporter: Reporter = (report, options) => {
35+
const { commitSHA, repository, showUnchanged } = options;
36+
const footer = `<sub>🤖 This report was generated against <a href='${repository}/commit/${commitSHA}'>${commitSHA}</a></sub>`;
3737

38-
if (!packageRoot) {
39-
throw new Error(
40-
[
41-
'Failed to find a package root (directory that contains "package.json" file)',
42-
`Lookup start in: ${dirname}`,
43-
].join('\n'),
44-
);
45-
}
38+
assertPackageRoot();
4639

47-
const report = [];
40+
const { changedEntries, unchangedEntries } = getChangedEntriesInReport(report);
4841

49-
report.push('## 📊 Bundle size report');
50-
report.push('');
42+
const reportOutput = ['## 📊 Bundle size report', ''];
5143

52-
const { changedEntries, unchangedEntries } = getChangedEntriesInReport(result);
44+
if (changedEntries.length === 0) {
45+
reportOutput.push(`✅ No changes found`);
46+
console.log(reportOutput.join('\n'));
47+
return;
48+
}
5349

5450
if (changedEntries.length > 0) {
55-
report.push('| Package & Exports | Baseline (minified/GZIP) | PR | Change |');
56-
report.push('| :---------------- | -----------------------: | ----: | ---------: |');
51+
reportOutput.push('| Package & Exports | Baseline (minified/GZIP) | PR | Change |');
52+
reportOutput.push('| :---------------- | -----------------------: | ----: | ---------: |');
5753

5854
changedEntries.forEach(entry => {
5955
const title = `<samp>${entry.packageName}</samp> <br /> <abbr title='${entry.path}'>${entry.name}</abbr>`;
@@ -71,36 +67,48 @@ export async function markdownReporter(result: ComparedReport, commitSHA: string
7167
? '🆕 New entry'
7268
: [`${formatDelta(entry.diff.minified)}`, '<br />', `${formatDelta(entry.diff.gzip)}`].join('');
7369

74-
report.push(`| ${title} | ${before} | ${after} | ${difference}|`);
70+
reportOutput.push(`| ${title} | ${before} | ${after} | ${difference}|`);
7571
});
7672

77-
report.push('');
73+
reportOutput.push('');
7874
}
7975

80-
if (unchangedEntries.length > 0) {
81-
report.push('<details>');
82-
report.push('<summary>Unchanged fixtures</summary>');
83-
report.push('');
76+
if (showUnchanged && unchangedEntries.length > 0) {
77+
reportOutput.push('<details>');
78+
reportOutput.push('<summary>Unchanged fixtures</summary>');
79+
reportOutput.push('');
8480

85-
report.push('| Package & Exports | Size (minified/GZIP) |');
86-
report.push('| ----------------- | -------------------: |');
81+
reportOutput.push('| Package & Exports | Size (minified/GZIP) |');
82+
reportOutput.push('| ----------------- | -------------------: |');
8783

8884
unchangedEntries.forEach(entry => {
8985
const title = `<samp>${entry.packageName}</samp> <br /> <abbr title='${entry.path}'>${entry.name}</abbr>`;
9086
const size = [`\`${formatBytes(entry.minifiedSize)}\``, '<br />', `\`${formatBytes(entry.gzippedSize)}\``].join(
9187
'',
9288
);
9389

94-
report.push(`| ${title} | ${size} |`);
90+
reportOutput.push(`| ${title} | ${size} |`);
9591
});
9692

97-
report.push('</details>');
93+
reportOutput.push('</details>');
9894
}
9995

10096
// TODO: use repo settings
101-
report.push(
102-
`<sub>🤖 This report was generated against <a href='${repository}/commit/${commitSHA}'>${commitSHA}</a></sub>`,
103-
);
97+
reportOutput.push(footer);
98+
99+
console.log(reportOutput.join('\n'));
100+
};
104101

105-
console.log(report.join('\n'));
102+
function assertPackageRoot() {
103+
const dirname = fileURLToPath(new URL('.', import.meta.url));
104+
const packageRoot = findPackageRoot(dirname);
105+
106+
if (!packageRoot) {
107+
throw new Error(
108+
[
109+
'Failed to find a package root (directory that contains "package.json" file)',
110+
`Lookup start in: ${dirname}`,
111+
].join('\n'),
112+
);
113+
}
106114
}

packages/monosize/src/reporters/markdownReporter.test.mts

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,34 @@ import { describe, expect, it, vitest } from 'vitest';
44
import { markdownReporter } from './markdownReporter.mjs';
55
import { sampleComparedReport } from '../__fixture__/sampleComparedReport.mjs';
66

7+
// eslint-disable-next-line @typescript-eslint/no-empty-function
8+
const noop = () => {};
9+
710
describe('markdownReporter', () => {
8-
it('renders a report to a file', async () => {
9-
const log = vitest.spyOn(console, 'log').mockImplementation(() => {
10-
/* no op */
11-
});
11+
const options = {
12+
repository: 'https://github.com/microsoft/monosize',
13+
commitSHA: 'commit-hash',
14+
showUnchanged: true,
15+
};
16+
17+
it('wont render anything if there is nothing to compare', () => {
18+
const log = vitest.spyOn(console, 'log').mockImplementation(noop);
19+
20+
markdownReporter([], options);
21+
22+
const output = prettier.format(log.mock.calls[0][0], { parser: 'markdown' });
23+
expect(output).toMatchInlineSnapshot(`
24+
"## 📊 Bundle size report
25+
26+
✅ No changes found
27+
"
28+
`);
29+
});
1230

13-
const repository = 'https://github.com/microsoft/monosize';
14-
const commitSHA = 'commit-hash';
31+
it('renders a report to a file', () => {
32+
const log = vitest.spyOn(console, 'log').mockImplementation(noop);
1533

16-
await markdownReporter(sampleComparedReport, commitSHA, repository, true);
34+
markdownReporter(sampleComparedReport, options);
1735
const output = prettier.format(log.mock.calls[0][0], { parser: 'markdown' });
1836

1937
expect(output).toMatchSnapshot();
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import type { ComparedReport } from '../utils/compareResultsInReports.mjs';
2+
3+
export type Reporter = (
4+
report: ComparedReport,
5+
options: { commitSHA: string; repository: string; showUnchanged: boolean },
6+
) => void;

0 commit comments

Comments
 (0)