"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 path = require("path");
const readPkg_1 = require("../fs/readPkg");
const writePkg = require("write-pkg");
const expandTilde_1 = require("../fs/expandTilde");
const pnpm_shrinkwrap_1 = require("pnpm-shrinkwrap");
const modulesController_1 = require("../fs/modulesController");
const mkdirp = require("mkdirp-promise");
const normalizePath = require("normalize-path");
const removeAllExceptOuterLinks = require("remove-all-except-outer-links");
const pnpm_logger_1 = require("pnpm-logger");
const checkCompatibility_1 = require("./checkCompatibility");
const STORE_VERSION = '2';
function getContext(opts, installType) {
    return __awaiter(this, void 0, void 0, function* () {
        const pkg = yield (opts.global ? readGlobalPkgJson(opts.prefix) : readPkg_1.fromDir(opts.prefix));
        const root = normalizePath(opts.prefix);
        const storeBasePath = resolveStoreBasePath(opts.store, root);
        const storePath = path.join(storeBasePath, STORE_VERSION);
        const modulesPath = path.join(root, 'node_modules');
        let modules = yield modulesController_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`);
                }
                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');
                }
                pnpm_logger_1.default.info(`Recreating ${modulesPath}`);
                yield removeAllExceptOuterLinks(modulesPath);
                return getContext(opts);
            }
        }
        const shrinkwrap = yield pnpm_shrinkwrap_1.read(root, { force: opts.force, registry: opts.registry });
        const ctx = {
            pkg,
            root,
            storePath,
            shrinkwrap,
            privateShrinkwrap: yield pnpm_shrinkwrap_1.readPrivate(root, { force: opts.force, registry: opts.registry }),
            skipped: new Set(modules && modules.skipped || []),
        };
        yield mkdirp(ctx.storePath);
        return ctx;
    });
}
exports.default = getContext;
const DefaultGlobalPkg = {
    name: 'pnpm-global-pkg',
    version: '1.0.0',
    private: true,
};
function readGlobalPkgJson(globalPkgPath) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const globalPkgJson = yield readPkg_1.fromDir(globalPkgPath);
            return globalPkgJson;
        }
        catch (err) {
            yield writePkg(globalPkgPath, DefaultGlobalPkg);
            return DefaultGlobalPkg;
        }
    });
}
function resolveStoreBasePath(storePath, pkgRoot) {
    if (expandTilde_1.isHomepath(storePath)) {
        return expandTilde_1.default(storePath);
    }
    return path.resolve(pkgRoot, storePath);
}
//# sourceMappingURL=getContext.js.map