"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.InitAction = void 0;
const path = __importStar(require("node:path"));
const node_core_library_1 = require("@rushstack/node-core-library");
const terminal_1 = require("@rushstack/terminal");
const BaseRushAction_1 = require("./BaseRushAction");
const PathConstants_1 = require("../../utilities/PathConstants");
const templateUtilities_1 = require("../../utilities/templateUtilities");
class InitAction extends BaseRushAction_1.BaseConfiglessRushAction {
    constructor(parser) {
        super({
            actionName: 'init',
            summary: 'Initializes a new repository to be managed by Rush',
            documentation: 'When invoked in an empty folder, this command provisions a standard' +
                ' set of config file templates to start managing projects using Rush.',
            parser
        });
        // template section name --> whether it should be commented out
        this._commentedBySectionName = new Map();
        this._overwriteParameter = this.defineFlagParameter({
            parameterLongName: '--overwrite-existing',
            description: 'By default "rush init" will not overwrite existing config files.' +
                ' Specify this switch to override that. This can be useful when upgrading' +
                ' your repo to a newer release of Rush. WARNING: USE WITH CARE!'
        });
        this._rushExampleParameter = this.defineFlagParameter({
            parameterLongName: '--rush-example-repo',
            description: 'When copying the template config files, this uncomments fragments that are used' +
                ' by the "rush-example" GitHub repo, which is a sample monorepo that illustrates many Rush' +
                ' features. This option is primarily intended for maintaining that example.'
        });
        this._experimentsParameter = this.defineFlagParameter({
            parameterLongName: '--include-experiments',
            description: 'Include features that may not be complete features, useful for demoing specific future features' +
                ' or current work in progress features.'
        });
    }
    async runAsync() {
        const initFolder = process.cwd();
        if (!this._overwriteParameter.value) {
            if (!this._validateFolderIsEmpty(initFolder)) {
                throw new node_core_library_1.AlreadyReportedError();
            }
        }
        await this._copyTemplateFilesAsync(initFolder);
    }
    // Check whether it's safe to run "rush init" in the current working directory.
    _validateFolderIsEmpty(initFolder) {
        if (this.rushConfiguration !== undefined) {
            // eslint-disable-next-line no-console
            console.error(terminal_1.Colorize.red('ERROR: Found an existing configuration in: ' + this.rushConfiguration.rushJsonFile));
            // eslint-disable-next-line no-console
            console.log('\nThe "rush init" command must be run in a new folder without an existing Rush configuration.');
            return false;
        }
        for (const itemName of node_core_library_1.FileSystem.readFolderItemNames(initFolder)) {
            if (itemName.substr(0, 1) === '.') {
                // Ignore any items that start with ".", for example ".git"
                continue;
            }
            const itemPath = path.join(initFolder, itemName);
            const stats = node_core_library_1.FileSystem.getStatistics(itemPath);
            // Ignore any loose files in the current folder, e.g. "README.md"
            // or "CONTRIBUTING.md"
            if (stats.isDirectory()) {
                // eslint-disable-next-line no-console
                console.error(terminal_1.Colorize.red(`ERROR: Found a subdirectory: "${itemName}"`));
                // eslint-disable-next-line no-console
                console.log('\nThe "rush init" command must be run in a new folder with no projects added yet.');
                return false;
            }
            else {
                if (itemName.toLowerCase() === 'package.json') {
                    // eslint-disable-next-line no-console
                    console.error(terminal_1.Colorize.red(`ERROR: Found a package.json file in this folder`));
                    // eslint-disable-next-line no-console
                    console.log('\nThe "rush init" command must be run in a new folder with no projects added yet.');
                    return false;
                }
            }
        }
        return true;
    }
    async _copyTemplateFilesAsync(initFolder) {
        // The "[dot]" base name is used for hidden files to prevent various tools from interpreting them.
        // For example, "npm publish" will always exclude the filename ".gitignore"
        const templateFilePaths = [
            '[dot]github/workflows/ci.yml',
            'common/config/rush/.pnpmfile.cjs',
            'common/config/rush/[dot]npmrc',
            'common/config/rush/[dot]npmrc-publish',
            'common/config/rush/artifactory.json',
            'common/config/rush/build-cache.json',
            'common/config/rush/cobuild.json',
            'common/config/rush/command-line.json',
            'common/config/rush/common-versions.json',
            'common/config/rush/custom-tips.json',
            'common/config/rush/experiments.json',
            'common/config/rush/pnpm-config.json',
            'common/config/rush/rush-plugins.json',
            'common/config/rush/subspaces.json',
            'common/config/rush/version-policies.json',
            'common/git-hooks/commit-msg.sample',
            '[dot]gitattributes',
            '[dot]gitignore',
            'rush.json'
        ];
        const experimentalTemplateFilePaths = ['common/config/rush/rush-alerts.json'];
        if (this._experimentsParameter.value) {
            templateFilePaths.push(...experimentalTemplateFilePaths);
        }
        const assetsSubfolder = `${PathConstants_1.assetsFolderPath}/rush-init`;
        for (const templateFilePath of templateFilePaths) {
            const sourcePath = path.join(assetsSubfolder, templateFilePath);
            if (!node_core_library_1.FileSystem.exists(sourcePath)) {
                // If this happens, please report a Rush bug
                throw new node_core_library_1.InternalError('Unable to find template input file: ' + sourcePath);
            }
            const destinationPath = path.join(initFolder, templateFilePath).replace('[dot]', '.');
            // The "DEMO" sections are uncommented only when "--rush-example-repo" is specified.
            await (0, templateUtilities_1.copyTemplateFileAsync)(sourcePath, destinationPath, this._overwriteParameter.value, !this._rushExampleParameter.value);
        }
    }
}
exports.InitAction = InitAction;
//# sourceMappingURL=InitAction.js.map