lint-staged.config.mjs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { randomUUID } from "node:crypto";
  2. import { writeFileSync } from "node:fs";
  3. function normalizePath(file) {
  4. return file.replaceAll("\\", "/");
  5. }
  6. function shellQuote(value) {
  7. if (process.platform === "win32") {
  8. // Bugfix: Windows 的 pre-push 路径会在 lint-staged 临时 GIT_INDEX_FILE 下 spawn
  9. // 返回的命令字符串;POSIX 单引号在这里可能被当成可执行参数的一部分,导致任务无法启动。
  10. return `"${value.replaceAll('"', '\\"')}"`;
  11. }
  12. return `'${value.replaceAll("'", "'\\''")}'`;
  13. }
  14. function quoteFiles(files) {
  15. return files.map(shellQuote).join(" ");
  16. }
  17. function writeFilesManifest(mode, files) {
  18. const manifestPath = `.lint-staged-vitest-${process.pid}-${randomUUID()}.json`;
  19. writeFileSync(
  20. manifestPath,
  21. JSON.stringify({
  22. mode,
  23. files,
  24. }),
  25. );
  26. return manifestPath;
  27. }
  28. function vitestCommand(mode, files) {
  29. // 不按文件拆批:重复启动 Vitest 会增加开销,related 拆批还会重复执行共同依赖的测试。
  30. // Bugfix: Windows 下 lint-staged 返回的是 shell command string,文件名里的 %PATH%
  31. // 会先被 cmd.exe 展开。文件列表写入 manifest,只把安全生成的 manifest 路径传给 Node。
  32. const manifestPath = writeFilesManifest(mode, files);
  33. return `node scripts/run-lint-staged-vitest.mjs ${mode} --files-manifest ${quoteFiles([
  34. manifestPath,
  35. ])}`;
  36. }
  37. function isRootUnitTestFile(file) {
  38. return (
  39. /^packages\/[^/]+\/test\/.*\.test\.ts$/u.test(file) &&
  40. !file.startsWith("packages/desktop/test/e2e/")
  41. );
  42. }
  43. function isRootVitestSourceFile(file) {
  44. return (
  45. file.startsWith("packages/") &&
  46. !file.startsWith("packages/desktop/test/e2e/") &&
  47. !isRootUnitTestFile(file)
  48. );
  49. }
  50. export default {
  51. "packages/*/test/**/*.test.ts": (files) => {
  52. const testFiles = files.map(normalizePath).filter(isRootUnitTestFile);
  53. if (testFiles.length === 0) {
  54. return [];
  55. }
  56. return vitestCommand("run", testFiles);
  57. },
  58. "packages/**/*.{js,jsx,ts,tsx,json}": (files) => {
  59. const sourceFiles = files.map(normalizePath).filter(isRootVitestSourceFile);
  60. if (sourceFiles.length === 0) {
  61. return [];
  62. }
  63. return vitestCommand("related", sourceFiles);
  64. },
  65. };