"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
// Map SIGINT & SIGTERM to process exit
// so that lockfiles are removed automatically
process
    .once('SIGINT', () => process.exit(1))
    .once('SIGTERM', () => process.exit(1));
// Patch the global fs module here at the app level
const fs = require("fs");
const gfs = require("graceful-fs");
gfs.gracefulify(fs);
const loudRejection = require("loud-rejection");
loudRejection();
const config_1 = require("@pnpm/config");
const logger_1 = require("@pnpm/logger");
const isCI = require("is-ci");
const nopt = require("nopt");
const checkForUpdates_1 = require("./checkForUpdates");
const cmd_1 = require("./cmd");
const getCommandFullName_1 = require("./getCommandFullName");
const getConfigs_1 = require("./getConfigs");
require("./logging/fileLogger");
const pnpmPkgJson_1 = require("./pnpmPkgJson");
const reporter_1 = require("./reporter");
cmd_1.default['install-test'] = cmd_1.default.installTest;
const supportedCmds = new Set([
    'add',
    'install',
    'uninstall',
    'update',
    'link',
    'prune',
    'install-test',
    'server',
    'store',
    'list',
    'unlink',
    'help',
    'root',
    'outdated',
    'rebuild',
    'recursive',
    'import',
]);
function run(argv) {
    return __awaiter(this, void 0, void 0, function* () {
        // tslint:disable
        const shortHands = {
            's': ['--loglevel', 'silent'],
            'd': ['--loglevel', 'info'],
            'dd': ['--loglevel', 'verbose'],
            'ddd': ['--loglevel', 'silly'],
            'noreg': ['--no-registry'],
            'N': ['--no-registry'],
            'reg': ['--registry'],
            'no-reg': ['--no-registry'],
            'silent': ['--loglevel', 'silent'],
            'verbose': ['--loglevel', 'verbose'],
            'quiet': ['--loglevel', 'warn'],
            'q': ['--loglevel', 'warn'],
            'h': ['--usage'],
            'H': ['--usage'],
            '?': ['--usage'],
            'help': ['--usage'],
            'v': ['--version'],
            'f': ['--force'],
            'desc': ['--description'],
            'no-desc': ['--no-description'],
            'local': ['--no-global'],
            'l': ['--long'],
            'm': ['--message'],
            'p': ['--parseable'],
            'porcelain': ['--parseable'],
            'prod': ['--production'],
            'g': ['--global'],
            'S': ['--save'],
            'D': ['--save-dev'],
            'P': ['--save-prod'],
            'E': ['--save-exact'],
            'O': ['--save-optional'],
            'y': ['--yes'],
            'n': ['--no-yes'],
            'B': ['--save-bundle'],
            'C': ['--prefix'],
        };
        // tslint:enable
        const cliConf = nopt(config_1.types, shortHands, argv, 0);
        let cmd = getCommandFullName_1.default(cliConf.argv.remain[0]) || 'help';
        if (!supportedCmds.has(cmd)) {
            cmd = 'help';
        }
        if (cliConf['dry-run']) {
            console.error(`Error: 'dry-run' is not supported yet, sorry!`);
            process.exit(1);
        }
        cliConf.save = cliConf.save || !cliConf['save-dev'] && !cliConf['save-optional'];
        let opts;
        try {
            opts = yield getConfigs_1.default(cliConf, { excludeReporter: false });
            opts.include = {
                dependencies: opts.production !== false,
                devDependencies: opts.development !== false,
                optionalDependencies: opts.optional !== false,
            };
        }
        catch (err) {
            // Reporting is not initialized at this point, so just printing the error
            console.error(err.message);
            process.exit(1);
            return;
        }
        const selfUpdate = opts.global && (cmd === 'install' || cmd === 'update') && cliConf.argv.remain.indexOf(pnpmPkgJson_1.default.name) !== -1;
        // Don't check for updates
        //   1. on CI environments
        //   2. when in the middle of an actual update
        if (!isCI && !selfUpdate) {
            checkForUpdates_1.default();
        }
        const reporterType = (() => {
            if (opts.loglevel === 'silent')
                return 'silent';
            if (opts.reporter)
                return opts.reporter;
            if (isCI || !process.stdout.isTTY)
                return 'append-only';
            return 'default';
        })();
        const subCmd = cliConf.argv.remain[1] && getCommandFullName_1.default(cliConf.argv.remain[1]);
        reporter_1.default(reporterType, {
            cmd,
            pnpmConfigs: opts,
            subCmd,
        });
        delete opts.reporter; // This is a silly workaround because supi expects a function as opts.reporter
        if (selfUpdate) {
            yield cmd_1.default.server(['stop'], opts); // tslint:disable-line:no-any
        }
        // NOTE: we defer the next stage, otherwise reporter might not catch all the logs
        yield new Promise((resolve, reject) => {
            setTimeout(() => {
                if (cliConf['shamefully-flatten'] === true) {
                    logger_1.default.info({
                        message: 'Installing a flat node_modules. Use flat node_modules only if you rely on buggy dependencies that you cannot fix.',
                        prefix: opts.prefix,
                    });
                }
                if (opts.force === true) {
                    logger_1.default.warn({
                        message: 'using --force I sure hope you know what you are doing',
                        prefix: opts.prefix,
                    });
                }
                if (cmd === 'recursive' && ['run', 'exec', 'test'].indexOf(subCmd) === -1 && cliConf.argv.cooked.indexOf('--') !== -1) {
                    opts.filter = opts.filter || [];
                    const dashDashIndex = cliConf.argv.cooked.indexOf('--');
                    Array.prototype.push.apply(opts.filter, cliConf.argv.cooked.slice(dashDashIndex + 1));
                    const afterDashDash = cliConf.argv.cooked.length - dashDashIndex - 1;
                    cliConf.argv.remain = cliConf.argv.remain.slice(0, cliConf.argv.remain.length - afterDashDash);
                }
                // `pnpm install ""` is going to be just `pnpm install`
                const cliArgs = cliConf.argv.remain.slice(1).filter(Boolean);
                try {
                    const result = cmd_1.default[cmd](cliArgs, opts, cliConf.argv.remain[0]);
                    if (result instanceof Promise) {
                        result
                            .then(resolve)
                            .catch(reject);
                    }
                    else {
                        resolve();
                    }
                }
                catch (err) {
                    reject(err);
                }
            }, 0);
        });
        logger_1.default('cli').debug('command_done');
    });
}
exports.default = run;
//# sourceMappingURL=main.js.map