Skip to content

Commit bc9f101

Browse files
authored
fix(cli): fix json format handling (#360)
1 parent c35a3ee commit bc9f101

File tree

8 files changed

+75
-31
lines changed

8 files changed

+75
-31
lines changed

e2e/cli-e2e/tests/collect.e2e.test.ts

+1-2
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,7 @@ describe('CLI collect', () => {
7878
expect(stderr).toBe('');
7979

8080
expect(stdout).toContain('Code PushUp Report');
81-
expect(stdout).toContain('Generated reports');
82-
expect(stdout).toContain('report.json');
81+
expect(stdout).not.toContain('Generated reports');
8382
expect(stdout).toContain(exampleCategoryTitle);
8483
expect(stdout).toContain(exampleAuditTitle);
8584
}, 120000);

packages/cli/src/lib/autorun/autorun-command.ts

+13-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,19 @@ export function yargsAutorunCommandObject() {
2323
console.info(chalk.bold(CLI_NAME));
2424
console.info(chalk.gray(`Run ${command}...`));
2525
const options = args as unknown as AutorunOptions;
26-
await collectAndPersistReports(options);
26+
27+
// we need to ensure `json` is part of the formats as we want to upload
28+
const optionsWithFormat: AutorunOptions = {
29+
...options,
30+
persist: {
31+
...options.persist,
32+
format: [
33+
...new Set([...options.persist.format, 'json']),
34+
] as AutorunOptions['persist']['format'],
35+
},
36+
};
37+
38+
await collectAndPersistReports(optionsWithFormat);
2739
if (!options.upload) {
2840
console.warn('Upload skipped because configuration is not set.'); // @TODO log verbose
2941
} else {

packages/cli/src/lib/autorun/autorun-command.unit.test.ts

+19-13
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
44
import { PortalUploadArgs, uploadToPortal } from '@code-pushup/portal-client';
55
import { collectAndPersistReports } from '@code-pushup/core';
66
import { MINIMAL_REPORT_MOCK } from '@code-pushup/testing-utils';
7+
import { objectToCliArgs } from '@code-pushup/utils';
78
import { DEFAULT_CLI_CONFIGURATION } from '../../../mocks/constants';
89
import { yargsCli } from '../yargs-cli';
910
import { yargsAutorunCommandObject } from './autorun-command';
@@ -16,6 +17,21 @@ vi.mock('@code-pushup/core', async () => {
1617
};
1718
});
1819

20+
const cli = (options = {}) =>
21+
yargsCli(
22+
objectToCliArgs({
23+
_: 'autorun',
24+
verbose: true,
25+
config: '/test/code-pushup.config.ts',
26+
'persist.outputDir': '/test',
27+
...options,
28+
}),
29+
{
30+
...DEFAULT_CLI_CONFIGURATION,
31+
commands: [yargsAutorunCommandObject()],
32+
},
33+
);
34+
1935
describe('autorun-command', () => {
2036
beforeEach(() => {
2137
vol.fromJSON(
@@ -28,19 +44,9 @@ describe('autorun-command', () => {
2844
});
2945

3046
it('should call collect and upload with correct parameters', async () => {
31-
await yargsCli(
32-
[
33-
'autorun',
34-
'--verbose',
35-
'--config=/test/code-pushup.config.ts',
36-
'--persist.filename=my-report',
37-
'--persist.outputDir=/test',
38-
],
39-
{
40-
...DEFAULT_CLI_CONFIGURATION,
41-
commands: [yargsAutorunCommandObject()],
42-
},
43-
).parseAsync();
47+
await cli({
48+
'persist.filename': 'my-report',
49+
}).parseAsync();
4450

4551
expect(bundleRequire).toHaveBeenCalledWith({
4652
format: 'esm',

packages/core/src/lib/implementation/persist.ts

+17-9
Original file line numberDiff line numberDiff line change
@@ -29,21 +29,23 @@ export async function persistReport(
2929
): Promise<MultipleFileResults> {
3030
const { outputDir, filename, format } = options;
3131

32-
let scoredReport = scoreReport(report);
32+
const scoredReport = scoreReport(report);
3333
console.info(reportToStdout(scoredReport));
3434

3535
// collect physical format outputs
36-
const results: { format: string; content: string }[] = [
37-
// JSON is always persisted
38-
{ format: 'json', content: JSON.stringify(report, null, 2) },
39-
];
36+
const results: { format: string; content: string }[] = [];
37+
38+
if (format.includes('json')) {
39+
results.push({
40+
format: 'json',
41+
content: JSON.stringify(report, null, 2),
42+
});
43+
}
4044

4145
if (format.includes('md')) {
42-
scoredReport = scoredReport || scoreReport(report);
4346
const commitData = await getLatestCommit();
44-
if (!commitData) {
45-
console.warn('no commit data available');
46-
}
47+
validateCommitData(commitData);
48+
4749
results.push({
4850
format: 'md',
4951
content: reportToMd(scoredReport, commitData),
@@ -81,3 +83,9 @@ export async function persistReport(
8183
export function logPersistedResults(persistResults: MultipleFileResults) {
8284
logMultipleFileResults(persistResults, 'Generated reports');
8385
}
86+
87+
function validateCommitData(commitData?: unknown) {
88+
if (!commitData) {
89+
console.warn('no commit data available');
90+
}
91+
}

packages/core/src/lib/implementation/persist.unit.test.ts

+17-2
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,11 @@ describe('persistReport', () => {
3636
);
3737
});
3838

39-
it('should create a report in json format by default', async () => {
39+
it('should create a report in json format', async () => {
4040
await persistReport(MINIMAL_REPORT_MOCK, {
4141
outputDir: MEMFS_VOLUME,
4242
filename: 'report',
43-
format: [],
43+
format: ['json'],
4444
});
4545

4646
const jsonReport: Report = JSON.parse(
@@ -58,6 +58,21 @@ describe('persistReport', () => {
5858
);
5959
});
6060

61+
it('should create a report in md format', async () => {
62+
await persistReport(MINIMAL_REPORT_MOCK, {
63+
outputDir: MEMFS_VOLUME,
64+
filename: 'report',
65+
format: ['md'],
66+
});
67+
68+
const mdReport = readFileSync(join(MEMFS_VOLUME, 'report.md')).toString();
69+
expect(mdReport).toContain('Code PushUp Report');
70+
71+
expect(() => readFileSync(join(MEMFS_VOLUME, 'report.json'))).toThrow(
72+
'no such file or directory',
73+
);
74+
});
75+
6176
it('should create a report in all formats', async () => {
6277
await persistReport(MINIMAL_REPORT_MOCK, {
6378
outputDir: MEMFS_VOLUME,

packages/models/src/lib/persist-config.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ export const persistConfigSchema = z.object({
99
filename: fileNameSchema(
1010
'Artifacts file name (without extension)',
1111
).optional(),
12-
format: z.array(formatSchema).default(['json']).optional(), // @TODO remove default or optional value and otherwise it will not set defaults.
12+
format: z.array(formatSchema).optional(),
1313
});
1414

1515
export type PersistConfig = z.infer<typeof persistConfigSchema>;

packages/models/src/lib/persist-config.unit.test.ts

+6
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,12 @@ describe('persistConfigSchema', () => {
88
expect(() => persistConfigSchema.parse(persistConfigMock)).not.toThrow();
99
});
1010

11+
it('should fill defaults', () => {
12+
const persistConfigMock = persistConfigSchema.parse(persistConfig());
13+
expect(persistConfigMock.filename).toBe('report');
14+
expect(persistConfigMock.format).toEqual(['json']);
15+
});
16+
1117
it('should throw if outputDir is invalid', () => {
1218
const persistConfigMock = persistConfig();
1319
persistConfigMock.outputDir = ' ';

testing-utils/src/lib/fixtures/configs/minimal-config.mock.ts

+1-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import type {
22
AuditOutput,
3-
CoreConfig,
43
PluginConfig,
54
RunnerConfig,
65
RunnerFunction,
@@ -46,8 +45,7 @@ export const MINIMAL_PLUGIN_CONFIG_MOCK: PluginConfig = {
4645
runner: MINIMAL_RUNNER_FUNCTION_MOCK,
4746
};
4847

49-
export const MINIMAL_CONFIG_MOCK: CoreConfig = {
50-
persist: { outputDir: '/test' },
48+
export const MINIMAL_CONFIG_MOCK = {
5149
upload: {
5250
organization: 'code-pushup',
5351
project: 'cli',

0 commit comments

Comments
 (0)