"use strict";
const child_process = require("child_process");
function execSync(command, opts) {
    try {
        return child_process.execSync(command, opts);
    }
    catch (err) {
        if (opts && opts.skipError) {
            return err;
        }
        else {
            throw (new Error(`Error ${err.message} while executing ${command}.`));
        }
    }
}
exports.execSync = execSync;
function spawnSync(command, args, opts) {
    try {
        return child_process.spawnSync(command, args, opts);
    }
    catch (err) {
        if (opts && opts.skipError) {
            return err;
        }
        else {
            throw (new Error(`Error ${err.message} while executing ${command}.`));
        }
    }
}
exports.spawnSync = spawnSync;
function spawn(command, args, opts) {
    return new Promise((resolve, reject) => {
        let capturedOut = "";
        let capturedErr = "";
        let childProcess = child_process.spawn(command, args);
        if (childProcess.stdout) {
            childProcess.stdout.on("data", (data) => {
                capturedOut += data;
            });
        }
        if (childProcess.stderr) {
            childProcess.stderr.on("data", (data) => {
                capturedErr += data;
            });
        }
        childProcess.on("close", (arg) => {
            var exitCode = typeof arg === 'number' ? arg : arg && arg.code;
            if (exitCode === 0) {
                resolve(capturedOut ? capturedOut.trim() : null);
            }
            else {
                if (opts && opts.skipError) {
                    resolve(capturedErr);
                }
                else {
                    reject(new Error(`Command ${command} with arguments ${args.join(" ")} failed with exit code ${exitCode}. Error output:\n ${capturedErr}`));
                }
            }
        });
    });
}
exports.spawn = spawn;
