"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyAppliedPatches = exports.clearPatchApplicationState = exports.savePatchApplicationState = exports.getPatchApplicationState = exports.STATE_FILE_NAME = void 0;
const fs_1 = require("fs");
const path_1 = require("path");
const json_stable_stringify_1 = __importDefault(require("json-stable-stringify"));
const hash_1 = require("./hash");
const chalk_1 = __importDefault(require("chalk"));
const version = 1;
exports.STATE_FILE_NAME = ".patch-package.json";
function getPatchApplicationState(packageDetails) {
    const fileName = path_1.join(packageDetails.path, exports.STATE_FILE_NAME);
    let state = null;
    try {
        state = JSON.parse(fs_1.readFileSync(fileName, "utf8"));
    }
    catch (e) {
        // noop
    }
    if (!state) {
        return null;
    }
    if (state.version !== version) {
        console.log(`You upgraded patch-package and need to fully reinstall node_modules to continue.`);
        process.exit(1);
    }
    return state;
}
exports.getPatchApplicationState = getPatchApplicationState;
function savePatchApplicationState({ packageDetails, patches, isRebasing, }) {
    const fileName = path_1.join(packageDetails.path, exports.STATE_FILE_NAME);
    const state = {
        patches,
        version,
        isRebasing,
    };
    fs_1.writeFileSync(fileName, json_stable_stringify_1.default(state, { space: 4 }), "utf8");
}
exports.savePatchApplicationState = savePatchApplicationState;
function clearPatchApplicationState(packageDetails) {
    const fileName = path_1.join(packageDetails.path, exports.STATE_FILE_NAME);
    try {
        fs_1.unlinkSync(fileName);
    }
    catch (e) {
        // noop
    }
}
exports.clearPatchApplicationState = clearPatchApplicationState;
function verifyAppliedPatches({ appPath, patchDir, state, }) {
    const patchesDirectory = path_1.join(appPath, patchDir);
    for (const patch of state.patches) {
        if (!patch.didApply) {
            break;
        }
        const fullPatchPath = path_1.join(patchesDirectory, patch.patchFilename);
        if (!fs_1.existsSync(fullPatchPath)) {
            console.log(chalk_1.default.blueBright("Expected patch file"), fullPatchPath, "to exist but it is missing. Try removing and reinstalling node_modules first.");
            process.exit(1);
        }
        if (patch.patchContentHash !== hash_1.hashFile(fullPatchPath)) {
            console.log(chalk_1.default.blueBright("Patch file"), fullPatchPath, "has changed since it was applied. Try removing and reinstalling node_modules first.");
            process.exit(1);
        }
    }
}
exports.verifyAppliedPatches = verifyAppliedPatches;
//# sourceMappingURL=data:application/json;base64,[encoded data, 6192 characters]