File size: 1,428 Bytes
9f5cf6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { spawn } from 'node:child_process'

export type CommandResult = {
  code: number | null
  signal: NodeJS.Signals | null
  stdout: string
  stderr: string
  durationMs: number
  timedOut: boolean
}

export function runCommand(

  command: string,

  args: string[],

  options: {

    cwd: string

    env?: Record<string, string | undefined>

    timeoutMs: number

    stdinText?: string

  },

): Promise<CommandResult> {
  return new Promise(resolve => {
    const startedAt = performance.now()
    const child = spawn(command, args, {
      cwd: options.cwd,
      env: {
        ...process.env,
        ...options.env,
      },
      stdio: 'pipe',
      windowsHide: true,
    })
    let stdout = ''
    let stderr = ''
    let timedOut = false

    child.stdout.on('data', chunk => {
      stdout += String(chunk)
    })
    child.stderr.on('data', chunk => {
      stderr += String(chunk)
    })

    if (options.stdinText !== undefined) {
      child.stdin.write(options.stdinText)
    }
    child.stdin.end()

    const timer = setTimeout(() => {
      timedOut = true
      child.kill()
    }, options.timeoutMs)

    child.on('close', (code, signal) => {
      clearTimeout(timer)
      resolve({
        code,
        signal,
        stdout,
        stderr,
        durationMs: performance.now() - startedAt,
        timedOut,
      })
    })
  })
}