"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const constants_1 = require("@pnpm/constants");
const types_1 = require("@pnpm/types");
const path = require("path");
const read_yaml_file_1 = require("read-yaml-file");
const errors_1 = require("./errors");
const logger_1 = require("./logger");
async function readCurrentLockfile(virtualStoreDir, opts) {
    const lockfilePath = path.join(virtualStoreDir, 'lock.yaml');
    return _read(lockfilePath, virtualStoreDir, opts);
}
exports.readCurrentLockfile = readCurrentLockfile;
async function readWantedLockfile(pkgPath, opts) {
    const lockfilePath = path.join(pkgPath, constants_1.WANTED_LOCKFILE);
    return _read(lockfilePath, pkgPath, opts);
}
exports.readWantedLockfile = readWantedLockfile;
async function _read(lockfilePath, prefix, opts) {
    let lockfile;
    try {
        lockfile = await read_yaml_file_1.default(lockfilePath);
    }
    catch (err) {
        if (err.code !== 'ENOENT') {
            throw err;
        }
        return null;
    }
    // tslint:disable:no-string-literal
    if (typeof (lockfile === null || lockfile === void 0 ? void 0 : lockfile['specifiers']) !== 'undefined') {
        lockfile.importers = {
            '.': {
                specifiers: lockfile['specifiers'],
            },
        };
        delete lockfile['specifiers'];
        for (const depType of types_1.DEPENDENCIES_FIELDS) {
            if (lockfile[depType]) {
                lockfile.importers['.'][depType] = lockfile[depType];
                delete lockfile[depType];
            }
        }
    }
    if (lockfile) {
        // tslint:enable:no-string-literal
        if (typeof opts.wantedVersion !== 'number' || Math.floor(lockfile.lockfileVersion) === Math.floor(opts.wantedVersion)) {
            if (typeof opts.wantedVersion === 'number' && lockfile.lockfileVersion > opts.wantedVersion) {
                logger_1.default.warn({
                    message: `Your ${constants_1.WANTED_LOCKFILE} was generated by a newer version of pnpm. ` +
                        `It is a compatible version but it might get downgraded to version ${opts.wantedVersion}`,
                    prefix,
                });
            }
            return lockfile;
        }
    }
    if (opts.ignoreIncompatible) {
        logger_1.default.warn({
            message: `Ignoring not compatible lockfile at ${lockfilePath}`,
            prefix,
        });
        return null;
    }
    throw new errors_1.LockfileBreakingChangeError(lockfilePath);
}
function createLockfileObject(importerIds, opts) {
    const importers = importerIds.reduce((acc, importerId) => {
        acc[importerId] = {
            dependencies: {},
            specifiers: {},
        };
        return acc;
    }, {});
    return {
        importers,
        lockfileVersion: opts.lockfileVersion || constants_1.LOCKFILE_VERSION,
    };
}
exports.createLockfileObject = createLockfileObject;
