ci-changes.mjs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { spawnSync } from "node:child_process";
  2. import { appendFileSync, readFileSync } from "node:fs";
  3. import { fileURLToPath } from "node:url";
  4. import path from "node:path";
  5. export function classifyChanges(files) {
  6. // Unknown paths, empty comparisons and release metadata always get full CI.
  7. const documentation = (p) =>
  8. [
  9. "README.md",
  10. "README_ZH.md",
  11. "CONTRIBUTING.md",
  12. ".github/PULL_REQUEST_TEMPLATE.md",
  13. ].includes(p) ||
  14. /^docs\/(?:[^/]+\/)*[^/]+\.md$/u.test(p) ||
  15. /^docs\/assets\/[^/]+\.(?:png|jpg|svg|gif|mp4)$/u.test(p);
  16. return {
  17. docsOnly: files.length > 0 && files.every(documentation),
  18. };
  19. }
  20. if (
  21. process.argv[1] &&
  22. path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
  23. ) {
  24. const event = JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, "utf8"));
  25. const base =
  26. process.env.GITHUB_EVENT_NAME === "pull_request"
  27. ? event.pull_request?.base?.sha
  28. : process.env.GITHUB_EVENT_NAME === "push"
  29. ? event.before
  30. : undefined;
  31. let result = { docsOnly: false };
  32. if (/^[a-f0-9]{40}$/u.test(base ?? "") && !/^0+$/u.test(base)) {
  33. // --no-renames includes both removed and added paths, preventing a code file
  34. // renamed into docs from becoming an accidental documentation-only change.
  35. const diff = spawnSync(
  36. "git",
  37. ["diff", "--name-only", "--no-renames", "-z", base, "HEAD"],
  38. { encoding: "utf8" },
  39. );
  40. if (diff.status === 0)
  41. result = classifyChanges(diff.stdout.split("\0").filter(Boolean));
  42. }
  43. const output = `docs_only=${result.docsOnly}\n`;
  44. console.log(output.trim());
  45. if (process.env.GITHUB_OUTPUT)
  46. appendFileSync(process.env.GITHUB_OUTPUT, output);
  47. }