@code-pushup/coverage-plugin 0.16.8 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // packages/plugin-coverage/src/lib/coverage-plugin.ts
2
- import { join as join3 } from "node:path";
2
+ import { dirname, join as join3 } from "node:path";
3
+ import { fileURLToPath } from "node:url";
3
4
 
4
5
  // packages/models/src/lib/audit.ts
5
6
  import { z as z2 } from "zod";
@@ -549,11 +550,18 @@ var reportSchema = packageVersionSchema({
549
550
  // packages/utils/src/lib/file-system.ts
550
551
  import { bundleRequire } from "bundle-require";
551
552
  import chalk from "chalk";
552
- import { mkdir, readFile, readdir, stat } from "node:fs/promises";
553
+ import { mkdir, readFile, readdir, rm, stat } from "node:fs/promises";
553
554
  import { join } from "node:path";
554
- async function readTextFile(path) {
555
- const buffer = await readFile(path);
556
- return buffer.toString();
555
+ async function ensureDirectoryExists(baseDir) {
556
+ try {
557
+ await mkdir(baseDir, { recursive: true });
558
+ return;
559
+ } catch (error) {
560
+ console.error(error.message);
561
+ if (error.code !== "EEXIST") {
562
+ throw error;
563
+ }
564
+ }
557
565
  }
558
566
  function pluginWorkDir(slug) {
559
567
  return join("node_modules", ".code-pushup", slug);
@@ -573,53 +581,23 @@ import chalk3 from "chalk";
573
581
  import CliTable3 from "cli-table3";
574
582
 
575
583
  // packages/utils/src/lib/transform.ts
576
- import { platform } from "node:os";
577
- function toUnixPath(path, options) {
578
- const unixPath = path.replace(/\\/g, "/");
579
- if (options?.toRelative) {
580
- return unixPath.replace(`${process.cwd().replace(/\\/g, "/")}/`, "");
581
- }
582
- return unixPath;
583
- }
584
- function toUnixNewlines(text) {
585
- return platform() === "win32" ? text.replace(/\r\n/g, "\n") : text;
586
- }
587
584
  function capitalize(text) {
588
585
  return `${text.charAt(0).toLocaleUpperCase()}${text.slice(
589
586
  1
590
587
  )}`;
591
588
  }
592
- function toNumberPrecision(value, decimalPlaces) {
593
- return Number(
594
- `${Math.round(
595
- Number.parseFloat(`${value}e${decimalPlaces}`)
596
- )}e-${decimalPlaces}`
597
- );
598
- }
599
- function toOrdinal(value) {
600
- if (value % 10 === 1 && value % 100 !== 11) {
601
- return `${value}st`;
602
- }
603
- if (value % 10 === 2 && value % 100 !== 12) {
604
- return `${value}nd`;
605
- }
606
- if (value % 10 === 3 && value % 100 !== 13) {
607
- return `${value}rd`;
608
- }
609
- return `${value}th`;
610
- }
611
589
 
612
590
  // packages/utils/src/lib/logging.ts
613
591
  import chalk4 from "chalk";
614
592
 
615
593
  // packages/plugin-coverage/package.json
616
594
  var name = "@code-pushup/coverage-plugin";
617
- var version = "0.16.8";
595
+ var version = "0.17.0";
618
596
 
619
597
  // packages/plugin-coverage/src/lib/config.ts
620
598
  import { z as z13 } from "zod";
621
599
  var coverageTypeSchema = z13.enum(["function", "branch", "line"]);
622
- var coverageReportSchema = z13.object({
600
+ var coverageResultSchema = z13.object({
623
601
  resultsPath: z13.string().includes("lcov"),
624
602
  pathToProject: z13.string({
625
603
  description: "Path from workspace root to project root. Necessary for LCOV reports."
@@ -635,7 +613,7 @@ var coveragePluginConfigSchema = z13.object({
635
613
  coverageTypes: z13.array(coverageTypeSchema, {
636
614
  description: "Coverage types measured. Defaults to all available types."
637
615
  }).min(1).default(["function", "branch", "line"]),
638
- reports: z13.array(coverageReportSchema, {
616
+ reports: z13.array(coverageResultSchema, {
639
617
  description: "Path to all code coverage report files. Only LCOV format is supported for now."
640
618
  }).min(1),
641
619
  perfectScoreThreshold: z13.number({
@@ -643,193 +621,80 @@ var coveragePluginConfigSchema = z13.object({
643
621
  }).gt(0).max(1).optional()
644
622
  });
645
623
 
646
- // packages/plugin-coverage/src/lib/runner/lcov/runner.ts
624
+ // packages/plugin-coverage/src/lib/runner/index.ts
625
+ import chalk5 from "chalk";
626
+ import { writeFile } from "node:fs/promises";
627
+
628
+ // packages/plugin-coverage/src/lib/utils.ts
629
+ var coverageDescription = {
630
+ branch: "Measures how many branches were executed after conditional statements in at least one test.",
631
+ line: "Measures how many lines of code were executed in at least one test.",
632
+ function: "Measures how many functions were called in at least one test."
633
+ };
634
+ function applyMaxScoreAboveThreshold(outputs, threshold) {
635
+ return outputs.map(
636
+ (output) => output.score >= threshold ? { ...output, score: 1 } : output
637
+ );
638
+ }
639
+ var coverageTypeWeightMapper = {
640
+ function: 6,
641
+ branch: 3,
642
+ line: 1
643
+ };
644
+
645
+ // packages/plugin-coverage/src/lib/runner/constants.ts
647
646
  import { join as join2 } from "node:path";
647
+ var WORKDIR = pluginWorkDir("coverage");
648
+ var RUNNER_OUTPUT_PATH = join2(WORKDIR, "runner-output.json");
649
+ var PLUGIN_CONFIG_PATH = join2(
650
+ process.cwd(),
651
+ WORKDIR,
652
+ "plugin-config.json"
653
+ );
648
654
 
649
655
  // packages/plugin-coverage/src/lib/runner/lcov/parse-lcov.ts
650
656
  import parseLcovExport from "parse-lcov";
651
657
  var godKnows = parseLcovExport;
652
658
  var parseLcov = "default" in godKnows ? godKnows.default : godKnows;
653
659
 
654
- // packages/plugin-coverage/src/lib/runner/lcov/utils.ts
655
- function calculateCoverage(hit, found) {
656
- return found > 0 ? hit / found : 1;
657
- }
658
- function mergeConsecutiveNumbers(numberArr) {
659
- return [...numberArr].sort().reduce((acc, currValue) => {
660
- const prevValue = acc.at(-1);
661
- if (prevValue != null && (prevValue.start === currValue - 1 || prevValue.end === currValue - 1)) {
662
- return [...acc.slice(0, -1), { start: prevValue.start, end: currValue }];
663
- }
664
- return [...acc, { start: currValue }];
665
- }, []);
666
- }
667
-
668
- // packages/plugin-coverage/src/lib/runner/lcov/transform.ts
669
- function lcovReportToFunctionStat(record) {
670
- return {
671
- totalFound: record.functions.found,
672
- totalHit: record.functions.hit,
673
- issues: record.functions.hit < record.functions.found ? record.functions.details.filter((detail) => !detail.hit).map(
674
- (detail) => ({
675
- message: `Function ${detail.name} is not called in any test case.`,
676
- severity: "error",
677
- source: {
678
- file: toUnixPath(record.file),
679
- position: { startLine: detail.line }
680
- }
681
- })
682
- ) : []
683
- };
684
- }
685
- function lcovReportToLineStat(record) {
686
- const missingCoverage = record.lines.hit < record.lines.found;
687
- const lines = missingCoverage ? record.lines.details.filter((detail) => !detail.hit).map((detail) => detail.line) : [];
688
- const linePositions = mergeConsecutiveNumbers(lines);
660
+ // packages/plugin-coverage/src/lib/runner/index.ts
661
+ async function createRunnerConfig(scriptPath, config) {
662
+ await ensureDirectoryExists(WORKDIR);
663
+ await writeFile(PLUGIN_CONFIG_PATH, JSON.stringify(config));
664
+ const threshold = config.perfectScoreThreshold;
689
665
  return {
690
- totalFound: record.lines.found,
691
- totalHit: record.lines.hit,
692
- issues: missingCoverage ? linePositions.map((linePosition) => {
693
- const lineReference = linePosition.end == null ? `Line ${linePosition.start} is` : `Lines ${linePosition.start}-${linePosition.end} are`;
694
- return {
695
- message: `${lineReference} not covered in any test case.`,
696
- severity: "warning",
697
- source: {
698
- file: toUnixPath(record.file),
699
- position: {
700
- startLine: linePosition.start,
701
- endLine: linePosition.end
702
- }
703
- }
704
- };
705
- }) : []
706
- };
707
- }
708
- function lcovReportToBranchStat(record) {
709
- return {
710
- totalFound: record.branches.found,
711
- totalHit: record.branches.hit,
712
- issues: record.branches.hit < record.branches.found ? record.branches.details.filter((detail) => !detail.taken).map(
713
- (detail) => ({
714
- message: `${toOrdinal(
715
- detail.branch + 1
716
- )} branch is not taken in any test case.`,
717
- severity: "error",
718
- source: {
719
- file: toUnixPath(record.file),
720
- position: { startLine: detail.line }
721
- }
722
- })
723
- ) : []
724
- };
725
- }
726
- var recordToStatFunctionMapper = {
727
- branch: lcovReportToBranchStat,
728
- line: lcovReportToLineStat,
729
- function: lcovReportToFunctionStat
730
- };
731
- function lcovCoverageToAuditOutput(stat2, coverageType) {
732
- const coverage = calculateCoverage(stat2.totalHit, stat2.totalFound);
733
- const MAX_DECIMAL_PLACES = 4;
734
- const roundedIntValue = toNumberPrecision(coverage * 100, 0);
735
- return {
736
- slug: `${coverageType}-coverage`,
737
- score: toNumberPrecision(coverage, MAX_DECIMAL_PLACES),
738
- value: roundedIntValue,
739
- displayValue: `${roundedIntValue} %`,
740
- ...stat2.issues.length > 0 && { details: { issues: stat2.issues } }
741
- };
742
- }
743
-
744
- // packages/plugin-coverage/src/lib/runner/lcov/runner.ts
745
- async function lcovResultsToAuditOutputs(reports, coverageTypes) {
746
- const parsedReports = await Promise.all(
747
- reports.map(async (report) => {
748
- const reportContent = await readTextFile(report.resultsPath);
749
- const parsedRecords = parseLcov(toUnixNewlines(reportContent));
750
- return parsedRecords.map((record) => ({
751
- ...record,
752
- file: report.pathToProject == null ? record.file : join2(report.pathToProject, record.file)
753
- }));
754
- })
755
- );
756
- if (parsedReports.length !== reports.length) {
757
- throw new Error("Some provided LCOV reports were not valid.");
758
- }
759
- const flatReports = parsedReports.flat();
760
- if (flatReports.length === 0) {
761
- throw new Error("All provided reports are empty.");
762
- }
763
- const totalCoverageStats = getTotalCoverageFromLcovReports(
764
- flatReports,
765
- coverageTypes
766
- );
767
- return coverageTypes.map((coverageType) => {
768
- const stats = totalCoverageStats[coverageType];
769
- if (!stats) {
770
- return null;
666
+ command: "node",
667
+ args: [scriptPath],
668
+ outputFile: RUNNER_OUTPUT_PATH,
669
+ ...threshold != null && {
670
+ outputTransform: (outputs) => applyMaxScoreAboveThreshold(outputs, threshold)
771
671
  }
772
- return lcovCoverageToAuditOutput(stats, coverageType);
773
- }).filter(exists);
774
- }
775
- function getTotalCoverageFromLcovReports(records, coverageTypes) {
776
- return records.reduce(
777
- (acc, report) => Object.fromEntries([
778
- ...Object.entries(acc),
779
- ...Object.entries(
780
- getCoverageStatsFromLcovRecord(report, coverageTypes)
781
- ).map(([type, stats]) => [
782
- type,
783
- {
784
- totalFound: (acc[type]?.totalFound ?? 0) + stats.totalFound,
785
- totalHit: (acc[type]?.totalHit ?? 0) + stats.totalHit,
786
- issues: [...acc[type]?.issues ?? [], ...stats.issues]
787
- }
788
- ])
789
- ]),
790
- {}
791
- );
792
- }
793
- function getCoverageStatsFromLcovRecord(record, coverageTypes) {
794
- return Object.fromEntries(
795
- coverageTypes.map((coverageType) => [
796
- coverageType,
797
- recordToStatFunctionMapper[coverageType](record)
798
- ])
799
- );
800
- }
801
-
802
- // packages/plugin-coverage/src/lib/utils.ts
803
- function applyMaxScoreAboveThreshold(outputs, threshold) {
804
- return outputs.map(
805
- (output) => output.score >= threshold ? { ...output, score: 1 } : output
806
- );
672
+ };
807
673
  }
808
674
 
809
675
  // packages/plugin-coverage/src/lib/coverage-plugin.ts
810
- var RUNNER_OUTPUT_PATH = join3(
811
- pluginWorkDir("coverage"),
812
- "runner-output.json"
813
- );
814
- function coveragePlugin(config) {
815
- const { reports, perfectScoreThreshold, coverageTypes, coverageToolCommand } = coveragePluginConfigSchema.parse(config);
816
- const audits = coverageTypes.map(
676
+ async function coveragePlugin(config) {
677
+ const coverageConfig = coveragePluginConfigSchema.parse(config);
678
+ const audits = coverageConfig.coverageTypes.map(
817
679
  (type) => ({
818
680
  slug: `${type}-coverage`,
819
681
  title: `${capitalize(type)} coverage`,
820
- description: `${capitalize(type)} coverage percentage on the project.`
682
+ description: coverageDescription[type]
821
683
  })
822
684
  );
823
- const getAuditOutputs = async () => perfectScoreThreshold ? applyMaxScoreAboveThreshold(
824
- await lcovResultsToAuditOutputs(reports, coverageTypes),
825
- perfectScoreThreshold
826
- ) : await lcovResultsToAuditOutputs(reports, coverageTypes);
827
- const runner = coverageToolCommand == null ? getAuditOutputs : {
828
- command: coverageToolCommand.command,
829
- args: coverageToolCommand.args,
830
- outputFile: RUNNER_OUTPUT_PATH,
831
- outputTransform: getAuditOutputs
685
+ const group = {
686
+ slug: "coverage",
687
+ title: "Code coverage metrics",
688
+ description: "Group containing all defined coverage types as audits.",
689
+ refs: audits.map((audit) => ({
690
+ ...audit,
691
+ weight: coverageTypeWeightMapper[audit.slug.slice(0, audit.slug.indexOf("-"))]
692
+ }))
832
693
  };
694
+ const runnerScriptPath = join3(
695
+ fileURLToPath(dirname(import.meta.url)),
696
+ "bin.js"
697
+ );
833
698
  return {
834
699
  slug: "coverage",
835
700
  title: "Code coverage",
@@ -839,12 +704,68 @@ function coveragePlugin(config) {
839
704
  packageName: name,
840
705
  version,
841
706
  audits,
842
- runner
707
+ groups: [group],
708
+ runner: await createRunnerConfig(runnerScriptPath, coverageConfig)
843
709
  };
844
710
  }
845
711
 
712
+ // packages/plugin-coverage/src/lib/nx/coverage-paths.ts
713
+ import chalk6 from "chalk";
714
+ import { join as join4 } from "node:path";
715
+ async function getNxCoveragePaths(targets = ["test"]) {
716
+ console.info(
717
+ chalk6.bold("\u{1F4A1} Gathering coverage from the following nx projects:")
718
+ );
719
+ const { createProjectGraphAsync } = await import("@nx/devkit");
720
+ const { nodes } = await createProjectGraphAsync({ exitOnError: false });
721
+ const coverageResults = targets.map((target) => {
722
+ const relevantNodes = Object.values(nodes).filter(
723
+ (graph) => hasNxTarget(graph, target)
724
+ );
725
+ return relevantNodes.map(({ name: name2, data }) => {
726
+ const targetConfig = data.targets?.[target];
727
+ const coveragePath = getCoveragePathForTarget(target, targetConfig, name2);
728
+ const rootToReportsDir = join4(data.root, coveragePath);
729
+ console.info(`- ${name2}: ${target}`);
730
+ return {
731
+ pathToProject: data.root,
732
+ resultsPath: join4(rootToReportsDir, "lcov.info")
733
+ };
734
+ });
735
+ });
736
+ console.info("\n");
737
+ return coverageResults.flat();
738
+ }
739
+ function hasNxTarget(project, target) {
740
+ return project.data.targets != null && target in project.data.targets;
741
+ }
742
+ function getCoveragePathForTarget(target, targetConfig, projectName) {
743
+ if (targetConfig.executor?.includes("@nx/vite")) {
744
+ const { reportsDirectory } = targetConfig.options;
745
+ if (reportsDirectory == null) {
746
+ throw new Error(
747
+ `Coverage configuration not found for target ${target} in ${projectName}. Define your Vitest coverage directory in the reportsDirectory option.`
748
+ );
749
+ }
750
+ return reportsDirectory;
751
+ }
752
+ if (targetConfig.executor?.includes("@nx/jest")) {
753
+ const { coverageDirectory } = targetConfig.options;
754
+ if (coverageDirectory == null) {
755
+ throw new Error(
756
+ `Coverage configuration not found for target ${target} in ${projectName}. Define your Jest coverage directory in the coverageDirectory option.`
757
+ );
758
+ }
759
+ return coverageDirectory;
760
+ }
761
+ throw new Error(
762
+ `Unsupported executor ${targetConfig.executor}. @nx/vite and @nx/jest are currently supported.`
763
+ );
764
+ }
765
+
846
766
  // packages/plugin-coverage/src/index.ts
847
767
  var src_default = coveragePlugin;
848
768
  export {
849
- src_default as default
769
+ src_default as default,
770
+ getNxCoveragePaths
850
771
  };
package/package.json CHANGED
@@ -1,12 +1,21 @@
1
1
  {
2
2
  "name": "@code-pushup/coverage-plugin",
3
- "version": "0.16.8",
3
+ "version": "0.17.0",
4
4
  "dependencies": {
5
5
  "@code-pushup/models": "*",
6
6
  "@code-pushup/utils": "*",
7
7
  "parse-lcov": "^1.0.4",
8
+ "chalk": "^5.3.0",
8
9
  "zod": "^3.22.4"
9
10
  },
11
+ "peerDependencies": {
12
+ "@nx/devkit": "^17.0.0"
13
+ },
14
+ "peerDependenciesMeta": {
15
+ "@nx/devkit": {
16
+ "optional": true
17
+ }
18
+ },
10
19
  "license": "MIT",
11
20
  "homepage": "https://github.com/code-pushup/cli#readme",
12
21
  "bugs": {
package/src/bin.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/src/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  import { coveragePlugin } from './lib/coverage-plugin';
2
2
  export default coveragePlugin;
3
3
  export type { CoveragePluginConfig } from './lib/config';
4
+ export { getNxCoveragePaths } from './lib/nx/coverage-paths';
@@ -1,7 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  export declare const coverageTypeSchema: z.ZodEnum<["function", "branch", "line"]>;
3
3
  export type CoverageType = z.infer<typeof coverageTypeSchema>;
4
- export declare const coverageReportSchema: z.ZodObject<{
4
+ export declare const coverageResultSchema: z.ZodObject<{
5
5
  resultsPath: z.ZodString;
6
6
  pathToProject: z.ZodOptional<z.ZodString>;
7
7
  }, "strip", z.ZodTypeAny, {
@@ -11,7 +11,7 @@ export declare const coverageReportSchema: z.ZodObject<{
11
11
  resultsPath: string;
12
12
  pathToProject?: string | undefined;
13
13
  }>;
14
- export type CoverageReport = z.infer<typeof coverageReportSchema>;
14
+ export type CoverageResult = z.infer<typeof coverageResultSchema>;
15
15
  export declare const coveragePluginConfigSchema: z.ZodObject<{
16
16
  coverageToolCommand: z.ZodOptional<z.ZodObject<{
17
17
  command: z.ZodString;
@@ -59,3 +59,4 @@ export declare const coveragePluginConfigSchema: z.ZodObject<{
59
59
  perfectScoreThreshold?: number | undefined;
60
60
  }>;
61
61
  export type CoveragePluginConfig = z.input<typeof coveragePluginConfigSchema>;
62
+ export type FinalCoveragePluginConfig = z.infer<typeof coveragePluginConfigSchema>;
@@ -1,6 +1,5 @@
1
1
  import type { PluginConfig } from '@code-pushup/models';
2
2
  import { CoveragePluginConfig } from './config';
3
- export declare const RUNNER_OUTPUT_PATH: string;
4
3
  /**
5
4
  * Instantiates Code PushUp code coverage plugin for core config.
6
5
  *
@@ -19,4 +18,4 @@ export declare const RUNNER_OUTPUT_PATH: string;
19
18
  *
20
19
  * @returns Plugin configuration.
21
20
  */
22
- export declare function coveragePlugin(config: CoveragePluginConfig): PluginConfig;
21
+ export declare function coveragePlugin(config: CoveragePluginConfig): Promise<PluginConfig>;
@@ -0,0 +1,6 @@
1
+ import { CoverageResult } from '../config';
2
+ /**
3
+ * @param targets nx targets to be used for measuring coverage, test by default
4
+ * @returns An array of coverage result information for the coverage plugin.
5
+ */
6
+ export declare function getNxCoveragePaths(targets?: string[]): Promise<CoverageResult[]>;
@@ -0,0 +1,3 @@
1
+ export declare const WORKDIR: string;
2
+ export declare const RUNNER_OUTPUT_PATH: string;
3
+ export declare const PLUGIN_CONFIG_PATH: string;
@@ -0,0 +1,4 @@
1
+ import type { RunnerConfig } from '@code-pushup/models';
2
+ import { FinalCoveragePluginConfig } from '../config';
3
+ export declare function executeRunner(): Promise<void>;
4
+ export declare function createRunnerConfig(scriptPath: string, config: FinalCoveragePluginConfig): Promise<RunnerConfig>;
@@ -0,0 +1,9 @@
1
+ import { AuditOutputs } from '@code-pushup/models';
2
+ import { CoverageResult, CoverageType } from '../../config';
3
+ /**
4
+ *
5
+ * @param results Paths to LCOV results
6
+ * @param coverageTypes types of coverage to be considered
7
+ * @returns Audit outputs with complete coverage data.
8
+ */
9
+ export declare function lcovResultsToAuditOutputs(results: CoverageResult[], coverageTypes: CoverageType[]): Promise<AuditOutputs>;
@@ -1,4 +1,6 @@
1
1
  import type { AuditOutputs } from '@code-pushup/models';
2
+ import { CoverageType } from './config';
3
+ export declare const coverageDescription: Record<CoverageType, string>;
2
4
  /**
3
5
  * Since more code coverage does not necessarily mean better score, this optional override allows for defining custom coverage goals.
4
6
  * @param outputs original results
@@ -6,3 +8,4 @@ import type { AuditOutputs } from '@code-pushup/models';
6
8
  * @returns Outputs with overriden score (not value) to 1 if it reached a defined threshold.
7
9
  */
8
10
  export declare function applyMaxScoreAboveThreshold(outputs: AuditOutputs, threshold: number): AuditOutputs;
11
+ export declare const coverageTypeWeightMapper: Record<CoverageType, number>;
@@ -1,9 +0,0 @@
1
- import { AuditOutputs } from '@code-pushup/models';
2
- import { CoverageReport, CoverageType } from '../../config';
3
- /**
4
- *
5
- * @param reports report files
6
- * @param coverageTypes types of coverage to be considered
7
- * @returns Audit outputs with complete coverage data.
8
- */
9
- export declare function lcovResultsToAuditOutputs(reports: CoverageReport[], coverageTypes: CoverageType[]): Promise<AuditOutputs>;