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) } }) }) }