coverage-to-istanbul.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. const fs = require("fs/promises");
  2. const path = require("path");
  3. const v8toIstanbul = require("v8-to-istanbul");
  4. const covDir = "./output/coverage";
  5. const resDir = "../coverage";
  6. const basePath = path.resolve("../");
  7. const basePathRegExp = new RegExp(`${basePath}\\LabelStudio`.replace(/\\/g, "\\\\"), "g");
  8. const fixBasePath = (path) => {
  9. return path.replace(basePathRegExp, basePath);
  10. };
  11. async function loadSource(fileName) {
  12. const source = await fs.readFile(`../build/static/js/${fileName}`);
  13. return source.toString();
  14. }
  15. async function loadSourceMap(fileName) {
  16. const sourceMap = await fs.readFile(`../build/static/js/${fileName}.map`);
  17. return JSON.parse(sourceMap.toString().replace(/\/\.\//g, "/"));
  18. }
  19. const convertCoverage = async (fileName) => {
  20. if (fileName.match("_final.coverage")) return;
  21. const coverage = require(`${covDir}/${fileName}`);
  22. const basename = path.basename(fileName).replace(".coverage.json", "");
  23. const finalName = path.resolve(`${resDir}/${basename}_final.coverage.json`);
  24. for (const entry of coverage) {
  25. // Used to get file name
  26. const sourceFileName = entry.url.match(/(?:http(s)*:\/\/.*\/)(?<file>.*)/).groups.file;
  27. if (!sourceFileName) continue;
  28. const scriptSource = await loadSource(sourceFileName);
  29. const scriptSourceMap = await loadSourceMap(sourceFileName);
  30. const filePath = path.resolve(`../${sourceFileName}`);
  31. const converter = new v8toIstanbul(filePath, 0, {
  32. source: scriptSource.toString(),
  33. sourceMap: {
  34. sourcemap: scriptSourceMap,
  35. },
  36. });
  37. await converter.load();
  38. converter.applyCoverage(entry.functions);
  39. const result = JSON.stringify(
  40. converter.toIstanbul(),
  41. (key, value) => {
  42. if (key === "") {
  43. return Object.fromEntries(
  44. Object.entries(value).reduce((res, [key, val]) => {
  45. res.push([fixBasePath(key), val]);
  46. return res;
  47. }, []),
  48. );
  49. }
  50. if (key === "path") {
  51. return fixBasePath(value);
  52. }
  53. return value;
  54. },
  55. 2,
  56. );
  57. // Store converted coverage file which can later be used to generate report
  58. await fs.writeFile(finalName, result);
  59. console.log(`Processed ${basename}`);
  60. }
  61. await fs.unlink(`${covDir}/${fileName}`);
  62. };
  63. // read all the coverage file from output/coverage folder
  64. fs.readdir(covDir).then(async (files) => {
  65. for (const file of files) {
  66. await convertCoverage(file);
  67. }
  68. });