check-push-worktree.mjs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { execFile } from "node:child_process";
  2. import { resolve } from "node:path";
  3. import { pathToFileURL } from "node:url";
  4. import { promisify } from "node:util";
  5. const exec = promisify(execFile);
  6. export async function checkPushWorktree(cwd = process.cwd(), env = process.env) {
  7. const git = async (...args) =>
  8. (await exec("git", args, { cwd, env, maxBuffer: 16 * 1024 * 1024 })).stdout.trim();
  9. // App 单测选择器退役后,仍须保证检查内容就是推送版本;不自动 stash 或修改 index。
  10. if (await git("status", "--porcelain=v1", "-z", "--untracked-files=all"))
  11. throw new Error("Push 工作区不干净:请先提交或自行保存已暂存、未暂存及未跟踪改动");
  12. const head = await git("rev-parse", "HEAD");
  13. for (const line of (env.ZCODE_PRE_PUSH_STDIN ?? "").split(/\r?\n/u).filter((s) => s.trim())) {
  14. const entry = line.trim().split(/\s+/u);
  15. if (
  16. entry.length !== 4 ||
  17. !/^[\da-f]{40,64}$/iu.test(entry[1]) ||
  18. !/^[\da-f]{40,64}$/iu.test(entry[3])
  19. )
  20. throw new Error("推送 ref 输入无效");
  21. if (/^0+$/u.test(entry[1])) continue;
  22. // 附注标签 SHA 指向 tag 对象;先剥离到 commit,避免发布时误拒绝指向 HEAD 的标签。
  23. const target = await git("rev-parse", "--verify", "--end-of-options", `${entry[1]}^{commit}`);
  24. if (target !== head) throw new Error("推送目标不是当前 HEAD");
  25. }
  26. }
  27. if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  28. try {
  29. await checkPushWorktree();
  30. } catch (error) {
  31. console.error(error.message);
  32. process.exitCode = 1;
  33. }
  34. }