"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createLockfileObject = exports.readWantedLockfile = exports.readWantedLockfileAndAutofixConflicts = exports.readCurrentLockfile = void 0;
const constants_1 = require("@pnpm/constants");
const types_1 = require("@pnpm/types");
const errors_1 = require("./errors");
const gitMergeFile_1 = require("./gitMergeFile");
const logger_1 = __importDefault(require("./logger"));
const yaml = require("js-yaml");
const path = require("path");
const stripBom = require("strip-bom");
const fs = require("mz/fs");
async function readCurrentLockfile(virtualStoreDir, opts) {
    const lockfilePath = path.join(virtualStoreDir, 'lock.yaml');
    return (await _read(lockfilePath, virtualStoreDir, opts)).lockfile;
}
exports.readCurrentLockfile = readCurrentLockfile;
function readWantedLockfileAndAutofixConflicts(pkgPath, opts) {
    const lockfilePath = path.join(pkgPath, constants_1.WANTED_LOCKFILE);
    return _read(lockfilePath, pkgPath, { ...opts, autofixMergeConflicts: true });
}
exports.readWantedLockfileAndAutofixConflicts = readWantedLockfileAndAutofixConflicts;
async function readWantedLockfile(pkgPath, opts) {
    const lockfilePath = path.join(pkgPath, constants_1.WANTED_LOCKFILE);
    return (await _read(lockfilePath, pkgPath, opts)).lockfile;
}
exports.readWantedLockfile = readWantedLockfile;
async function _read(lockfilePath, prefix, opts) {
    let lockfileRawContent;
    try {
        lockfileRawContent = stripBom(await fs.readFile(lockfilePath, 'utf8'));
    }
    catch (err) {
        if (err.code !== 'ENOENT') {
            throw err;
        }
        return {
            lockfile: null,
            hadConflicts: false,
        };
    }
    let lockfile;
    let hadConflicts;
    try {
        lockfile = yaml.safeLoad(lockfileRawContent);
        hadConflicts = false;
    }
    catch (err) {
        if (!opts.autofixMergeConflicts || !gitMergeFile_1.isDiff(lockfileRawContent)) {
            throw err;
        }
        hadConflicts = true;
        lockfile = gitMergeFile_1.autofixMergeConflicts(lockfileRawContent);
        logger_1.default.info({
            message: `Merge conflict detected in ${constants_1.WANTED_LOCKFILE} and successfully merged`,
            prefix: path.dirname(lockfilePath),
        });
    }
    /* eslint-disable @typescript-eslint/dot-notation */
    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) {
        /* eslint-enable @typescript-eslint/dot-notation */
        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, hadConflicts };
        }
    }
    if (opts.ignoreIncompatible) {
        logger_1.default.warn({
            message: `Ignoring not compatible lockfile at ${lockfilePath}`,
            prefix,
        });
        return { lockfile: null, hadConflicts: false };
    }
    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;
//# sourceMappingURL=read.js.map