"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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ChangeFiles = void 0;
const node_core_library_1 = require("@rushstack/node-core-library");
const change_file_schema_json_1 = __importDefault(require("../schemas/change-file.schema.json"));
/**
 * This class represents the collection of change files existing in the repo and provides operations
 * for those change files.
 */
class ChangeFiles {
    constructor(changesPath) {
        this._changesPath = changesPath;
    }
    /**
     * Validate if the newly added change files match the changed packages.
     */
    static validate(newChangeFilePaths, changedPackages, rushConfiguration) {
        const schema = node_core_library_1.JsonSchema.fromLoadedObject(change_file_schema_json_1.default);
        const projectsWithChangeDescriptions = new Set();
        newChangeFilePaths.forEach((filePath) => {
            // eslint-disable-next-line no-console
            console.log(`Found change file: ${filePath}`);
            const changeFile = node_core_library_1.JsonFile.loadAndValidate(filePath, schema);
            if (rushConfiguration.hotfixChangeEnabled) {
                if (changeFile && changeFile.changes) {
                    for (const change of changeFile.changes) {
                        if (change.type !== 'none' && change.type !== 'hotfix') {
                            throw new Error(`Change file ${filePath} specifies a type of '${change.type}' ` +
                                `but only 'hotfix' and 'none' change types may be used in a branch with 'hotfixChangeEnabled'.`);
                        }
                    }
                }
            }
            if (changeFile && changeFile.changes) {
                changeFile.changes.forEach((change) => projectsWithChangeDescriptions.add(change.packageName));
            }
            else {
                throw new Error(`Invalid change file: ${filePath}`);
            }
        });
        const projectsMissingChangeDescriptions = new Set(changedPackages);
        projectsWithChangeDescriptions.forEach((name) => projectsMissingChangeDescriptions.delete(name));
        if (projectsMissingChangeDescriptions.size > 0) {
            const projectsMissingChangeDescriptionsArray = [];
            projectsMissingChangeDescriptions.forEach((name) => projectsMissingChangeDescriptionsArray.push(name));
            throw new Error([
                'The following projects have been changed and require change descriptions, but change descriptions were not ' +
                    'detected for them:',
                ...projectsMissingChangeDescriptionsArray.map((projectName) => `- ${projectName}`),
                'To resolve this error, run "rush change". This will generate change description files that must be ' +
                    'committed to source control.'
            ].join('\n'));
        }
    }
    static getChangeComments(newChangeFilePaths) {
        const changes = new Map();
        newChangeFilePaths.forEach((filePath) => {
            // eslint-disable-next-line no-console
            console.log(`Found change file: ${filePath}`);
            const changeRequest = node_core_library_1.JsonFile.load(filePath);
            if (changeRequest && changeRequest.changes) {
                changeRequest.changes.forEach((change) => {
                    if (!changes.get(change.packageName)) {
                        changes.set(change.packageName, []);
                    }
                    if (change.comment && change.comment.length) {
                        changes.get(change.packageName).push(change.comment);
                    }
                });
            }
            else {
                throw new Error(`Invalid change file: ${filePath}`);
            }
        });
        return changes;
    }
    /**
     * Get the array of absolute paths of change files.
     */
    async getFilesAsync() {
        if (!this._files) {
            const { default: glob } = await Promise.resolve().then(() => __importStar(require('fast-glob')));
            this._files = (await glob('**/*.json', { cwd: this._changesPath, absolute: true })) || [];
        }
        return this._files;
    }
    /**
     * Get the path of changes folder.
     */
    getChangesPath() {
        return this._changesPath;
    }
    /**
     * Delete all change files
     */
    async deleteAllAsync(shouldDelete, updatedChangelogs) {
        if (updatedChangelogs) {
            // Skip changes files if the package's change log is not updated.
            const packagesToInclude = new Set();
            updatedChangelogs.forEach((changelog) => {
                packagesToInclude.add(changelog.name);
            });
            const files = await this.getFilesAsync();
            const filesToDelete = [];
            await node_core_library_1.Async.forEachAsync(files, async (filePath) => {
                const changeRequest = await node_core_library_1.JsonFile.loadAsync(filePath);
                let shouldDeleteFile = true;
                for (const changeInfo of changeRequest.changes) {
                    if (!packagesToInclude.has(changeInfo.packageName)) {
                        shouldDeleteFile = false;
                        break;
                    }
                }
                if (shouldDeleteFile) {
                    filesToDelete.push(filePath);
                }
            }, { concurrency: 5 });
            return await this._deleteFilesAsync(filesToDelete, shouldDelete);
        }
        else {
            // Delete all change files.
            const files = await this.getFilesAsync();
            return await this._deleteFilesAsync(files, shouldDelete);
        }
    }
    async _deleteFilesAsync(files, shouldDelete) {
        if (files.length) {
            // eslint-disable-next-line no-console
            console.log(`\n* ${shouldDelete ? 'DELETING:' : 'DRYRUN: Deleting'} ${files.length} change file(s).`);
            await node_core_library_1.Async.forEachAsync(files, async (filePath) => {
                // eslint-disable-next-line no-console
                console.log(` - ${filePath}`);
                if (shouldDelete) {
                    await node_core_library_1.FileSystem.deleteFileAsync(filePath);
                }
            }, { concurrency: 5 });
        }
        return files.length;
    }
}
exports.ChangeFiles = ChangeFiles;
//# sourceMappingURL=ChangeFiles.js.map