"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExecError = exports.exec = void 0;
const logger_1 = require("@refloat/logger");
const spawn_1 = require("./spawn");
const logger = logger_1.Logger.create('exec');
async function exec(command, args, { env = process.env, cwd, output, printOutput = false } = {}) {
    logger.debug('Running command', {
        command: [command, ...args],
        cwd,
        env,
    });
    return (0, spawn_1.spawnProcess)(command, {
        args,
        cwd,
        env,
        onData(data) {
            output === null || output === void 0 ? void 0 : output(data);
            if (printOutput) {
                process.stdout.write(data.toString());
            }
        },
    });
}
exports.exec = exec;
class ExecError extends Error {
    constructor(code, error) {
        var _a;
        super((_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : String(error !== null && error !== void 0 ? error : 'Unknown error'));
        this.code = code;
    }
}
exports.ExecError = ExecError;
exec.run = async function execRun(command, args, options = {}) {
    const chunks = [];
    const code = await exec(command, args, {
        ...options,
        output: (chunk) => {
            var _a;
            chunks.push(chunk);
            (_a = options.output) === null || _a === void 0 ? void 0 : _a.call(options, chunk);
        },
    });
    const output = Buffer.concat(chunks).toString('utf-8');
    if (code === 0) {
        return output;
    }
    throw new ExecError(code, output);
};
//# sourceMappingURL=exec.js.map