From 1330276859d1b7d9199df3803f5e50323cfb3b09 Mon Sep 17 00:00:00 2001 From: Vladimir Date: Fri, 9 Aug 2024 14:57:10 +0200 Subject: [PATCH] fix(vitest): add more type guards for --merge-reports (#6307) --- packages/vitest/src/node/reporters/blob.ts | 29 ++++++++++++++++++---- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/packages/vitest/src/node/reporters/blob.ts b/packages/vitest/src/node/reporters/blob.ts index 4f780e93fa6f..961d9ed492f3 100644 --- a/packages/vitest/src/node/reporters/blob.ts +++ b/packages/vitest/src/node/reporters/blob.ts @@ -1,4 +1,4 @@ -import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises' +import { mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises' import { existsSync } from 'node:fs' import { parse, stringify } from 'flatted' import { dirname, resolve } from 'pathe' @@ -79,18 +79,37 @@ export async function readBlobs( // using process.cwd() because --merge-reports can only be used in CLI const resolvedDir = resolve(process.cwd(), blobsDirectory) const blobsFiles = await readdir(resolvedDir) - const promises = blobsFiles.map(async (file) => { - const content = await readFile(resolve(resolvedDir, file), 'utf-8') + const promises = blobsFiles.map(async (filename) => { + const fullPath = resolve(resolvedDir, filename) + const stats = await stat(fullPath) + if (!stats.isFile()) { + throw new TypeError( + `vitest.mergeReports() expects all paths in "${blobsDirectory}" to be files generated by the blob reporter, but "${filename}" is not a file`, + ) + } + const content = await readFile(fullPath, 'utf-8') const [version, files, errors, moduleKeys, coverage] = parse( content, ) as MergeReport - return { version, files, errors, moduleKeys, coverage } + if (!version) { + throw new TypeError( + `vitest.mergeReports() expects all paths in "${blobsDirectory}" to be files generated by the blob reporter, but "${filename}" is not a valid blob file`, + ) + } + return { version, files, errors, moduleKeys, coverage, file: filename } }) const blobs = await Promise.all(promises) if (!blobs.length) { throw new Error( - `vitest.mergeReports() requires at least one blob file paths in the config`, + `vitest.mergeReports() requires at least one blob file in "${blobsDirectory}" directory, but none were found`, + ) + } + + const versions = new Set(blobs.map(blob => blob.version)) + if (versions.size > 1) { + throw new Error( + `vitest.mergeReports() requires all blob files to be generated by the same Vitest version, received\n\n${blobs.map(b => `- "${b.file}" uses v${b.version}`).join('\n')}`, ) }