// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import { pnpmSyncGetJsonVersion } from 'pnpm-sync-lib';
import { JsonFile, Path, Objects } from '@rushstack/node-core-library';
import * as objectUtilities from '../utilities/objectUtilities';
import { Selection } from '../logic/Selection';
import { FlagFile } from './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.
 */
export class LastInstallFlag extends 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 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 (!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
                            ? Path.convertToPlatformDefault(oldState.storePath)
                            : '<global>';
                        const normalizedNewStorePath = newState.storePath
                            ? 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.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);
    }
}
/**
 * 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
 */
export function getCommonTempFlag(rushConfiguration, subspace, extraState = {}) {
    const currentState = {
        node: process.versions.node,
        packageManager: rushConfiguration.packageManager,
        packageManagerVersion: rushConfiguration.packageManagerToolVersion,
        rushJsonFolder: rushConfiguration.rushJsonFolder,
        ignoreScripts: false,
        pnpmSync: 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