"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.AutoinstallerPluginLoader = void 0;
const path = __importStar(require("node:path"));
const node_core_library_1 = require("@rushstack/node-core-library");
const Autoinstaller_1 = require("../../logic/Autoinstaller");
const RushConstants_1 = require("../../logic/RushConstants");
const PluginLoaderBase_1 = require("./PluginLoaderBase");
/**
 * @beta
 */
class AutoinstallerPluginLoader extends PluginLoaderBase_1.PluginLoaderBase {
    constructor(options) {
        super(options);
        this.autoinstaller = new Autoinstaller_1.Autoinstaller({
            autoinstallerName: options.pluginConfiguration.autoinstallerName,
            rushConfiguration: this._rushConfiguration,
            restrictConsoleOutput: options.restrictConsoleOutput,
            rushGlobalFolder: options.rushGlobalFolder
        });
        this.packageFolder = path.join(this.autoinstaller.folderFullPath, 'node_modules', this.packageName);
    }
    /**
     * The folder where rush plugins static files are stored.
     * Example: `C:\MyRepo\common\autoinstallers\<autoinstaller_name>\rush-plugins`
     */
    static getPluginAutoinstallerStorePath(autoinstaller) {
        return path.join(autoinstaller.folderFullPath, 'rush-plugins');
    }
    update() {
        const packageName = this.packageName;
        const pluginName = this.pluginName;
        const packageFolder = this.packageFolder;
        const manifestPath = path.join(packageFolder, RushConstants_1.RushConstants.rushPluginManifestFilename);
        // validate
        const manifest = node_core_library_1.JsonFile.loadAndValidate(manifestPath, AutoinstallerPluginLoader._jsonSchema);
        const destinationManifestPath = this._getManifestPath();
        node_core_library_1.FileSystem.copyFile({
            sourcePath: manifestPath,
            destinationPath: destinationManifestPath
        });
        // Make permission consistent since it will be committed to Git
        node_core_library_1.FileSystem.changePosixModeBits(destinationManifestPath, 
        // eslint-disable-next-line no-bitwise
        node_core_library_1.PosixModeBits.AllRead | node_core_library_1.PosixModeBits.UserWrite);
        const pluginManifest = manifest.plugins.find((item) => item.pluginName === pluginName);
        if (!pluginManifest) {
            throw new Error(`A plugin named "${pluginName}" is not provided by the Rush plugin package "${packageName}"`);
        }
        const commandLineJsonFilePath = pluginManifest.commandLineJsonFilePath;
        if (commandLineJsonFilePath) {
            const commandLineJsonFullFilePath = path.join(packageFolder, commandLineJsonFilePath);
            if (!node_core_library_1.FileSystem.exists(commandLineJsonFullFilePath)) {
                this._terminal.writeErrorLine(`The Rush plugin "${pluginName}" from "${packageName}" specifies a commandLineJsonFilePath` +
                    ` ${commandLineJsonFilePath} that does not exist.`);
            }
            const destinationCommandLineJsonFilePath = this._getCommandLineJsonFilePath();
            node_core_library_1.FileSystem.copyFile({
                sourcePath: commandLineJsonFullFilePath,
                destinationPath: destinationCommandLineJsonFilePath
            });
            // Make permission consistent since it will be committed to Git
            node_core_library_1.FileSystem.changePosixModeBits(destinationCommandLineJsonFilePath, 
            // eslint-disable-next-line no-bitwise
            node_core_library_1.PosixModeBits.AllRead | node_core_library_1.PosixModeBits.UserWrite);
        }
    }
    _getCommandLineAdditionalPathFolders() {
        const additionalPathFolders = super._getCommandLineAdditionalPathFolders();
        additionalPathFolders.push(
        // Example: `common/autoinstaller/plugins/node_modules/.bin`
        path.join(this.autoinstaller.folderFullPath, 'node_modules', '.bin'));
        return additionalPathFolders;
    }
    _getPluginOptions() {
        const optionsJsonFilePath = this._getPluginOptionsJsonFilePath();
        const optionsSchema = this._getRushPluginOptionsSchema();
        let pluginOptions = {};
        try {
            pluginOptions = node_core_library_1.JsonFile.load(optionsJsonFilePath);
        }
        catch (e) {
            if (node_core_library_1.FileSystem.isFileDoesNotExistError(e)) {
                if (optionsSchema) {
                    throw new Error(`Plugin options are required by ${this.pluginName} from package ${this.packageName}, please create it at ${optionsJsonFilePath}.`);
                }
                else {
                    return {};
                }
            }
            throw e;
        }
        if (optionsSchema) {
            optionsSchema.validateObject(pluginOptions, optionsJsonFilePath);
        }
        return pluginOptions;
    }
    _getManifestPath() {
        return path.join(AutoinstallerPluginLoader.getPluginAutoinstallerStorePath(this.autoinstaller), this.packageName, RushConstants_1.RushConstants.rushPluginManifestFilename);
    }
    _getCommandLineJsonFilePath() {
        return path.join(AutoinstallerPluginLoader.getPluginAutoinstallerStorePath(this.autoinstaller), this.packageName, this.pluginName, RushConstants_1.RushConstants.commandLineFilename);
    }
}
exports.AutoinstallerPluginLoader = AutoinstallerPluginLoader;
//# sourceMappingURL=AutoinstallerPluginLoader.js.map