violations.mjs 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import { createHash } from "node:crypto";
  2. import path from "node:path";
  3. import { isException, isSourceFile, moduleForFile, posix } from "./policy.mjs";
  4. function fingerprint(rule, file, detail = "") {
  5. return createHash("sha256").update(`${rule}\0${file}\0${detail}`).digest("hex").slice(0, 16);
  6. }
  7. /**
  8. * 违规文件路径统一为相对 cwd 的 posix 路径。修复原因:首版写入绝对路径,fingerprint 随之含机器
  9. * 路径,baseline 在 CI 与不同开发机之间永远对不上(首版 baseline 为空所以没暴露)。
  10. */
  11. export function violation({
  12. rule,
  13. file,
  14. detail,
  15. message,
  16. module,
  17. global = false,
  18. cwd = process.cwd(),
  19. }) {
  20. const relative = path.isAbsolute(file) ? posix(path.relative(cwd, file)) : posix(file);
  21. const relativeDetail =
  22. typeof detail === "string" && path.isAbsolute(detail) && detail.startsWith(cwd)
  23. ? posix(path.relative(cwd, detail))
  24. : detail;
  25. return {
  26. rule,
  27. file: relative,
  28. module: module?.id ?? null,
  29. detail: relativeDetail,
  30. message,
  31. fingerprint: fingerprint(rule, relative, relativeDetail),
  32. global,
  33. };
  34. }
  35. export function cycleViolations(edges, policy, modulesByFile, cwd) {
  36. const state = new Map();
  37. const stack = [];
  38. const cycles = [];
  39. function visit(node) {
  40. state.set(node, 1);
  41. stack.push(node);
  42. for (const next of edges.get(node) ?? []) {
  43. if (!modulesByFile.get(next)?.managed && policy.global.managedOnly) continue;
  44. if (state.get(next) === 1) {
  45. const index = stack.indexOf(next);
  46. cycles.push(stack.slice(index).concat(next));
  47. } else if (!state.get(next)) visit(next);
  48. }
  49. stack.pop();
  50. state.set(node, 2);
  51. }
  52. for (const node of edges.keys()) if (!state.get(node)) visit(node);
  53. const unique = new Map();
  54. for (const cycle of cycles) {
  55. const detail = [...new Set(cycle)]
  56. .map((item) => posix(path.relative(cwd, item)))
  57. .sort()
  58. .join(" -> ");
  59. const file = cycle[0];
  60. unique.set(
  61. detail,
  62. violation({
  63. rule: "cycle",
  64. file,
  65. detail,
  66. module: modulesByFile.get(file),
  67. message: `检测到循环依赖:${cycle.map((item) => posix(path.relative(cwd, item))).join(" -> ")}`,
  68. global: true,
  69. cwd,
  70. }),
  71. );
  72. }
  73. return [...unique.values()];
  74. }
  75. const TEST_LIKE =
  76. /(\.(test|spec|stories)\.[cm]?[jt]sx?|\.d\.ts)$|(^|\/)(test|tests|__tests__|e2e|__mocks__|fixtures|scripts)\//;
  77. /**
  78. * unmanaged-new-file:新增源码文件必须属于 managed 模块。
  79. * 修复原因:首版 `managedOnly: true` 下,新文件只要写进 legacy 根目录(如 packages/ui/src/)就
  80. * 跳过全部规则,"新代码走这套约束"没有任何机械保证;实测在 ui 根目录新建文件深导入
  81. * services 实现,0 违规。测试、类型声明与测试目录不在此列,避免把测试也逼进 managed 模块。
  82. */
  83. export function unmanagedNewFileViolations(addedFiles, policy, cwd) {
  84. if (!policy.global.newFilesRequireManagedModule) return [];
  85. const violations = [];
  86. for (const relative of addedFiles) {
  87. const normalized = posix(relative);
  88. if (!isSourceFile(normalized) || TEST_LIKE.test(normalized)) continue;
  89. if (!policy.global.newFileScopes.some((scope) => normalized.startsWith(`${scope}/`))) continue;
  90. if (isException(policy, "unmanaged-new-file", path.resolve(cwd, relative), cwd)) continue;
  91. const module = moduleForFile(path.resolve(cwd, relative), policy);
  92. if (module?.managed) continue;
  93. violations.push(
  94. violation({
  95. cwd,
  96. rule: "unmanaged-new-file",
  97. file: path.resolve(cwd, relative),
  98. detail: module?.id ?? "unregistered",
  99. module,
  100. message: module
  101. ? `新文件落在未受管模块 ${module.id};请放入 managed 模块,或用 pnpm architecture:adopt <id> --root <dir> 为它所在目录登记模块`
  102. : "新文件不属于任何已登记模块;请用 pnpm architecture:adopt <id> --root <dir> 登记后再提交",
  103. }),
  104. );
  105. }
  106. return violations;
  107. }