"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.exec = void 0;
const child_process_1 = require("child_process");
const git_environment_1 = require("./git-environment");
const errors_1 = require("./errors");
const ignore_closed_input_stream_1 = require("./ignore-closed-input-stream");
function exec(args, path, options) {
    const { env, gitLocation } = (0, git_environment_1.setupEnvironment)(options?.env ?? {});
    const opts = {
        cwd: path,
        env,
        encoding: options?.encoding ?? 'utf8',
        maxBuffer: options?.maxBuffer ?? Infinity,
        signal: options?.signal,
        killSignal: options?.killSignal,
    };
    return new Promise((resolve, reject) => {
        const cp = (0, child_process_1.execFile)(gitLocation, args, opts, (err, stdout, stderr) => {
            if (!err || typeof err.code === 'number') {
                const exitCode = typeof err?.code === 'number' ? err.code : 0;
                resolve({ stdout, stderr, exitCode });
                return;
            }
            // If the error's code is a string then it means the code isn't the
            // process's exit code but rather an error coming from Node's bowels,
            // e.g., ENOENT.
            let { message } = err;
            if (err.code === 'ENOENT') {
                message =
                    `ENOENT: Git failed to execute. This typically means that ` +
                        `the path provided doesn't exist or that the Git executable ` +
                        `could not be found which could indicate a problem with the ` +
                        `packaging of dugite. Verify that resolveGitBinary returns a ` +
                        `valid path to the git binary.`;
            }
            reject(new errors_1.ExecError(message, stdout, stderr, err));
        });
        (0, ignore_closed_input_stream_1.ignoreClosedInputStream)(cp);
        if (options?.stdin !== undefined && cp.stdin) {
            // See https://github.com/nodejs/node/blob/7b5ffa46fe4d2868c1662694da06eb55ec744bde/test/parallel/test-stdin-pipe-large.js
            if (options.stdinEncoding) {
                cp.stdin.end(options.stdin, options.stdinEncoding);
            }
            else {
                cp.stdin.end(options.stdin);
            }
        }
        options?.processCallback?.(cp);
    });
}
exports.exec = exec;
//# sourceMappingURL=exec.js.map