// // Copyright 2021 DXOS.org // import fs from 'fs'; const chalk = require('chalk'); import { exec, spawn } from 'child_process'; export const sorter = (p: string) => ({ [p]: a }: any, { [p]: b }: any) => a < b ? -1 : a > b ? 1 : 0; export const printKeyValue = (key: string, value: string, color = 'grey', pad = 12) => { const left = key ? `- ${key}:` : '' console.log(`${(left).padEnd(pad - 1, ' ')} ${chalk[color](value)}`); } export const deleteFile = (file: string) => { fs.existsSync(file) && fs.unlinkSync(file); } export const writeFile = (file: string, text: string) => { fs.writeFileSync(file, text); } // TODO(burdon): Change to spawn for streaming results. // https://stackoverflow.com/questions/10232192/exec-display-stdout-live export const asyncExec = async (cmd: string, verbose?: boolean) => { return new Promise((resolve, reject) => { exec(cmd, (error, stdout, stderr) => { if (error) { if (verbose) { console.error(stderr); } reject(error); } else { resolve(stdout.trim()); } }); }); }; // TODO(burdon): See spawn.ts export const asyncSpawn = async (cmd: string, args: any[], logger = console.log) => { return new Promise((resolve, reject) => { const child = spawn(cmd, args); child.stdout.on('data', (data) => { logger(data.toString()); }); child.stderr.on('data', (data) => { console.error(data.toString()); reject(data); }); child.on('exit', (code: number) => { resolve(code); }); }); }