import { promisify } from 'util'
import { exec } from 'child_process'

const runCommand = promisify(exec)

const removeLastNewline = (str: string): string =>
	str.replace(/\n$/, '')

module.exports = (command: string, maxBuffer?: number): Promise<string> =>
	command === ''
		? Promise.resolve('')
		: runCommand(command, maxBuffer === undefined ? undefined : { maxBuffer }).then(({ stdout }) =>
			removeLastNewline(typeof stdout === 'string' ? stdout : '')
		).catch((error: any) =>
			Promise.reject(removeLastNewline(error.stderr))
		)