1 | "use strict";
|
2 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
3 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
4 | };
|
5 | const cross_spawn_1 = __importDefault(require("cross-spawn"));
|
6 | const bluebird_1 = __importDefault(require("bluebird"));
|
7 | const cache_stream_1 = __importDefault(require("./cache_stream"));
|
8 | class StatusError extends Error {
|
9 | }
|
10 | function promiseSpawn(command, args = [], options = {}) {
|
11 | if (!command)
|
12 | throw new TypeError('command is required!');
|
13 | if (typeof args === 'string')
|
14 | args = [args];
|
15 | if (!Array.isArray(args)) {
|
16 | options = args;
|
17 | args = [];
|
18 | }
|
19 | return new bluebird_1.default((resolve, reject) => {
|
20 | const task = (0, cross_spawn_1.default)(command, args, options);
|
21 | const verbose = options.verbose;
|
22 | const { encoding = 'utf8' } = options;
|
23 | const stdoutCache = new cache_stream_1.default();
|
24 | const stderrCache = new cache_stream_1.default();
|
25 | if (task.stdout) {
|
26 | const stdout = task.stdout.pipe(stdoutCache);
|
27 | if (verbose)
|
28 | stdout.pipe(process.stdout);
|
29 | }
|
30 | if (task.stderr) {
|
31 | const stderr = task.stderr.pipe(stderrCache);
|
32 | if (verbose)
|
33 | stderr.pipe(process.stderr);
|
34 | }
|
35 | task.on('close', code => {
|
36 | if (code) {
|
37 | const e = new StatusError(getCache(stderrCache, encoding));
|
38 | e.code = code;
|
39 | return reject(e);
|
40 | }
|
41 | resolve(getCache(stdoutCache, encoding));
|
42 | });
|
43 | task.on('error', reject);
|
44 |
|
45 | if (!task.stdout && !task.stderr) {
|
46 | task.on('exit', code => {
|
47 | if (code) {
|
48 | const e = new StatusError('Spawn failed');
|
49 | e.code = code;
|
50 | return reject(e);
|
51 | }
|
52 | resolve();
|
53 | });
|
54 | }
|
55 | });
|
56 | }
|
57 | function getCache(stream, encoding) {
|
58 | const buf = stream.getCache();
|
59 | stream.destroy();
|
60 | if (!encoding)
|
61 | return buf;
|
62 | return buf.toString(encoding);
|
63 | }
|
64 | module.exports = promiseSpawn;
|
65 |
|
\ | No newline at end of file |