All files / infrastructure/scripts/src/coverage-report/adapters nx.ts

100% Statements 27/27
83.33% Branches 5/6
100% Functions 6/6
100% Lines 27/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59                1x 1x             1x 4x 4x 4x 4x 4x 4x 4x       4x   4x 1x   4x 4x 4x 4x 4x   4x 2x 2x   2x       1x 3x       1x   1x 1x        
import { spawn } from "node:child_process";
import { closeSync, mkdtempSync, openSync, readFileSync, rmSync } from "node:fs";
import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import { join } from "node:path";
import process from "node:process";
import type { ProjectTarget } from "../domain/discover.ts";
 
const TARGET = "test:coverage";
const PATH = "/usr/bin:/bin";
 
interface NxProject {
    root: string;
    targets: Record<string, { outputs?: string[] }>;
}
 
const nx = (args: string[]): Promise<string> =>
    new Promise((resolve, reject) => {
        const require = createRequire(import.meta.url);
        const nxPath = require.resolve("nx/bin/nx.js");
        const directory = mkdtempSync(join(tmpdir(), "coverage-report-nx-"));
        const output = join(directory, "project.json");
        const file = openSync(output, "w");
        const child = spawn(process.execPath, [nxPath, ...args], {
            env: { ...process.env, PATH },
            stdio: ["ignore", file, "pipe"],
        });
        let stderr = "";
 
        child.stderr?.on("data", (chunk: Buffer) => {
            stderr += chunk.toString();
        });
        child.on("error", reject);
        child.on("close", (code) => {
            closeSync(file);
            const stdout = readFileSync(output, "utf8").trim();
            rmSync(directory, { recursive: true, force: true });
 
            if (code !== 0) {
                reject(new Error(stderr.trim() || `nx ${args.join(" ")} exited with ${code}`));
                return;
            }
            resolve(stdout);
        });
    });
 
export const projectsWithCoverage = async (): Promise<ProjectTarget[]> => {
    const names = JSON.parse(
        await nx(["show", "projects", "--with-target", TARGET, "--json"]),
    ) as string[];
 
    return Promise.all(
        names.map(async (name) => {
            const project = JSON.parse(await nx(["show", "project", name, "--json"])) as NxProject;
            return { name, root: project.root, outputs: project.targets[TARGET]?.outputs ?? [] };
        }),
    );
};