Skip to content

Commit

Permalink
feat(core): create report-diff.md file if specified by persist.format
Browse files Browse the repository at this point in the history
  • Loading branch information
matejchalk committed Mar 19, 2024
1 parent 65a08ea commit 8c4e1e4
Show file tree
Hide file tree
Showing 5 changed files with 94 additions and 23 deletions.
13 changes: 6 additions & 7 deletions packages/cli/src/lib/compare/compare-command.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import chalk from 'chalk';
import { join } from 'node:path';
import { CommandModule } from 'yargs';
import { compareReportFiles } from '@code-pushup/core';
import { PersistConfig } from '@code-pushup/models';
Expand All @@ -23,14 +22,14 @@ export function yargsCompareCommandObject() {
};

const { before, after, persist } = options;
const outputPath = join(
persist.outputDir,
`${persist.filename}-diff.json`,
);

await compareReportFiles({ before, after }, outputPath);
const outputPaths = await compareReportFiles({ before, after }, persist);

ui().logger.info(`Reports diff written to ${chalk.bold(outputPath)}`);
ui().logger.info(
`Reports diff written to ${outputPaths
.map(path => chalk.bold(path))
.join(' and ')}`,
);
},
} satisfies CommandModule;
}
31 changes: 28 additions & 3 deletions packages/cli/src/lib/compare/compare-command.unit.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { join } from 'node:path';
import chalk from 'chalk';
import { compareReportFiles } from '@code-pushup/core';
import {
DEFAULT_PERSIST_FILENAME,
DEFAULT_PERSIST_FORMAT,
DEFAULT_PERSIST_OUTPUT_DIR,
} from '@code-pushup/models';
import { getLogMessages } from '@code-pushup/test-utils';
import { ui } from '@code-pushup/utils';
import { DEFAULT_CLI_CONFIGURATION } from '../../../mocks/constants';
import { yargsCli } from '../yargs-cli';
import { yargsCompareCommandObject } from './compare-command';
Expand All @@ -15,7 +18,12 @@ vi.mock('@code-pushup/core', async () => {
return {
...core,
autoloadRc: vi.fn().mockResolvedValue(CORE_CONFIG_MOCK),
compareReportFiles: vi.fn(),
compareReportFiles: vi
.fn()
.mockResolvedValue([
'.code-pushup/report-diff.json',
'.code-pushup/report-diff.md',
]),
};
});

Expand All @@ -30,7 +38,24 @@ describe('compare-command', () => {
Parameters<typeof compareReportFiles>
>(
{ before: 'source-report.json', after: 'target-report.json' },
join(DEFAULT_PERSIST_OUTPUT_DIR, `${DEFAULT_PERSIST_FILENAME}-diff.json`),
{
outputDir: DEFAULT_PERSIST_OUTPUT_DIR,
filename: DEFAULT_PERSIST_FILENAME,
format: DEFAULT_PERSIST_FORMAT,
},
);
});

it('should log output paths to stdout', async () => {
await yargsCli(
['compare', '--before=source-report.json', '--after=target-report.json'],
{ ...DEFAULT_CLI_CONFIGURATION, commands: [yargsCompareCommandObject()] },
).parseAsync();

expect(getLogMessages(ui().logger).at(-1)).toContain(
`Reports diff written to ${chalk.bold(
'.code-pushup/report-diff.json',
)} and ${chalk.bold('.code-pushup/report-diff.md')}`,
);
});
});
37 changes: 33 additions & 4 deletions packages/core/src/lib/compare.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
import { writeFile } from 'node:fs/promises';
import { Report, ReportsDiff, reportSchema } from '@code-pushup/models';
import { join } from 'node:path';
import {
type Format,
type PersistConfig,
Report,
ReportsDiff,
reportSchema,
} from '@code-pushup/models';
import {
Diff,
calcDuration,
generateMdReportsDiff,
readJsonFile,
scoreReport,
} from '@code-pushup/utils';
Expand All @@ -16,8 +24,10 @@ import {

export async function compareReportFiles(
inputPaths: Diff<string>,
outputPath: string,
): Promise<void> {
persistConfig: Required<PersistConfig>,
): Promise<string[]> {
const { outputDir, filename, format } = persistConfig;

const [reportBefore, reportAfter] = await Promise.all([
readJsonFile(inputPaths.before),
readJsonFile(inputPaths.after),
Expand All @@ -29,7 +39,14 @@ export async function compareReportFiles(

const reportsDiff = compareReports(reports);

await writeFile(outputPath, JSON.stringify(reportsDiff, null, 2));
return Promise.all(
format.map(async fmt => {
const outputPath = join(outputDir, `${filename}-diff.${fmt}`);
const content = reportsDiffToFileContent(reportsDiff, fmt);
await writeFile(outputPath, content);
return outputPath;
}),
);
}

export function compareReports(reports: Diff<Report>): ReportsDiff {
Expand Down Expand Up @@ -63,3 +80,15 @@ export function compareReports(reports: Diff<Report>): ReportsDiff {
duration,
};
}

function reportsDiffToFileContent(
reportsDiff: ReportsDiff,
format: Format,
): string {
switch (format) {
case 'json':
return JSON.stringify(reportsDiff, null, 2);
case 'md':
return generateMdReportsDiff(reportsDiff);
}
}
25 changes: 21 additions & 4 deletions packages/core/src/lib/compare.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
REPORT_MOCK,
reportMock,
} from '@code-pushup/test-utils';
import { Diff, readJsonFile } from '@code-pushup/utils';
import { Diff, fileExists, readJsonFile } from '@code-pushup/utils';
import { compareReportFiles, compareReports } from './compare';

describe('compareReportFiles', () => {
Expand All @@ -23,23 +23,40 @@ describe('compareReportFiles', () => {
);
});

it('should create valid reports-diff.json from report.json files', async () => {
it('should create valid report-diff.json from report.json files', async () => {
await compareReportFiles(
{
before: join(MEMFS_VOLUME, 'source-report.json'),
after: join(MEMFS_VOLUME, 'target-report.json'),
},
join(MEMFS_VOLUME, 'reports-diff.json'),
{ outputDir: MEMFS_VOLUME, filename: 'report', format: ['json'] },
);

const reportsDiffPromise = readJsonFile(
join(MEMFS_VOLUME, 'reports-diff.json'),
join(MEMFS_VOLUME, 'report-diff.json'),
);
await expect(reportsDiffPromise).resolves.toBeTruthy();

const reportsDiff = await reportsDiffPromise;
expect(() => reportsDiffSchema.parse(reportsDiff)).not.toThrow();
});

it('should create all diff files specified by persist.format', async () => {
await compareReportFiles(
{
before: join(MEMFS_VOLUME, 'source-report.json'),
after: join(MEMFS_VOLUME, 'target-report.json'),
},
{ outputDir: MEMFS_VOLUME, filename: 'report', format: ['json', 'md'] },
);

await expect(
fileExists(join(MEMFS_VOLUME, 'report-diff.json')),
).resolves.toBeTruthy();
await expect(
fileExists(join(MEMFS_VOLUME, 'report-diff.md')),
).resolves.toBeTruthy();
});
});

describe('compareReports', () => {
Expand Down
11 changes: 6 additions & 5 deletions packages/utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export { exists } from '@code-pushup/models';
export { Diff, matchArrayItemsByKey, comparePairs } from './lib/diff';
export { Diff, comparePairs, matchArrayItemsByKey } from './lib/diff';
export {
ProcessConfig,
ProcessError,
Expand Down Expand Up @@ -37,20 +37,20 @@ export {
} from './lib/formatting';
export {
formatGitPath,
getCurrentBranchOrTag,
getGitRoot,
getLatestCommit,
toGitPath,
getCurrentBranchOrTag,
safeCheckout,
toGitPath,
} from './lib/git';
export { groupByStatus } from './lib/group-by-status';
export {
isPromiseFulfilledResult,
isPromiseRejectedResult,
} from './lib/guards';
export { logMultipleResults } from './lib/log-results';
export { CliUi, Column, link, ui } from './lib/logging';
export { ProgressBar, getProgressBar } from './lib/progress';
export { logStdoutSummary } from './lib/reports/log-stdout-summary';
export {
CODE_PUSHUP_DOMAIN,
FOOTER_PREFIX,
Expand All @@ -62,6 +62,8 @@ export {
listGroupsFromAllPlugins,
} from './lib/reports/flatten-plugins';
export { generateMdReport } from './lib/reports/generate-md-report';
export { generateMdReportsDiff } from './lib/reports/generate-md-reports-diff';
export { logStdoutSummary } from './lib/reports/log-stdout-summary';
export { scoreReport } from './lib/reports/scoring';
export { sortReport } from './lib/reports/sorting';
export {
Expand Down Expand Up @@ -90,4 +92,3 @@ export {
toUnixPath,
} from './lib/transform';
export { verboseUtils } from './lib/verbose-utils';
export { link, ui, CliUi, Column } from './lib/logging';

0 comments on commit 8c4e1e4

Please sign in to comment.