scope.mjs 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { resolve } from "node:path";
  2. import { git, run } from "./process.mjs";
  3. async function commit(root, ref) {
  4. try {
  5. return (await git(root, ["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`]))
  6. .toString()
  7. .trim();
  8. } catch (error) {
  9. throw new Error(`无法解析基线或提交 ${ref}:${error.message}`, { cause: error });
  10. }
  11. }
  12. async function isAncestor(root, ancestor, head) {
  13. const check = await run("git", ["merge-base", "--is-ancestor", ancestor, head], {
  14. allowFailure: true,
  15. });
  16. return check.code === 0;
  17. }
  18. // rebase / force-push 后远端 SHA 不再是 HEAD 的祖先;直接拿它当基线会让 Vitest
  19. // 找不到公共祖先而退化成全量选择。回退到双方 merge-base,永远给官方选择一个
  20. // 真实分叉点(最坏也只是比严格推送范围多选 staging 侧的新增改动,不会全量)。
  21. async function resolvePushBase(root, head, remote) {
  22. if (await isAncestor(root, remote, head)) {
  23. return remote;
  24. }
  25. return (await git(root, ["merge-base", remote, head])).toString().trim();
  26. }
  27. async function firstPushBase(root, head) {
  28. // 首次推送没有 remote SHA;只使用已确认的集成分支,缺失时严格报错,不猜测其他分支。
  29. const staging = await commit(root, "origin/staging");
  30. return (await git(root, ["merge-base", staging, head])).toString().trim();
  31. }
  32. /** 只解析比较基线;改动文件与关联测试全部由 Vitest 官方选择。 */
  33. export async function resolveScope(root, options = {}, env = process.env) {
  34. if (options.scope && !["worktree", "push"].includes(options.scope))
  35. throw new Error(`未知范围:${options.scope}`);
  36. const explicit = options.base ?? env.ZCODE_AFFECTED_TEST_BASE ?? env.ZCODE_PRE_PUSH_BASE;
  37. if (options.files && (options.scope === "push" || explicit))
  38. throw new Error("--files 不能与 push 或 --base 混用");
  39. if (options.files)
  40. return { files: [...new Set(options.files.map((file) => resolve(root, file)))], bases: [true] };
  41. if (options.scope !== "push") return { bases: [explicit ? await commit(root, explicit) : true] };
  42. // 脏工作区会让未提交代码掩盖推送版本的失败;先阻止,不自动 stash 或改写 index。
  43. if ((await git(root, ["status", "--porcelain=v1", "-z", "--untracked-files=all"])).length)
  44. throw new Error("Push 工作区不干净:请先提交或自行保存已暂存、未暂存及未跟踪改动");
  45. const head = await commit(root, "HEAD");
  46. const entries = (env.ZCODE_PRE_PUSH_STDIN ?? "")
  47. .trim()
  48. .split(/\r?\n/u)
  49. .filter(Boolean)
  50. .map((line) => line.split(/\s+/u));
  51. const bases = [];
  52. if (entries.length) {
  53. for (const entry of entries) {
  54. if (entry.length !== 4 || !/^[\da-f]+$/iu.test(entry[1]) || !/^[\da-f]+$/iu.test(entry[3]))
  55. throw new Error("推送 ref 输入无效");
  56. if (/^0+$/u.test(entry[1])) continue;
  57. if ((await commit(root, entry[1])) !== head) throw new Error("推送目标不是当前 HEAD");
  58. // hook 曾直接使用 remote SHA,导致显式基线变量失效;校验目标后优先使用调用方指定基线。
  59. bases.push(
  60. explicit
  61. ? await commit(root, explicit)
  62. : /^0+$/u.test(entry[3])
  63. ? await firstPushBase(root, head)
  64. : await resolvePushBase(root, head, await commit(root, entry[3])),
  65. );
  66. }
  67. return { bases: [...new Set(bases)], deletedOnly: !bases.length };
  68. }
  69. if (explicit) return { bases: [await commit(root, explicit)] };
  70. const upstream = await run("git", ["rev-parse", "--verify", "@{upstream}^{commit}"], {
  71. cwd: root,
  72. allowFailure: true,
  73. });
  74. return {
  75. bases: [
  76. upstream.code === 0
  77. ? await resolvePushBase(root, head, upstream.stdout.toString().trim())
  78. : await firstPushBase(root, head),
  79. ],
  80. };
  81. }