git-command-helper
Version:
github command helper for nodejs
87 lines (84 loc) • 2.47 kB
JavaScript
// git-command-helper 2.1.0 by Dimas Lanjaka <dimaslanjaka@gmail.com> (https://www.webmanajemen.com)
import Bluebird from 'bluebird';
import * as spawn$1 from 'cross-spawn';
export { spawn as crossSpawn, async as crossSpawnAsync, sync as crossSpawnSync, spawnSync } from 'cross-spawn';
export { default as spawnAsync } from './dependencies/@expo/spawn-async/build/spawnAsync.mjs';
import _ from 'lodash';
import CacheStream from './cache-stream.mjs';
/**
* spawn promise
* @param command
* @param args
* @param options
* @returns
*/
function promiseSpawn(command, args = [], options = {}) {
if (!command) throw new TypeError("command is required!");
if (typeof args === "string") args = [args];
if (!Array.isArray(args)) {
options = args;
args = [];
}
return new Bluebird((resolve, reject) => {
const task = spawn$1.spawn(command, args, options);
const verbose = options.verbose || false;
const {
encoding = "utf8"
} = options;
const stdoutCache = new CacheStream();
const stderrCache = new CacheStream();
if (task.stdout) {
const stdout = task.stdout.pipe(stdoutCache);
if (verbose) stdout.pipe(process.stdout);
}
if (task.stderr) {
const stderr = task.stderr.pipe(stderrCache);
if (verbose) stderr.pipe(process.stderr);
}
task.on("close", code => {
if (code) {
const e = new Error(getCache(stderrCache, encoding).toString());
e["code"] = code;
return reject(e);
}
resolve(getCache(stdoutCache, encoding).toString());
});
task.on("error", reject);
// Listen to exit events if neither stdout and stderr exist (inherit stdio)
if (!task.stdout && !task.stderr) {
task.on("exit", code => {
if (code) {
const e = new Error("Spawn failed");
e["code"] = code;
return reject(e);
}
resolve();
});
}
});
}
function getCache(stream, encoding) {
const buf = stream.getCache();
stream.destroy();
if (!encoding) return buf;
return buf.toString(encoding);
}
/**
* spawn async
*/
const spawn = promiseSpawn;
/**
* spawn async suppress errors
* @param command
* @param args
* @param options
* @returns
*/
const spawnSilent = async function (command, args, options) {
try {
return await promiseSpawn(command, args, options);
} catch (_err) {
return _.noop(_err);
}
};
export { promiseSpawn as default, spawn, spawnSilent };