"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 shrinkwrap_1 = require("../fs/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");
function getContext(opts, installType) {
    return __awaiter(this, void 0, void 0, function* () {
        const pkg = yield (opts.global ? readGlobalPkg(opts.prefix) : readPkg_1.ignoreCache(opts.prefix));
        const root = normalizePath(opts.prefix);
        const storeBasePath = resolveStoreBasePath(opts.storePath, root);
        const storePath = getStorePath(storeBasePath);
        const modulesPath = path.join(root, 'node_modules');
        let modules = yield modulesController_1.read(modulesPath);
        if (modules) {
            try {
                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 shrinkwrap_1.read(root, { force: opts.force, registry: opts.registry });
        const ctx = {
            pkg,
            root,
            storePath,
            shrinkwrap,
            privateShrinkwrap: yield shrinkwrap_1.readPrivate(root, { force: opts.force, registry: opts.registry }),
            skipped: modules && modules.skipped || [],
        };
        yield mkdirp(ctx.storePath);
        return ctx;
    });
}
exports.default = getContext;
function readGlobalPkg(globalPath) {
    return __awaiter(this, void 0, void 0, function* () {
        const globalPkgPath = path.resolve(globalPath, 'package.json');
        return yield readGlobalPkgJson(globalPkgPath);
    });
}
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.ignoreCache(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);
}
function getStorePath(storeBasePath) {
    if (underNodeModules(storeBasePath)) {
        return storeBasePath;
    }
    return path.join(storeBasePath, '1');
}
function underNodeModules(dirpath) {
    return dirpath.split(path.sep).indexOf('node_modules') !== -1;
}
//# sourceMappingURL=getContext.js.map