git-file-names.mjs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { spawn } from "node:child_process";
  2. export function gitAddedFilesSince(cwd, { since, ref = "HEAD" }) {
  3. // Git 会给纯日期补上当前时刻和宿主时区,导致相同 ref 的准入集合随执行时间漂移。
  4. // 纯日期统一取 UTC 零点;显式时间戳沿用调用方给定的边界。
  5. const boundary = /^\d{4}-\d{2}-\d{2}$/.test(since) ? `${since}T00:00:00Z` : since;
  6. return gitFileNames(cwd, [
  7. "log",
  8. "--diff-filter=A",
  9. "--name-only",
  10. "-z",
  11. "--format=",
  12. `--since=${boundary}`,
  13. ref,
  14. ]);
  15. }
  16. export function gitFileNames(cwd, args) {
  17. return new Promise((resolve, reject) => {
  18. const child = spawn("git", args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
  19. const files = [];
  20. let pending = "";
  21. let stderr = "";
  22. // CI 持久缓存曾让 execFile 的 1 MiB 输出缓冲区溢出;流式消费路径,NUL 分隔避免转义和空白损坏。
  23. child.stdout.setEncoding("utf8");
  24. child.stdout.on("data", (chunk) => {
  25. const names = (pending + chunk).split("\0");
  26. pending = names.pop() ?? "";
  27. for (const name of names) if (name) files.push(name);
  28. });
  29. child.stderr.setEncoding("utf8");
  30. child.stderr.on("data", (chunk) => {
  31. stderr = (stderr + chunk).slice(-16 * 1024);
  32. });
  33. child.on("error", reject);
  34. child.on("close", (code, signal) => {
  35. if (code !== 0) {
  36. reject(new Error(`git ${args.join(" ")} failed (${signal ?? code}): ${stderr.trim()}`));
  37. return;
  38. }
  39. if (pending) files.push(pending);
  40. resolve(files);
  41. });
  42. });
  43. }