"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 });
const logger_1 = require("@pnpm/logger");
const modules_yaml_1 = require("@pnpm/modules-yaml");
const utils_1 = require("@pnpm/utils");
const mkdirp = require("mkdirp-promise");
const normalizePath = require("normalize-path");
const path = require("path");
const removeAllExceptOuterLinks = require("remove-all-except-outer-links");
const writePkg = require("write-pkg");
const readShrinkwrapFiles_1 = require("../readShrinkwrapFiles");
const checkCompatibility_1 = require("./checkCompatibility");
function getContext(opts, installType) {
    return __awaiter(this, void 0, void 0, function* () {
        const root = normalizePath(opts.prefix);
        const storePath = opts.store;
        const modulesPath = path.join(root, 'node_modules');
        const modules = yield modules_yaml_1.read(modulesPath);
        if (modules) {
            try {
                if (Boolean(modules.independentLeaves) !== opts.independentLeaves) {
                    if (modules.independentLeaves) {
                        throw new Error(`This node_modules was installed with --independent-leaves option.
            Use this option or run same command with --force to recreated node_modules`);
                    }
                    throw new Error(`This node_modules was not installed with the --independent-leaves option.
          Don't use --independent-leaves run same command with --force to recreated node_modules`);
                }
                if (Boolean(modules.shamefullyFlatten) !== opts.shamefullyFlatten) {
                    if (modules.shamefullyFlatten) {
                        throw new Error(`This node_modules was installed with --shamefully-flatten option.
            Use this option or run same command with --force to recreated node_modules`);
                    }
                    throw new Error(`This node_modules was not installed with the --shamefully-flatten option.
          Don't use --shamefully-flatten or run same command with --force to recreated node_modules`);
                }
                checkCompatibility_1.default(modules, { storePath, modulesPath });
            }
            catch (err) {
                if (!opts.force)
                    throw err;
                if (installType !== 'general') {
                    throw new Error('Named installation cannot be used to regenerate the node_modules structure. Run pnpm install --force');
                }
                logger_1.default.info(`Recreating ${modulesPath}`);
                yield removeAllExceptOuterLinks(modulesPath);
                return getContext(opts);
            }
        }
        const files = yield Promise.all([
            (opts.global ? readGlobalPkgJson(opts.prefix) : utils_1.safeReadPackageFromDir(opts.prefix)),
            mkdirp(storePath),
        ]);
        const pkg = files[0] || {};
        const ctx = Object.assign({ hoistedAliases: modules && modules.hoistedAliases || {}, pendingBuilds: modules && modules.pendingBuilds || [], pkg: opts.hooks && opts.hooks.readPackage ? opts.hooks.readPackage(pkg) : pkg, root, skipped: new Set(modules && modules.skipped || []), storePath }, yield readShrinkwrapFiles_1.default(opts));
        utils_1.packageJsonLogger.debug({ initial: ctx.pkg });
        return ctx;
    });
}
exports.default = getContext;
const DefaultGlobalPkg = {
    name: 'pnpm-global-pkg',
    private: true,
    version: '1.0.0',
};
function readGlobalPkgJson(globalPkgPath) {
    return __awaiter(this, void 0, void 0, function* () {
        const globalPkgJson = yield utils_1.safeReadPackageFromDir(globalPkgPath);
        if (globalPkgJson)
            return globalPkgJson;
        yield writePkg(globalPkgPath, DefaultGlobalPkg);
        return DefaultGlobalPkg;
    });
}
//# sourceMappingURL=getContext.js.map