"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const types_1 = require("@pnpm/types");
const path = require("path");
const read_yaml_file_1 = require("read-yaml-file");
const constants_1 = require("./constants");
const errors_1 = require("./errors");
const logger_1 = require("./logger");
exports.readPrivate = readCurrent;
async function readCurrent(pkgPath, opts) {
    const shrinkwrapPath = path.join(pkgPath, constants_1.CURRENT_SHRINKWRAP_FILENAME);
    return _read(shrinkwrapPath, pkgPath, opts);
}
exports.readCurrent = readCurrent;
exports.read = readWanted;
async function readWanted(pkgPath, opts) {
    const shrinkwrapPath = path.join(pkgPath, constants_1.WANTED_SHRINKWRAP_FILENAME);
    return _read(shrinkwrapPath, pkgPath, opts);
}
exports.readWanted = readWanted;
async function _read(shrinkwrapPath, prefix, opts) {
    let shrinkwrap;
    try {
        shrinkwrap = await read_yaml_file_1.default(shrinkwrapPath);
    }
    catch (err) {
        if (err.code !== 'ENOENT') {
            throw err;
        }
        return null;
    }
    // tslint:disable:no-string-literal
    if (shrinkwrap && typeof shrinkwrap['specifiers'] !== 'undefined') {
        shrinkwrap.importers = {
            '.': {
                specifiers: shrinkwrap['specifiers'],
            },
        };
        delete shrinkwrap['specifiers'];
        for (const depType of types_1.DEPENDENCIES_FIELDS) {
            if (shrinkwrap[depType]) {
                shrinkwrap.importers['.'][depType] = shrinkwrap[depType];
                delete shrinkwrap[depType];
            }
        }
    }
    if (shrinkwrap) {
        // tslint:enable:no-string-literal
        if (typeof opts.wantedVersion !== 'number' || Math.floor(shrinkwrap.shrinkwrapVersion) === Math.floor(opts.wantedVersion)) {
            if (typeof opts.wantedVersion === 'number' && shrinkwrap.shrinkwrapVersion > opts.wantedVersion) {
                logger_1.default.warn({
                    message: 'Your shrinkwrap.yaml was generated by a newer version of pnpm. ' +
                        `It is a compatible version but it might get downgraded to version ${opts.wantedVersion}`,
                    prefix,
                });
            }
            return shrinkwrap;
        }
    }
    if (opts.ignoreIncompatible) {
        logger_1.default.warn({
            message: `Ignoring not compatible shrinkwrap file at ${shrinkwrapPath}`,
            prefix,
        });
        return null;
    }
    throw new errors_1.ShrinkwrapBreakingChangeError(shrinkwrapPath);
}
function create(importerIds, opts) {
    const importers = importerIds.reduce((acc, importerId) => {
        acc[importerId] = {
            dependencies: {},
            specifiers: {},
        };
        return acc;
    }, {});
    return {
        importers,
        shrinkwrapVersion: opts.shrinkwrapVersion || constants_1.SHRINKWRAP_VERSION,
    };
}
exports.create = create;
//# sourceMappingURL=read.js.map