run-affected-unit-tests.mjs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. #!/usr/bin/env node
  2. import { spawnSync } from "node:child_process";
  3. import { existsSync, mkdtempSync, rmSync } from "node:fs";
  4. import { tmpdir } from "node:os";
  5. import { delimiter, join, resolve } from "node:path";
  6. import { selectDefaultBranchRef } from "./affected-unit-test-baseline.mjs";
  7. const CODE_EXTENSIONS = new Set([
  8. ".cjs",
  9. ".cts",
  10. ".js",
  11. ".json",
  12. ".jsx",
  13. ".mjs",
  14. ".mts",
  15. ".ts",
  16. ".tsx",
  17. ]);
  18. const CHANGED_DIFF_FILTER = "ACMRTUXB";
  19. const ZERO_SHA = /^0{40}$/u;
  20. function resolvePnpmCliPath(env) {
  21. const npmExecPath = env.npm_execpath;
  22. if (
  23. npmExecPath &&
  24. (npmExecPath.toLowerCase().includes("\\pnpm\\") ||
  25. npmExecPath.toLowerCase().includes("/pnpm/"))
  26. ) {
  27. return npmExecPath;
  28. }
  29. const pathEntries = (env.PATH ?? env.Path ?? "")
  30. .split(delimiter)
  31. .map((entry) => entry.trim())
  32. .filter(Boolean);
  33. for (const pathEntry of pathEntries) {
  34. const candidate = join(pathEntry, "node_modules", "pnpm", "bin", "pnpm.cjs");
  35. if (existsSync(candidate)) {
  36. return candidate;
  37. }
  38. }
  39. return undefined;
  40. }
  41. function run(command, args, options = {}) {
  42. const spawnOptions = {
  43. cwd: options.cwd,
  44. encoding: "utf8",
  45. env: options.env,
  46. stdio: options.stdio ?? ["ignore", "pipe", "pipe"],
  47. };
  48. if (process.platform === "win32" && command === "pnpm") {
  49. // Bugfix: Windows pre-push runner 需要保持 lint-staged 传入的文件 argv 原样。
  50. // 只在本脚本内绕过 cmd shim,避免影响 bootstrap/build 共享命令入口。
  51. const cliPath = resolvePnpmCliPath(options.env ?? process.env);
  52. if (cliPath) {
  53. return spawnSync(process.execPath, [cliPath, ...args], spawnOptions);
  54. }
  55. return spawnSync("pnpm", args, { ...spawnOptions, shell: true });
  56. }
  57. return spawnSync(command, args, spawnOptions);
  58. }
  59. function runGit(args, options = {}) {
  60. const result = run("git", args, options);
  61. if (result.status !== 0 && options.required !== false) {
  62. const detail = result.stderr?.trim() || result.stdout?.trim();
  63. throw new Error(`git ${args.join(" ")} failed${detail ? `: ${detail}` : ""}`);
  64. }
  65. return result.status === 0 ? result.stdout.trim() : "";
  66. }
  67. function print(message) {
  68. console.log(`[pre-push affected tests] ${message}`);
  69. }
  70. function hasCommit(root, ref) {
  71. if (!ref) {
  72. return false;
  73. }
  74. const result = runGit(["rev-parse", "--verify", `${ref}^{commit}`], {
  75. cwd: root,
  76. required: false,
  77. });
  78. return Boolean(result);
  79. }
  80. function isZeroSha(value) {
  81. return ZERO_SHA.test(value);
  82. }
  83. function parsePrePushInput(value) {
  84. return value
  85. .split(/\r?\n/u)
  86. .map((line) => line.trim())
  87. .filter(Boolean)
  88. .map((line) => {
  89. const [localRef, localSha, remoteRef, remoteSha] = line.split(/\s+/u);
  90. if (!localRef || !localSha || !remoteRef || !remoteSha) {
  91. return undefined;
  92. }
  93. return { localRef, localSha, remoteRef, remoteSha };
  94. })
  95. .filter(Boolean);
  96. }
  97. function resolveDefaultBranchBase(root) {
  98. const originHead = runGit(["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"], {
  99. cwd: root,
  100. required: false,
  101. });
  102. const ref = selectDefaultBranchRef({
  103. originHead,
  104. hasCommit: (candidate) => hasCommit(root, candidate),
  105. });
  106. if (!ref) {
  107. return undefined;
  108. }
  109. return {
  110. base: ref,
  111. head: "HEAD",
  112. label: `default branch ${ref}`,
  113. useMergeBase: true,
  114. };
  115. }
  116. function resolvePrePushTarget(root) {
  117. const entries = parsePrePushInput(process.env.ZCODE_PRE_PUSH_STDIN ?? "");
  118. if (entries.length === 0) {
  119. return undefined;
  120. }
  121. const headSha = runGit(["rev-parse", "HEAD"], { cwd: root });
  122. const currentRef = runGit(["symbolic-ref", "--quiet", "HEAD"], {
  123. cwd: root,
  124. required: false,
  125. });
  126. const candidate =
  127. entries.find((entry) => entry.localSha === headSha && !isZeroSha(entry.localSha)) ??
  128. entries.find((entry) => entry.localRef === currentRef && !isZeroSha(entry.localSha)) ??
  129. entries.find((entry) => !isZeroSha(entry.localSha));
  130. if (!candidate) {
  131. return undefined;
  132. }
  133. if (isZeroSha(candidate.remoteSha)) {
  134. print(`${candidate.remoteRef} 是新建远端分支,pre-push stdin 没有可比较的 remote sha。`);
  135. return undefined;
  136. }
  137. if (!hasCommit(root, candidate.remoteSha) || !hasCommit(root, candidate.localSha)) {
  138. return undefined;
  139. }
  140. return {
  141. base: candidate.remoteSha,
  142. head: candidate.localSha,
  143. label: `pre-push remote ${candidate.remoteRef}`,
  144. useMergeBase: false,
  145. };
  146. }
  147. function resolveUpstreamTarget(root) {
  148. const upstream = runGit(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], {
  149. cwd: root,
  150. required: false,
  151. });
  152. if (!hasCommit(root, upstream)) {
  153. return undefined;
  154. }
  155. return {
  156. base: upstream,
  157. head: "HEAD",
  158. label: `upstream ${upstream}`,
  159. useMergeBase: false,
  160. };
  161. }
  162. function resolveDiffTarget(root) {
  163. const explicitBase =
  164. process.env.ZCODE_PRE_PUSH_BASE?.trim() || process.env.ZCODE_AFFECTED_TEST_BASE?.trim();
  165. if (explicitBase) {
  166. if (!hasCommit(root, explicitBase)) {
  167. throw new Error(`显式 base 不存在或不是 commit: ${explicitBase}`);
  168. }
  169. return {
  170. base: explicitBase,
  171. head: "HEAD",
  172. label: `explicit base ${explicitBase}`,
  173. useMergeBase: true,
  174. };
  175. }
  176. return (
  177. resolvePrePushTarget(root) ?? resolveUpstreamTarget(root) ?? resolveDefaultBranchBase(root)
  178. );
  179. }
  180. function extensionOf(file) {
  181. const match = file.match(/(\.[^./]+)$/u);
  182. return match?.[1] ?? "";
  183. }
  184. function isRootUnitTestFile(file) {
  185. return (
  186. /^packages\/[^/]+\/test\/.*\.test\.ts$/u.test(file) &&
  187. !file.startsWith("packages/desktop/test/e2e/")
  188. );
  189. }
  190. function isCodeLikeFile(file) {
  191. return CODE_EXTENSIONS.has(extensionOf(file));
  192. }
  193. function isRootVitestScope(file) {
  194. return file.startsWith("packages/") && !file.startsWith("packages/desktop/test/e2e/");
  195. }
  196. function collectPaths(value) {
  197. return value.split("\0").filter(Boolean);
  198. }
  199. function runFullUnitTests(root, reason) {
  200. print(`${reason},执行全量 pnpm run test:unit。`);
  201. return (
  202. run("pnpm", ["run", "test:unit"], {
  203. cwd: root,
  204. stdio: "inherit",
  205. }).status ?? 1
  206. );
  207. }
  208. function runLintStaged(root, base, head) {
  209. const diffRange = `${base}..${head}`;
  210. print(`执行 pnpm exec lint-staged --diff ${diffRange}`);
  211. // lint-staged 面向 pre-commit 设计,会在任务结束后自动 git add 匹配文件。
  212. // pre-push 只应验证,不应改动真实 index;因此让 lint-staged 在临时 index 上完成内部流程。
  213. const tempIndexDir = mkdtempSync(join(tmpdir(), "zcode-lint-staged-index-"));
  214. const tempIndexFile = join(tempIndexDir, "index");
  215. try {
  216. return (
  217. run(
  218. "pnpm",
  219. [
  220. "exec",
  221. "lint-staged",
  222. "--relative",
  223. "--concurrent",
  224. "false",
  225. "--diff",
  226. diffRange,
  227. "--diff-filter",
  228. CHANGED_DIFF_FILTER,
  229. "--config",
  230. "lint-staged.config.mjs",
  231. ],
  232. {
  233. cwd: root,
  234. env: {
  235. ...process.env,
  236. GIT_INDEX_FILE: tempIndexFile,
  237. },
  238. stdio: "inherit",
  239. },
  240. ).status ?? 1
  241. );
  242. } finally {
  243. rmSync(tempIndexDir, { force: true, recursive: true });
  244. }
  245. }
  246. function main() {
  247. const root = runGit(["rev-parse", "--show-toplevel"], {
  248. cwd: process.cwd(),
  249. });
  250. const target = resolveDiffTarget(root);
  251. if (!target) {
  252. return runFullUnitTests(root, "未找到可用于比较的 upstream 或默认 base");
  253. }
  254. const comparisonBase = target.useMergeBase
  255. ? runGit(["merge-base", target.base, target.head], { cwd: root })
  256. : target.base;
  257. print(`使用 ${target.label} 计算 affected 范围:${comparisonBase}..${target.head}`);
  258. const changedFiles = collectPaths(
  259. runGit(
  260. [
  261. "diff",
  262. "--name-only",
  263. "-z",
  264. `--diff-filter=${CHANGED_DIFF_FILTER}`,
  265. comparisonBase,
  266. target.head,
  267. ],
  268. { cwd: root },
  269. ),
  270. );
  271. const deletedFiles = collectPaths(
  272. runGit(["diff", "--name-only", "-z", "--diff-filter=D", comparisonBase, target.head], {
  273. cwd: root,
  274. }),
  275. );
  276. if (changedFiles.length === 0 && deletedFiles.length === 0) {
  277. print(`当前 ${target.head} 相对 ${comparisonBase} 没有变更,跳过 Vitest 单测。`);
  278. return 0;
  279. }
  280. const deletedCodeFile = deletedFiles.find(
  281. (file) => isRootVitestScope(file) && isCodeLikeFile(file),
  282. );
  283. if (deletedCodeFile) {
  284. return runFullUnitTests(root, `${deletedCodeFile} 已删除,无法交给 vitest related 分析`);
  285. }
  286. const existingFiles = changedFiles.filter((file) => existsSync(resolve(root, file)));
  287. const testFiles = existingFiles.filter(isRootUnitTestFile);
  288. const relatedSourceFiles = existingFiles.filter(
  289. (file) => isRootVitestScope(file) && isCodeLikeFile(file) && !isRootUnitTestFile(file),
  290. );
  291. if (testFiles.length === 0 && relatedSourceFiles.length === 0) {
  292. print("没有影响根 Vitest 单测范围的 JS/TS/JSON 文件,跳过 Vitest 单测。");
  293. return 0;
  294. }
  295. return runLintStaged(root, comparisonBase, target.head);
  296. }
  297. try {
  298. process.exitCode = main();
  299. } catch (error) {
  300. console.error(
  301. `[pre-push affected tests] ${error instanceof Error ? error.message : String(error)}`,
  302. );
  303. process.exitCode = 1;
  304. }