"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const yaml = require("js-yaml");
const mkdirp = require("mkdirp-promise");
const path = require("path");
const rimraf = require("rimraf-then");
const thenify = require("thenify");
const writeFileAtomicCB = require("write-file-atomic");
const constants_1 = require("./constants");
const logger_1 = require("./logger");
const writeFileAtomic = thenify(writeFileAtomicCB);
const SHRINKWRAP_YAML_FORMAT = {
    lineWidth: 1000,
    noCompatMode: true,
    sortKeys: true,
};
function write(pkgPath, wantedShrinkwrap, currentShrinkwrap) {
    const wantedShrinkwrapPath = path.join(pkgPath, constants_1.WANTED_SHRINKWRAP_FILENAME);
    const currentShrinkwrapPath = path.join(pkgPath, constants_1.CURRENT_SHRINKWRAP_FILENAME);
    // empty shrinkwrap is not saved
    if (Object.keys(wantedShrinkwrap.specifiers).length === 0) {
        return Promise.all([
            rimraf(wantedShrinkwrapPath),
            rimraf(currentShrinkwrapPath),
        ]);
    }
    const yamlDoc = yaml.safeDump(wantedShrinkwrap, SHRINKWRAP_YAML_FORMAT);
    // in most cases the `shrinkwrap.yaml` and `node_modules/.shrinkwrap.yaml` are equal
    // in those cases the YAML document can be stringified only once for both files
    // which is more efficient
    if (wantedShrinkwrap === currentShrinkwrap) {
        return Promise.all([
            writeFileAtomic(wantedShrinkwrapPath, yamlDoc),
            mkdirp(path.dirname(currentShrinkwrapPath)).then(() => writeFileAtomic(currentShrinkwrapPath, yamlDoc)),
        ]);
    }
    logger_1.default.warn('`shrinkwrap.yaml` differs from `node_modules/.shrinkwrap.yaml`. ' +
        'To fix this, run `pnpm install`. From pnpm version 2, named installations and uninstallations will fail ' +
        'when the content of `node_modules` won\'t match what the `shrinkwrap.yaml` expects.');
    const currentYamlDoc = yaml.safeDump(currentShrinkwrap, SHRINKWRAP_YAML_FORMAT);
    return Promise.all([
        writeFileAtomic(wantedShrinkwrapPath, yamlDoc),
        mkdirp(path.dirname(currentShrinkwrapPath)).then(() => writeFileAtomic(currentShrinkwrapPath, currentYamlDoc)),
    ]);
}
exports.default = write;
//# sourceMappingURL=write.js.map