git-file-names.mjs 1.1 KB

123456789101112131415161718192021222324252627282930
  1. import { spawn } from "node:child_process";
  2. export function gitFileNames(cwd, args) {
  3. return new Promise((resolve, reject) => {
  4. const child = spawn("git", args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
  5. const files = [];
  6. let pending = "";
  7. let stderr = "";
  8. // CI 持久缓存曾让 execFile 的 1 MiB 输出缓冲区溢出;流式消费路径,NUL 分隔避免转义和空白损坏。
  9. child.stdout.setEncoding("utf8");
  10. child.stdout.on("data", (chunk) => {
  11. const names = (pending + chunk).split("\0");
  12. pending = names.pop() ?? "";
  13. for (const name of names) if (name) files.push(name);
  14. });
  15. child.stderr.setEncoding("utf8");
  16. child.stderr.on("data", (chunk) => {
  17. stderr = (stderr + chunk).slice(-16 * 1024);
  18. });
  19. child.on("error", reject);
  20. child.on("close", (code, signal) => {
  21. if (code !== 0) {
  22. reject(new Error(`git ${args.join(" ")} failed (${signal ?? code}): ${stderr.trim()}`));
  23. return;
  24. }
  25. if (pending) files.push(pending);
  26. resolve(files);
  27. });
  28. });
  29. }