"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.LastInstallFlag = void 0;
exports.getCommonTempFlag = getCommonTempFlag;
const pnpm_sync_lib_1 = require("pnpm-sync-lib");
const node_core_library_1 = require("@rushstack/node-core-library");
const objectUtilities = __importStar(require("../utilities/objectUtilities"));
const Selection_1 = require("../logic/Selection");
const FlagFile_1 = require("./FlagFile");
const LAST_INSTALL_FLAG_FILE_NAME = 'last-install';
/**
 * A helper class for managing last-install flags, which are persistent and
 * indicate that something installed in the folder was successfully completed.
 * It also compares state, so that if something like the Node.js version has changed,
 * it can invalidate the last install.
 */
class LastInstallFlag extends FlagFile_1.FlagFile {
    /**
     * Creates a new LastInstall flag
     * @param folderPath - the folder that this flag is managing
     * @param state - optional, the state that should be managed or compared
     */
    constructor(folderPath, state) {
        super(folderPath, LAST_INSTALL_FLAG_FILE_NAME, state || {});
    }
    /**
     * Returns true if the file exists and the contents match the current state.
     */
    async isValidAsync() {
        return await this._isValidAsync(false, {});
    }
    /**
     * Same as isValid(), but with an additional check:  If the current state is not equal to the previous
     * state, and an the current state causes an error, then throw an exception with a friendly message.
     *
     * @internal
     */
    async checkValidAndReportStoreIssuesAsync(options) {
        return this._isValidAsync(true, options);
    }
    async _isValidAsync(checkValidAndReportStoreIssues, { rushVerb = 'update', statePropertiesToIgnore } = {}) {
        let oldState;
        try {
            oldState = await node_core_library_1.JsonFile.loadAsync(this.path);
        }
        catch (err) {
            return false;
        }
        const newState = { ...this._state };
        if (statePropertiesToIgnore) {
            for (const optionToIgnore of statePropertiesToIgnore) {
                delete newState[optionToIgnore];
                delete oldState[optionToIgnore];
            }
        }
        if (!node_core_library_1.Objects.areDeepEqual(oldState, newState)) {
            if (checkValidAndReportStoreIssues) {
                const pkgManager = newState.packageManager;
                if (pkgManager === 'pnpm') {
                    if (
                    // Only throw an error if the package manager hasn't changed from PNPM
                    oldState.packageManager === pkgManager) {
                        const normalizedOldStorePath = oldState.storePath
                            ? node_core_library_1.Path.convertToPlatformDefault(oldState.storePath)
                            : '<global>';
                        const normalizedNewStorePath = newState.storePath
                            ? node_core_library_1.Path.convertToPlatformDefault(newState.storePath)
                            : '<global>';
                        if (
                        // Throw if the store path changed
                        normalizedOldStorePath !== normalizedNewStorePath) {
                            throw new Error('Current PNPM store path does not match the last one used. This may cause inconsistency in your builds.\n\n' +
                                `If you wish to install with the new store path, please run "rush ${rushVerb} --purge"\n\n` +
                                `Old Path: ${normalizedOldStorePath}\n` +
                                `New Path: ${normalizedNewStorePath}`);
                        }
                    }
                    // check whether new selected projects are installed
                    if (newState.selectedProjectNames) {
                        if (!oldState.selectedProjectNames) {
                            // used to be a full install
                            return true;
                        }
                        else if (Selection_1.Selection.union(newState.selectedProjectNames, oldState.selectedProjectNames).size ===
                            oldState.selectedProjectNames.length) {
                            // current selected projects are included in old selected projects
                            return true;
                        }
                    }
                }
            }
            return false;
        }
        return true;
    }
    /**
     * Merge new data into current state by "merge"
     */
    mergeFromObject(data) {
        if (objectUtilities.isMatch(this._state, data)) {
            return;
        }
        objectUtilities.merge(this._state, data);
    }
}
exports.LastInstallFlag = LastInstallFlag;
/**
 * Gets the LastInstall flag and sets the current state. This state is used to compare
 * against the last-known-good state tracked by the LastInstall flag.
 * @param rushConfiguration - the configuration of the Rush repo to get the install
 * state from
 *
 * @internal
 */
function getCommonTempFlag(rushConfiguration, subspace, extraState = {}) {
    const currentState = {
        node: process.versions.node,
        packageManager: rushConfiguration.packageManager,
        packageManagerVersion: rushConfiguration.packageManagerToolVersion,
        rushJsonFolder: rushConfiguration.rushJsonFolder,
        ignoreScripts: false,
        pnpmSync: (0, pnpm_sync_lib_1.pnpmSyncGetJsonVersion)(),
        ...extraState
    };
    if (currentState.packageManager === 'pnpm' && rushConfiguration.pnpmOptions) {
        currentState.storePath = rushConfiguration.pnpmOptions.pnpmStorePath;
        if (rushConfiguration.pnpmOptions.useWorkspaces) {
            currentState.workspaces = rushConfiguration.pnpmOptions.useWorkspaces;
        }
    }
    return new LastInstallFlag(subspace.getSubspaceTempFolderPath(), currentState);
}
//# sourceMappingURL=LastInstallFlag.js.map