git-base.mjs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import { execFile } from "node:child_process";
  2. import { promisify } from "node:util";
  3. import { selectDefaultBranchRef } from "./default-branch.mjs";
  4. import { gitAddedFilesSince, gitFileNames } from "./git-file-names.mjs";
  5. import { applyUpstreamAdmission } from "./upstream-admission.mjs";
  6. const execFileAsync = promisify(execFile);
  7. const ZERO_SHA = /^0{40}$/;
  8. async function gitOut(cwd, args) {
  9. try {
  10. const { stdout } = await execFileAsync("git", args, { cwd });
  11. return stdout.trim() || null;
  12. } catch {
  13. return null;
  14. }
  15. }
  16. async function hasCommit(cwd, ref) {
  17. return (
  18. !!ref &&
  19. !ZERO_SHA.test(ref) &&
  20. (await gitOut(cwd, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`])) !== null
  21. );
  22. }
  23. function parsePrePushInput(text) {
  24. return text
  25. .split(/\r?\n/)
  26. .map((line) => line.trim())
  27. .filter(Boolean)
  28. .map((line) => {
  29. const [localRef, localSha, remoteRef, remoteSha] = line.split(/\s+/);
  30. return localRef && localSha && remoteRef && remoteSha
  31. ? { localRef, localSha, remoteRef, remoteSha }
  32. : null;
  33. })
  34. .filter(Boolean);
  35. }
  36. /**
  37. * 选择 --changed 的比较基线。
  38. * 修复原因:首版只用 `git diff HEAD`(工作树 vs HEAD)。CI 干净 checkout 与 pre-push 时改动
  39. * 已提交,差异为空,scoped 违规只剩 cycle 等 global 规则,门禁实际不工作。
  40. * 架构检查的选择顺序:显式 > CI 变量 > pre-push stdin > upstream > 默认分支 merge-base > HEAD。
  41. */
  42. export async function resolveDiffBase(
  43. cwd = process.cwd(),
  44. { explicit = null, env = process.env } = {},
  45. ) {
  46. const pick = async (ref, label, mergeBase = false) => {
  47. if (!(await hasCommit(cwd, ref))) return null;
  48. if (!mergeBase) return { base: ref, label };
  49. const base = await gitOut(cwd, ["merge-base", "HEAD", ref]);
  50. return base ? { base, label: `merge-base ${label}` } : null;
  51. };
  52. const explicitRef =
  53. explicit ??
  54. env.ZCODE_PRE_PUSH_BASE?.trim() ??
  55. env.ZCODE_AFFECTED_TEST_BASE?.trim() ??
  56. env.ARCHITECTURE_BASE?.trim();
  57. if (explicitRef) {
  58. const chosen = await pick(explicitRef, `explicit ${explicitRef}`, true);
  59. if (!chosen) throw new Error(`显式 base 不存在或不是 commit: ${explicitRef}`);
  60. return chosen;
  61. }
  62. for (const key of [
  63. "CI_MERGE_REQUEST_DIFF_BASE_SHA",
  64. "CI_MERGE_REQUEST_TARGET_BRANCH_SHA",
  65. "CI_COMMIT_BEFORE_SHA",
  66. ]) {
  67. const chosen = await pick(env[key], `${key} ${env[key]}`);
  68. if (chosen) return chosen;
  69. }
  70. const entries = parsePrePushInput(env.ZCODE_PRE_PUSH_STDIN ?? "");
  71. if (entries.length > 0) {
  72. const head = await gitOut(cwd, ["rev-parse", "HEAD"]);
  73. const candidate =
  74. entries.find((entry) => entry.localSha === head && !ZERO_SHA.test(entry.localSha)) ??
  75. entries.find((entry) => !ZERO_SHA.test(entry.localSha));
  76. const chosen =
  77. candidate && (await pick(candidate.remoteSha, `pre-push remote ${candidate.remoteRef}`));
  78. if (chosen) return chosen;
  79. }
  80. const upstream = await gitOut(cwd, [
  81. "rev-parse",
  82. "--abbrev-ref",
  83. "--symbolic-full-name",
  84. "@{upstream}",
  85. ]);
  86. const viaUpstream = upstream && (await pick(upstream, `upstream ${upstream}`, true));
  87. if (viaUpstream) return viaUpstream;
  88. // 架构检查优先 origin/staging,其次 origin/HEAD;
  89. // 否则长期分支会把 staging 尚未合入 main 的历史差异误算成本分支新增。
  90. const originHead =
  91. (await gitOut(cwd, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"])) ?? null;
  92. const existing = new Set();
  93. for (const ref of [
  94. "origin/staging",
  95. originHead,
  96. "origin/main",
  97. "origin/master",
  98. "main",
  99. "master",
  100. ]) {
  101. if (ref && (await hasCommit(cwd, ref))) existing.add(ref);
  102. }
  103. const ref = selectDefaultBranchRef({
  104. originHead,
  105. hasCommit: (candidate) => existing.has(candidate),
  106. });
  107. const viaDefault = ref && (await pick(ref, ref, true));
  108. if (viaDefault) return viaDefault;
  109. return { base: "HEAD", label: "HEAD (仅工作树差异;未找到远端基线)" };
  110. }
  111. export async function changedFilesFromGit(cwd = process.cwd(), { base = "HEAD" } = {}) {
  112. const [diff, untracked] = await Promise.all([
  113. gitFileNames(cwd, ["diff", "--name-only", "-z", base]),
  114. gitFileNames(cwd, ["ls-files", "--others", "--exclude-standard", "-z"]),
  115. ]);
  116. return [...new Set([...diff, ...untracked])];
  117. }
  118. /**
  119. * 相对 base 新增的文件(含未跟踪)。传入 since 时,只保留"首次进入历史晚于 since"的已跟踪文件,
  120. * 未跟踪文件永远算新增。since 为空则不过滤。
  121. */
  122. export async function addedFilesFromGit(
  123. cwd = process.cwd(),
  124. {
  125. base = "HEAD",
  126. since = null,
  127. acceptedUpstreamCommits = [],
  128. acceptedUpstreamSnapshot = null,
  129. } = {},
  130. ) {
  131. const [added, untracked] = await Promise.all([
  132. gitFileNames(cwd, ["diff", "--name-only", "-z", "--diff-filter=A", base]),
  133. gitFileNames(cwd, ["ls-files", "--others", "--exclude-standard", "-z"]),
  134. ]);
  135. const untrackedSet = new Set(untracked);
  136. let enforced = added;
  137. let recent = null;
  138. if (since) {
  139. recent = new Set(await gitAddedFilesSince(cwd, { since }));
  140. enforced = added.filter((file) => untrackedSet.has(file) || recent.has(file));
  141. }
  142. return applyUpstreamAdmission(cwd, {
  143. base,
  144. candidates: [...new Set([...enforced, ...untracked])],
  145. untracked,
  146. admissions: acceptedUpstreamCommits,
  147. snapshotPath: acceptedUpstreamSnapshot,
  148. eligibleHistoryFiles: recent,
  149. });
  150. }