"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handler = exports.help = exports.cliOptionsTypes = exports.rcOptionsTypes = exports.commandNames = exports.shorthands = void 0;
const cli_utils_1 = require("@pnpm/cli-utils");
const config_1 = require("@pnpm/config");
const error_1 = __importDefault(require("@pnpm/error"));
const lifecycle_1 = require("@pnpm/lifecycle");
const logger_1 = __importDefault(require("@pnpm/logger"));
const sort_packages_1 = __importDefault(require("@pnpm/sort-packages"));
const existsInDir_1 = __importDefault(require("./existsInDir"));
const run_1 = require("./run");
const execa = require("execa");
const pLimit = require("p-limit");
const R = require("ramda");
const renderHelp = require("render-help");
exports.shorthands = {
    parallel: run_1.shorthands.parallel,
};
exports.commandNames = ['exec'];
function rcOptionsTypes() {
    return R.pick([
        'bail',
        'sort',
        'unsafe-perm',
        'workspace-concurrency',
    ], config_1.types);
}
exports.rcOptionsTypes = rcOptionsTypes;
exports.cliOptionsTypes = () => ({
    ...rcOptionsTypes(),
    recursive: Boolean,
});
function help() {
    return renderHelp({
        description: 'Run a command in each package.',
        descriptionLists: [
            {
                title: 'Options',
                list: [
                    run_1.PARALLEL_OPTION_HELP,
                ],
            },
        ],
        usages: ['-r exec -- <command> [args...]'],
    });
}
exports.help = help;
async function handler(opts, params) {
    var _a;
    if (!opts.recursive) {
        throw new error_1.default('EXEC_NOT_RECURSIVE', 'The "pnpm exec" command currently only works with the "-r" option');
    }
    const limitRun = pLimit((_a = opts.workspaceConcurrency) !== null && _a !== void 0 ? _a : 4);
    const result = {
        fails: [],
        passes: 0,
    };
    const chunks = opts.sort
        ? sort_packages_1.default(opts.selectedProjectsGraph)
        : [Object.keys(opts.selectedProjectsGraph).sort()];
    const existsPnp = existsInDir_1.default.bind(null, '.pnp.js');
    const workspacePnpPath = opts.workspaceDir && await existsPnp(opts.workspaceDir);
    for (const chunk of chunks) {
        await Promise.all(chunk.map((prefix) => limitRun(async () => {
            try {
                const pnpPath = workspacePnpPath !== null && workspacePnpPath !== void 0 ? workspacePnpPath : await existsPnp(prefix);
                const extraEnv = pnpPath
                    ? lifecycle_1.makeNodeRequireOption(pnpPath)
                    : {};
                await execa(params[0], params.slice(1), {
                    cwd: prefix,
                    env: {
                        ...process.env,
                        ...extraEnv,
                        PNPM_PACKAGE_NAME: opts.selectedProjectsGraph[prefix].package.manifest.name,
                    },
                    stdio: 'inherit',
                });
                result.passes++;
            }
            catch (err) {
                logger_1.default.info(err);
                if (!opts.bail) {
                    result.fails.push({
                        error: err,
                        message: err.message,
                        prefix,
                    });
                    return;
                }
                /* eslint-disable @typescript-eslint/dot-notation */
                err['code'] = 'ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL';
                err['prefix'] = prefix;
                /* eslint-enable @typescript-eslint/dot-notation */
                throw err;
            }
        })));
    }
    cli_utils_1.throwOnCommandFail('pnpm recursive exec', result);
}
exports.handler = handler;
//# sourceMappingURL=exec.js.map