You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

50 lines
1.5 KiB
JavaScript

import { spawn } from 'child_process'
export const CONTAINERS_ROOT = '/tmp/phc-run/containers'
export const getContainerPath = (ns, uuid) => `${CONTAINERS_ROOT}/${ns}/${uuid}`
export function runCommand(command, args, options = {}) {
options.stdin ??= null
options.capture ??= ['stdout', 'stderr']
console.log(`Running: ${command} ${JSON.stringify(args)}`)
return new Promise((resolve, reject) => {
const child = spawn(command, args)
let output = ''
if (options.capture.includes('stdout')) {
child.stdout.on('data', data => {
console.log('[command]', '[stdout]', JSON.stringify(data.toString()))
output += data.toString()
})
}
if (options.capture.includes('stderr')) {
child.stderr.on('data', data => {
console.log('[command]', '[stderr]', JSON.stringify(data.toString()))
output += data.toString()
})
}
if (options.stdin) {
console.log('[command]', '[stdin]', options.stdin)
child.stdin.setDefaultEncoding('utf8')
child.stdin.write(options.stdin)
child.stdin.end()
}
child.on('close', code => {
if (code === 0) {
resolve(output)
} else {
reject(new Error(`Command failed with code ${code}: ${output}`))
console.error('Command error:', output)
}
})
})
}