spawn-command.mjs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { spawnSync } from "node:child_process";
  2. const windowsShellCommandPattern = /\.(cmd|bat)$/i;
  3. const windowsShellCommandNames = new Set(["npm", "pnpm"]);
  4. export function resolveSpawnRuntimeOptions(command, platform = process.platform) {
  5. if (
  6. platform === "win32" &&
  7. (windowsShellCommandPattern.test(command) || windowsShellCommandNames.has(command))
  8. ) {
  9. return {
  10. // Windows runner 上 bare `pnpm` / `npm` 实际也是通过 cmd shim 提供。
  11. // 之前先把命令名改写成 `pnpm.cmd`,会让部分 `pnpm exec` 场景重新落回错误的包 cwd,
  12. // 最终把 tsup 入口解析成 scripts/src/... 并报“Cannot find src/main/index.ts”。
  13. // 这里保留原始命令名,只要求 shell/cmd.exe 负责解析 shim,避免再次改变 pnpm 的包上下文。
  14. shell: true,
  15. };
  16. }
  17. return {};
  18. }
  19. // shell:true 时 Node 只把 args 按空格拼接进命令行、不做转义(对应 DEP0190 警告)。
  20. // Windows 上仓库路径含空格时(如 E:\Z Code\...),pnpm --dir 的路径会被 cmd 按空格
  21. // 截断成 E:\Z 并报 ENOENT: lstat。这里按 cmd.exe 规则给含空格的参数补双引号;
  22. // 无空格参数保持原样,不影响现有无空格路径与 CI 行为。
  23. export function quoteArgsForWindowsShell(args) {
  24. return args.map((arg) => (/\s/.test(arg) ? `"${arg}"` : arg));
  25. }
  26. export function runCommand(command, args, options = {}) {
  27. const runtimeOptions = resolveSpawnRuntimeOptions(command);
  28. const spawnArgs = runtimeOptions.shell ? quoteArgsForWindowsShell(args) : args;
  29. const result = spawnSync(command, spawnArgs, {
  30. stdio: "inherit",
  31. ...options,
  32. ...runtimeOptions,
  33. });
  34. if (result.error) {
  35. throw result.error;
  36. }
  37. if (typeof result.status === "number" && result.status !== 0) {
  38. throw new Error(`${command} ${args.join(" ")} failed with code ${result.status}`);
  39. }
  40. return result;
  41. }
  42. export function runCommandAndReadStdout(command, args, options = {}) {
  43. const runtimeOptions = resolveSpawnRuntimeOptions(command);
  44. const spawnArgs = runtimeOptions.shell ? quoteArgsForWindowsShell(args) : args;
  45. const result = spawnSync(command, spawnArgs, {
  46. encoding: "utf8",
  47. ...options,
  48. ...runtimeOptions,
  49. });
  50. if (result.error) {
  51. throw result.error;
  52. }
  53. if (typeof result.status === "number" && result.status !== 0) {
  54. throw new Error(`${command} ${args.join(" ")} failed with code ${result.status}`);
  55. }
  56. return result.stdout;
  57. }