marketing-touch-coverage-audit.mjs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import { readFile } from "node:fs/promises";
  2. import { execFile } from "node:child_process";
  3. import { promisify } from "node:util";
  4. import { gunzip } from "node:zlib";
  5. import { createHash } from "node:crypto";
  6. import { join, resolve } from "node:path";
  7. import { pathToFileURL } from "node:url";
  8. import coverageLibrary from "istanbul-lib-coverage";
  9. import { loadGeneratedLineEvidence } from "./marketing-source-map-evidence.mjs";
  10. import { executableSourceLines } from "./marketing-executable-lines.mjs";
  11. const { createFileCoverage } = coverageLibrary;
  12. const runGit = promisify(execFile);
  13. const unzip = promisify(gunzip);
  14. const domainPaths = {
  15. renderer: "coverage-final.json",
  16. host: "host/coverage-final.json",
  17. main: "main/coverage-final.json",
  18. cli: "cli/coverage-final.json",
  19. };
  20. export function verifySourceEvidence(file, sha256, domain, manifest) {
  21. if (
  22. manifest?.schemaVersion !== 1 ||
  23. manifest.status !== "fresh-stable" ||
  24. !Array.isArray(manifest.domains) ||
  25. !manifest.domains.includes(domain) ||
  26. !Array.isArray(manifest.changedFiles) ||
  27. manifest.changedFiles.length !== 0 ||
  28. !manifest.outputs ||
  29. Object.keys(manifest.outputs).length === 0 ||
  30. !Object.values(manifest.outputs).every(
  31. (hash) => typeof hash === "string" && /^[a-f0-9]{64}$/u.test(hash),
  32. )
  33. )
  34. return "unverified";
  35. const actual = manifest.sources?.[file];
  36. return actual === undefined ? "missing-source" : actual === sha256 ? "matched" : "mismatch";
  37. }
  38. export function changedLines(diff) {
  39. const result = new Set();
  40. for (const match of diff.matchAll(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm)) {
  41. const start = Number(match[1]);
  42. const count = match[2] === undefined ? 1 : Number(match[2]);
  43. for (let line = start; line < start + count; line++) result.add(line);
  44. }
  45. return result;
  46. }
  47. export function isBusinessSource(file) {
  48. return (
  49. /^packages\/[^/]+\/src\//u.test(file) &&
  50. /\.[cm]?[jt]sx?$/u.test(file) &&
  51. !/\.d\.ts$|\.(test|spec)\.[cm]?[jt]sx?$|\/i18n\/locales\//u.test(file)
  52. );
  53. }
  54. function expectedDomains(file) {
  55. if (file.startsWith("packages/ui/") || file.startsWith("packages/desktop/src/renderer/"))
  56. return ["renderer"];
  57. if (file.startsWith("packages/services/")) return ["host"];
  58. if (file.startsWith("packages/desktop/src/main/")) return ["main"];
  59. // shared/client 等可在多个域使用;未定义归属不能自动判错或合并。
  60. return null;
  61. }
  62. export function analyzeCoverage(file, domain, changed, data) {
  63. if (!data) return { status: "unknown", warnings: ["missing-file-coverage"] };
  64. const fc = createFileCoverage(data);
  65. const lineMap = fc.getLineCoverage();
  66. const lines = Object.entries(lineMap).filter(([line]) => changed.has(Number(line)));
  67. const functions = Object.entries(data.fnMap).filter(([, value]) =>
  68. changed.has(value.decl?.start?.line ?? value.loc.start.line),
  69. );
  70. const branches = Object.entries(data.branchMap)
  71. .filter(([, value]) => changed.has(value.line ?? value.loc.start.line))
  72. .flatMap(([id]) => data.b[id]);
  73. const warnings = [];
  74. const expected = expectedDomains(file);
  75. if (expected && !expected.includes(domain)) warnings.push("unexpected-runtime-domain");
  76. if (domain !== "renderer") {
  77. const locations = Object.values(data.statementMap);
  78. // V8 转换器可把 import/类型/空行都标为 statement,不是统一的可执行行分母。
  79. if (
  80. locations.length &&
  81. locations.every((loc) => loc.start.line === loc.end.line && loc.start.column === 0)
  82. )
  83. warnings.push("node-physical-line-map");
  84. if (!Object.keys(data.fnMap).length) warnings.push("no-function-records");
  85. }
  86. return {
  87. status: "mapped",
  88. basis: domain === "renderer" ? "renderer-istanbul-lines" : "node-raw-mapped-lines",
  89. warnings,
  90. lines: { covered: lines.filter(([, count]) => count > 0).length, total: lines.length },
  91. functions: {
  92. covered: functions.filter(([id]) => data.f[id] > 0).length,
  93. total: functions.length,
  94. },
  95. branches: { covered: branches.filter((count) => count > 0).length, total: branches.length },
  96. uncoveredLines: lines.filter(([, count]) => count === 0).map(([line]) => Number(line)),
  97. unmappedChangedLines: [...changed].filter((line) => lineMap[line] === undefined),
  98. };
  99. }
  100. export async function readReport(file) {
  101. try {
  102. return JSON.parse(await readFile(file, "utf8"));
  103. } catch (error) {
  104. if (error.code !== "ENOENT") throw error;
  105. }
  106. try {
  107. return JSON.parse((await unzip(await readFile(`${file}.gz`))).toString("utf8"));
  108. } catch (error) {
  109. if (error.code !== "ENOENT") throw error;
  110. }
  111. return null;
  112. }
  113. export async function audit(baseRef, headRef, runDirectory) {
  114. const sourceEvidence = await readReport(join(runDirectory, "build-source-evidence.json"));
  115. const git = async (...args) =>
  116. (await runGit("git", args, { maxBuffer: 32 * 1024 * 1024 })).stdout;
  117. const base = (await git("rev-parse", "--verify", `${baseRef}^{commit}`)).trim();
  118. const head = (await git("rev-parse", "--verify", `${headRef}^{commit}`)).trim();
  119. const repoRoot = (await git("rev-parse", "--show-toplevel")).trim();
  120. const generated = Object.fromEntries(
  121. await Promise.all(
  122. ["host", "main"].map(async (domain) => [
  123. domain,
  124. await loadGeneratedLineEvidence(
  125. join(repoRoot, "packages/desktop/out"),
  126. domain,
  127. sourceEvidence,
  128. ),
  129. ]),
  130. ),
  131. );
  132. const files = (await git("diff", "--name-only", "--diff-filter=AM", base, head))
  133. .trim()
  134. .split("\n")
  135. .filter(isBusinessSource);
  136. const reports = Object.fromEntries(
  137. await Promise.all(
  138. Object.entries(domainPaths).map(async ([domain, file]) => [
  139. domain,
  140. await readReport(join(runDirectory, "coverage", file)),
  141. ]),
  142. ),
  143. );
  144. const rows = [];
  145. for (const file of files) {
  146. const source = await git("show", `${head}:${file}`);
  147. const sourceSha256 = createHash("sha256").update(source).digest("hex");
  148. const changed = changedLines(await git("diff", "--unified=0", base, head, "--", file));
  149. const executable = executableSourceLines(source, file);
  150. const canonicalExecutableLines =
  151. executable.status === "mapped"
  152. ? { ...executable, lines: executable.lines.filter((line) => changed.has(line)) }
  153. : executable;
  154. const domains = {};
  155. for (const [domain, report] of Object.entries(reports)) {
  156. const matches = Object.entries(report ?? {}).filter(
  157. ([key]) => key.replaceAll("\\", "/").endsWith(`/${file}`) || key === file,
  158. );
  159. if (matches.length > 1) throw new Error(`Ambiguous source mapping: ${domain} ${file}`);
  160. domains[domain] = analyzeCoverage(file, domain, changed, matches[0]?.[1]);
  161. domains[domain].sourceIdentity = verifySourceEvidence(
  162. file,
  163. sourceSha256,
  164. domain,
  165. sourceEvidence,
  166. );
  167. const evidence = generated[domain];
  168. const generatedLines = evidence?.sources?.[resolve(repoRoot, file)];
  169. const verified =
  170. evidence?.status === "matched" && domains[domain].sourceIdentity === "matched";
  171. domains[domain].generatedMapping = {
  172. status: verified
  173. ? generatedLines
  174. ? "matched"
  175. : "source-absent"
  176. : evidence?.status === "matched"
  177. ? "unverified-source"
  178. : (evidence?.status ?? "unverified"),
  179. };
  180. if (verified && generatedLines && matches[0]) {
  181. const lineMap = createFileCoverage(matches[0][1]).getLineCoverage();
  182. const mapped = new Set(generatedLines);
  183. domains[domain].generatedMapping.positiveLinesWithoutGeneratedMapping = Object.entries(
  184. lineMap,
  185. )
  186. .filter(
  187. ([line, count]) => count > 0 && changed.has(Number(line)) && !mapped.has(Number(line)),
  188. )
  189. .map(([line]) => Number(line));
  190. }
  191. }
  192. rows.push({
  193. file,
  194. sourceSha256,
  195. changedLines: changed.size,
  196. canonicalExecutableLines,
  197. expectedDomains: expectedDomains(file),
  198. domains,
  199. });
  200. }
  201. const summaries = {};
  202. for (const domain of Object.keys(reports)) {
  203. const mapped = rows
  204. .map((row) => row.domains[domain])
  205. .filter((result) => result.status === "mapped");
  206. summaries[domain] = {
  207. sourceIdentityVerified:
  208. mapped.length > 0 && mapped.every((result) => result.sourceIdentity === "matched"),
  209. reportPresent: reports[domain] !== null,
  210. basis: domain === "renderer" ? "renderer-istanbul-lines" : "node-raw-mapped-lines",
  211. ...Object.fromEntries(
  212. ["lines", "functions", "branches"].map((metric) => [
  213. metric,
  214. mapped.reduce(
  215. (sum, row) => ({
  216. covered: sum.covered + row[metric].covered,
  217. total: sum.total + row[metric].total,
  218. }),
  219. { covered: 0, total: 0 },
  220. ),
  221. ]),
  222. ),
  223. };
  224. }
  225. return {
  226. status: "diagnostic-only",
  227. base,
  228. head,
  229. runDirectory: resolve(runDirectory),
  230. buildSourceIdentityVerified: Object.values(summaries).every(
  231. (summary) => summary.sourceIdentityVerified,
  232. ),
  233. sourceEvidenceStatus: sourceEvidence?.status ?? "missing",
  234. // 不允许调用方将多个 instrumentation 域求和/OR 后当作整体覆盖率。
  235. overallCoverage: null,
  236. limitations: [
  237. "node executable-line denominator unnormalized",
  238. "source identity not matched to build",
  239. "test outcome not validated by this diagnostic",
  240. ],
  241. summaries,
  242. unmappedFiles: rows
  243. .filter((row) => Object.values(row.domains).every((result) => result.status === "unknown"))
  244. .map((row) => row.file),
  245. rows,
  246. };
  247. }
  248. if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  249. if (process.argv.length !== 5)
  250. throw new Error(
  251. "Usage: node scripts/marketing-touch-coverage-audit.mjs <base> <head> <run-dir>",
  252. );
  253. console.log(JSON.stringify(await audit(...process.argv.slice(2)), null, 2));
  254. }