Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions packages/plugin-coverage/src/lib/config.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { z } from 'zod';
import { pluginScoreTargetsSchema } from '@code-pushup/models';
import { ALL_COVERAGE_TYPES } from './constants.js';

export const coverageTypeSchema = z
.enum(['function', 'branch', 'line'])
.enum(ALL_COVERAGE_TYPES)
.meta({ title: 'CoverageType' });
export type CoverageType = z.infer<typeof coverageTypeSchema>;

Expand Down Expand Up @@ -48,7 +49,7 @@ export const coveragePluginConfigSchema = z
coverageTypes: z
.array(coverageTypeSchema)
.min(1)
.default(['function', 'branch', 'line'])
.default([...ALL_COVERAGE_TYPES])
.meta({
description:
'Coverage types measured. Defaults to all available types.',
Expand Down
4 changes: 4 additions & 0 deletions packages/plugin-coverage/src/lib/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const COVERAGE_PLUGIN_SLUG = 'coverage';
export const COVERAGE_PLUGIN_TITLE = 'Code coverage';

export const ALL_COVERAGE_TYPES = ['function', 'branch', 'line'] as const;
18 changes: 13 additions & 5 deletions packages/plugin-coverage/src/lib/coverage-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ import {
type PluginConfig,
validate,
} from '@code-pushup/models';
import { capitalize } from '@code-pushup/utils';
import { logger, pluralizeToken } from '@code-pushup/utils';
import {
type CoveragePluginConfig,
type CoverageType,
coveragePluginConfigSchema,
} from './config.js';
import { COVERAGE_PLUGIN_SLUG, COVERAGE_PLUGIN_TITLE } from './constants.js';
import { formatMetaLog, typeToAuditSlug, typeToAuditTitle } from './format.js';
import { createRunnerFunction } from './runner/runner.js';
import { coverageDescription, coverageTypeWeightMapper } from './utils.js';

Expand Down Expand Up @@ -39,8 +41,8 @@ export async function coveragePlugin(

const audits = coverageConfig.coverageTypes.map(
(type): Audit => ({
slug: `${type}-coverage`,
title: `${capitalize(type)} coverage`,
slug: typeToAuditSlug(type),
title: typeToAuditTitle(type),
description: coverageDescription[type],
}),
);
Expand All @@ -58,15 +60,21 @@ export async function coveragePlugin(
})),
};

logger.info(
formatMetaLog(
`Created ${pluralizeToken('audit', audits.length)} (${coverageConfig.coverageTypes.join('/')} coverage) and 1 group`,
),
);

const packageJson = createRequire(import.meta.url)(
'../../package.json',
) as typeof import('../../package.json');

const scoreTargets = coverageConfig.scoreTargets;

return {
slug: 'coverage',
title: 'Code coverage',
slug: COVERAGE_PLUGIN_SLUG,
title: COVERAGE_PLUGIN_TITLE,
icon: 'folder-coverage-open',
description: 'Official Code PushUp code coverage plugin.',
docsUrl: 'https://www.npmjs.com/package/@code-pushup/coverage-plugin/',
Expand Down
17 changes: 17 additions & 0 deletions packages/plugin-coverage/src/lib/format.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { capitalize, pluginMetaLogFormatter } from '@code-pushup/utils';
import type { CoverageType } from './config.js';
import { COVERAGE_PLUGIN_TITLE } from './constants.js';

export const formatMetaLog = pluginMetaLogFormatter(COVERAGE_PLUGIN_TITLE);

export function typeToAuditSlug(type: CoverageType): string {
return `${type}-coverage`;
}

export function typeToAuditTitle(type: CoverageType): string {
return `${capitalize(type)} coverage`;
}

export function slugToTitle(slug: string): string {
return capitalize(slug.split('-').join(' '));
}
73 changes: 51 additions & 22 deletions packages/plugin-coverage/src/lib/nx/coverage-paths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,15 @@ import type {
import type { JestExecutorOptions } from '@nx/jest/src/executors/jest/schema';
import type { VitestExecutorOptions } from '@nx/vite/executors';
import path from 'node:path';
import { importModule, logger, stringifyError } from '@code-pushup/utils';
import {
importModule,
logger,
pluralize,
pluralizeToken,
stringifyError,
} from '@code-pushup/utils';
import type { CoverageResult } from '../config.js';
import { formatMetaLog } from '../format.js';

/**
* Resolves the cached project graph for the current Nx workspace.
Expand All @@ -21,9 +28,8 @@ async function resolveCachedProjectGraph() {
try {
return readCachedProjectGraph();
} catch (error) {
logger.info(
`Could not read cached project graph, falling back to async creation.
${stringifyError(error)}`,
logger.warn(
`Could not read cached project graph, falling back to async creation - ${stringifyError(error)}`,
);
return await createProjectGraphAsync({ exitOnError: false });
}
Expand All @@ -36,29 +42,52 @@ async function resolveCachedProjectGraph() {
export async function getNxCoveragePaths(
targets: string[] = ['test'],
): Promise<CoverageResult[]> {
logger.debug('💡 Gathering coverage from the following nx projects:');

const { nodes } = await resolveCachedProjectGraph();

const coverageResults = await Promise.all(
targets.map(async target => {
const relevantNodes = Object.values(nodes).filter(graph =>
hasNxTarget(graph, target),
);

return await Promise.all(
relevantNodes.map<Promise<CoverageResult>>(async ({ name, data }) => {
const coveragePaths = await getCoveragePathsForTarget(data, target);
logger.debug(`- ${name}: ${target}`);
return coveragePaths;
}),
);
}),
const coverageResultsPerTarget = Object.fromEntries(
await Promise.all(
targets.map(async (target): Promise<[string, CoverageResult[]]> => {
const relevantNodes = Object.values(nodes).filter(graph =>
hasNxTarget(graph, target),
);

return [
target,
await Promise.all(
relevantNodes.map(({ data }) =>
getCoveragePathsForTarget(data, target),
),
),
];
}),
),
);

logger.debug('');
const coverageResults = Object.values(coverageResultsPerTarget).flat();

logger.info(
formatMetaLog(
`Inferred ${pluralizeToken('coverage report', coverageResults.length)} from Nx projects with ${pluralize('target', targets.length)} ${
targets.length === 1
? targets[0]
: Object.entries(coverageResultsPerTarget)
.map(([target, results]) => `${target} (${results.length})`)
.join(' and ')
}`,
),
);
logger.debug(
formatMetaLog(
coverageResults
.map(
result =>
`• ${typeof result === 'string' ? result : result.resultsPath}`,
)
.join('\n'),
),
);

return coverageResults.flat();
return coverageResults;
}

function hasNxTarget(
Expand Down
Loading