// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import { Async, FileSystem, JsonFile } from '@rushstack/node-core-library';
import { ConsoleTerminalProvider, Terminal } from '@rushstack/terminal';
import { assetsFolderPath } from '../../utilities/PathConstants';
import { BaseRushAction } from './BaseRushAction';
import { SubspacesConfiguration } from '../../api/SubspacesConfiguration';
import { copyTemplateFileAsync } from '../../utilities/templateUtilities';
export class InitSubspaceAction extends BaseRushAction {
    constructor(parser) {
        super({
            actionName: 'init-subspace',
            summary: 'Create a new subspace.',
            documentation: 'Use this command to create a new subspace with the default subspace configuration files.',
            parser
        });
        this._subspaceNameParameter = this.defineStringParameter({
            parameterLongName: '--name',
            parameterShortName: '-n',
            argumentName: 'SUBSPACE_NAME',
            description: 'The name of the subspace that is being initialized.',
            required: true
        });
    }
    async runAsync() {
        var _a;
        const terminal = new Terminal(new ConsoleTerminalProvider());
        if (!this.rushConfiguration.subspacesFeatureEnabled) {
            throw new Error('Unable to create a subspace because the subspaces feature is not enabled.');
        }
        const subspacesConfiguration = this.rushConfiguration
            .subspacesConfiguration;
        // Verify this subspace name does not already exist
        const existingSubspaceNames = subspacesConfiguration.subspaceNames;
        const newSubspaceName = this._subspaceNameParameter.value;
        if (existingSubspaceNames.has(newSubspaceName)) {
            throw new Error(`The subspace name: ${this._subspaceNameParameter.value} already exists in the subspace.json file.`);
        }
        if (SubspacesConfiguration.explainIfInvalidSubspaceName(newSubspaceName, (_a = this.rushConfiguration.subspacesConfiguration) === null || _a === void 0 ? void 0 : _a.splitWorkspaceCompatibility)) {
            return;
        }
        const subspaceConfigPath = `${this.rushConfiguration.commonFolder}/config/subspaces/${newSubspaceName}`;
        const assetsSubfolder = `${assetsFolderPath}/rush-init`;
        const templateFilePaths = [
            '[dot]npmrc',
            '.pnpmfile.cjs',
            'common-versions.json',
            'pnpm-config.json'
        ];
        await FileSystem.ensureEmptyFolderAsync(subspaceConfigPath);
        await Async.forEachAsync(templateFilePaths, async (templateFilePath) => {
            const sourcePath = `${assetsSubfolder}/common/config/rush/${templateFilePath}`;
            const destinationPath = `${subspaceConfigPath}/${templateFilePath.replace('[dot]', '.')}`;
            await copyTemplateFileAsync(sourcePath, destinationPath, true);
        }, { concurrency: 10 });
        // Add the subspace name to subspaces.json
        const subspaceJson = await JsonFile.loadAsync(subspacesConfiguration.subspaceJsonFilePath);
        subspaceJson.subspaceNames.push(newSubspaceName);
        await JsonFile.saveAsync(subspaceJson, subspacesConfiguration.subspaceJsonFilePath, {
            updateExistingFile: true
        });
        terminal.writeLine('\nSubspace successfully created. Please review the subspace configuration files before committing.');
    }
}
//# sourceMappingURL=InitSubspaceAction.js.map