UNPKG

runok

Version:

NPM scripts on steroids! Replace your scripts with pure JS

88 lines (87 loc) 2.67 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ExecConfig = void 0; const task_1 = require("../task"); const result_1 = require("../result"); const child_process_1 = require("child_process"); /** * Executes shell command and returns a promise. * * ```js * await exec('ls -ll'); * ``` * A second parameter can be used to pass in [ExecOptions](https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback) from "child_process" module: * * ```js * await exec('rails s', { env: { RAILS_ENV: 'production' } }) * ``` * * To hide output pass in `output: false`: * * ```js * await exec('docker build', { output: false }); * ``` * */ async function exec(command, config) { const cfg = new ExecConfig(command); cfg.apply(config); return new Promise((resolve, reject) => { let result = result_1.Result.start(cfg.TASK, cfg.command); const event = child_process_1.exec(cfg.command, cfg.execOptions, (error, stdout, stderr) => { if (error) { Object.assign(result, { stdout, stderr, error }); return resolve(result.fail(error, { stdout, stderr })); } resolve(result.success({ stdout, stderr })); }); process.on('SIGINT', () => { process.stdin.resume(); event.kill('SIGINT'); }); if (!event.stdout) return; if (cfg.hasOutput) event.stdout.on('data', (data) => process.stdout.write(data)); if (cfg.hasOutput) event.stdout.on('error', (error) => process.stderr.write(result.output.error(error))); }); } exports.default = exec; class ExecConfig extends task_1.TaskConfig { constructor(command) { super(); this.TASK = 'exec'; this.hasOutput = true; this.command = command; } applyOptions(opts) { this.execOptions = opts; if (opts['output'] !== undefined) { this.silent(!opts['output']); } } prefix(prefix) { this.command = `${prefix} ${this.command}`; } opt(option, value = '') { this.command += ` --${option} ${value}`; } env(variable, value) { if (!this.execOptions.env) { this.execOptions.env = process.env; } this.execOptions.env[variable] = value; this.prefix(`${variable}=${value}`); return this; } arg(arg = '') { this.command += ` ${arg}`; return this; } silent(silent = true) { this.hasOutput = !silent; return this; } } exports.ExecConfig = ExecConfig;