process.mjs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { spawn } from "node:child_process";
  2. export function run(
  3. command,
  4. args,
  5. { cwd, env = process.env, input, inherit = false, allowFailure = false } = {},
  6. ) {
  7. return new Promise((resolve, reject) => {
  8. const child = spawn(command, args, {
  9. cwd,
  10. env,
  11. shell: false,
  12. stdio: ["pipe", inherit ? "inherit" : "pipe", inherit ? "inherit" : "pipe"],
  13. });
  14. const stdout = [],
  15. stderr = [];
  16. child.stdout?.on("data", (chunk) => stdout.push(chunk));
  17. child.stderr?.on("data", (chunk) => stderr.push(chunk));
  18. child.on("error", reject);
  19. child.stdin.on("error", (error) => {
  20. if (error.code !== "EPIPE") reject(error);
  21. });
  22. child.stdin.end(input);
  23. child.on("close", (code, signal) => {
  24. const result = {
  25. code: code ?? 1,
  26. stdout: Buffer.concat(stdout),
  27. stderr: Buffer.concat(stderr),
  28. };
  29. if (result.code && !allowFailure)
  30. reject(
  31. new Error(
  32. `${command} ${args[0] ?? ""}: ${result.stderr.toString().trim() || signal || result.code}`,
  33. ),
  34. );
  35. else resolve(result);
  36. });
  37. });
  38. }
  39. export async function git(root, args, options = {}) {
  40. return (await run("git", args, { cwd: root, ...options })).stdout;
  41. }
  42. export async function cleanGitEnv(root, env = process.env) {
  43. const names = (await git(root, ["rev-parse", "--local-env-vars"]))
  44. .toString()
  45. .trim()
  46. .split(/\r?\n/u);
  47. const clean = { ...env };
  48. for (const name of names) delete clean[name];
  49. return clean;
  50. }