commands.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { spawn, ChildProcess, SpawnOptions } from 'node:child_process';
  2. export function spawnCommand(
  3. command: string,
  4. args: string[] = [],
  5. options?: SpawnOptions
  6. ): ChildProcess {
  7. return spawn(command, args, { ...options });
  8. }
  9. export async function hasCommand(command: string): Promise<boolean> {
  10. try {
  11. await waitForCommand(spawnCommand('which', [command], { stdio: 'ignore' }));
  12. return true;
  13. } catch {
  14. return false;
  15. }
  16. }
  17. export async function waitForCommand(child: ChildProcess): Promise<number> {
  18. return new Promise((resolve, reject) => {
  19. const errorLogs: string[] = [];
  20. child.stderr?.on('data', (data) => {
  21. errorLogs.push(data.toString());
  22. });
  23. child.on('close', (code) => {
  24. if (code !== 0) {
  25. console.log(errorLogs.join(''));
  26. const message = `$(${child.spawnargs.join(' ')}) exited with code ${code}`;
  27. reject(new Error(message));
  28. } else {
  29. resolve(code);
  30. }
  31. });
  32. });
  33. }
  34. export async function readStdout(child: ChildProcess): Promise<string[]> {
  35. const stdout: string[] = [];
  36. return new Promise((resolve) => {
  37. child.stdout?.on('data', (data) => {
  38. stdout.push(data.toString());
  39. });
  40. child.on('close', () => resolve(stdout));
  41. });
  42. }