"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
exports.OperationResultSummarizerPlugin = void 0;
exports._printOperationStatus = _printOperationStatus;
const node_core_library_1 = require("@rushstack/node-core-library");
const terminal_1 = require("@rushstack/terminal");
const OperationStatus_1 = require("./OperationStatus");
const PLUGIN_NAME = 'OperationResultSummarizerPlugin';
/**
 * Format "======" lines for a shell window with classic 80 columns
 */
const ASCII_HEADER_WIDTH = 79;
/**
 * Phased command plugin that emits a summary of build results to the console.
 */
class OperationResultSummarizerPlugin {
    constructor(terminal) {
        this._terminal = terminal;
    }
    apply(hooks) {
        hooks.afterExecuteOperations.tap(PLUGIN_NAME, (result, context) => {
            _printOperationStatus(this._terminal, result);
        });
    }
}
exports.OperationResultSummarizerPlugin = OperationResultSummarizerPlugin;
/**
 * Prints out a report of the status of each project
 * @internal
 */
function _printOperationStatus(terminal, result) {
    const { operationResults } = result;
    const operationsByStatus = new Map();
    for (const record of operationResults) {
        if (record[1].silent) {
            // Don't report silenced operations
            continue;
        }
        const { status } = record[1];
        switch (status) {
            // These are the sections that we will report below
            case OperationStatus_1.OperationStatus.Skipped:
            case OperationStatus_1.OperationStatus.FromCache:
            case OperationStatus_1.OperationStatus.Success:
            case OperationStatus_1.OperationStatus.SuccessWithWarning:
            case OperationStatus_1.OperationStatus.Blocked:
            case OperationStatus_1.OperationStatus.Failure:
            case OperationStatus_1.OperationStatus.NoOp:
            case OperationStatus_1.OperationStatus.Aborted:
                break;
            default:
                // This should never happen
                throw new node_core_library_1.InternalError(`Unexpected operation status: ${status}`);
        }
        const collection = operationsByStatus.get(status);
        if (collection) {
            collection.push(record);
        }
        else {
            operationsByStatus.set(status, [record]);
        }
    }
    // Skip a few lines before we start the summary
    terminal.writeLine('\n\n');
    // These are ordered so that the most interesting statuses appear last:
    writeCondensedSummary(terminal, OperationStatus_1.OperationStatus.Skipped, operationsByStatus, terminal_1.Colorize.green, 'These operations were already up to date:');
    writeCondensedSummary(terminal, OperationStatus_1.OperationStatus.NoOp, operationsByStatus, terminal_1.Colorize.gray, 'These operations did not define any work:');
    writeCondensedSummary(terminal, OperationStatus_1.OperationStatus.FromCache, operationsByStatus, terminal_1.Colorize.green, 'These operations were restored from the build cache:');
    writeCondensedSummary(terminal, OperationStatus_1.OperationStatus.Success, operationsByStatus, terminal_1.Colorize.green, 'These operations completed successfully:');
    writeDetailedSummary(terminal, OperationStatus_1.OperationStatus.SuccessWithWarning, operationsByStatus, terminal_1.Colorize.yellow, 'WARNING');
    writeCondensedSummary(terminal, OperationStatus_1.OperationStatus.Aborted, operationsByStatus, terminal_1.Colorize.white, 'These operations were aborted:');
    writeCondensedSummary(terminal, OperationStatus_1.OperationStatus.Blocked, operationsByStatus, terminal_1.Colorize.white, 'These operations were blocked by dependencies that failed:');
    writeDetailedSummary(terminal, OperationStatus_1.OperationStatus.Failure, operationsByStatus, terminal_1.Colorize.red);
    terminal.writeLine('');
    switch (result.status) {
        case OperationStatus_1.OperationStatus.Failure:
            terminal.writeErrorLine('Operations failed.\n');
            break;
        case OperationStatus_1.OperationStatus.SuccessWithWarning:
            terminal.writeWarningLine('Operations succeeded with warnings.\n');
            break;
    }
}
function writeCondensedSummary(terminal, status, operationsByStatus, headingColor, preamble) {
    var _a, _b, _c;
    // Example:
    //
    // ==[ BLOCKED: 4 projects ]==============================================================
    //
    // These projects were blocked by dependencies that failed:
    //   @scope/name
    //   e
    //   k
    const operations = operationsByStatus.get(status);
    if (!operations || operations.length === 0) {
        return;
    }
    writeSummaryHeader(terminal, status, operations, headingColor);
    terminal.writeLine(preamble);
    let longestTaskName = 0;
    for (const [operation] of operations) {
        const nameLength = operation.name.length;
        if (nameLength > longestTaskName) {
            longestTaskName = nameLength;
        }
    }
    for (const [operation, operationResult] of operations) {
        const { _operationMetadataManager: operationMetadataManager } = operationResult;
        const stopwatch = (_a = operationMetadataManager === null || operationMetadataManager === void 0 ? void 0 : operationMetadataManager.tryRestoreStopwatch(operationResult.stopwatch)) !== null && _a !== void 0 ? _a : operationResult.stopwatch;
        if (stopwatch.duration !== 0 &&
            operation.runner.reportTiming &&
            operationResult.status !== OperationStatus_1.OperationStatus.Skipped) {
            const time = stopwatch.toString();
            const padding = ' '.repeat(longestTaskName - (operation.name || '').length);
            const cacheString = (operationMetadataManager === null || operationMetadataManager === void 0 ? void 0 : operationMetadataManager.wasCobuilt)
                ? ` (restore ${(((_b = operationResult.stopwatch.endTime) !== null && _b !== void 0 ? _b : 0) - ((_c = operationResult.stopwatch.startTime) !== null && _c !== void 0 ? _c : 0)).toFixed(1)}ms)`
                : '';
            terminal.writeLine(`  ${operation.name}${padding}    ${time}${cacheString}`);
        }
        else {
            terminal.writeLine(`  ${operation.name}`);
        }
    }
    terminal.writeLine('');
}
function writeDetailedSummary(terminal, status, operationsByStatus, headingColor, shortStatusName) {
    // Example:
    //
    // ==[ SUCCESS WITH WARNINGS: 2 projects ]================================
    //
    // --[ WARNINGS: f ]------------------------------------[ 5.07 seconds ]--
    //
    // [eslint] Warning: src/logic/operations/OperationsExecutionManager.ts:393:3 ...
    var _a;
    const operations = operationsByStatus.get(status);
    if (!operations || operations.length === 0) {
        return;
    }
    writeSummaryHeader(terminal, status, operations, headingColor);
    if (shortStatusName === undefined) {
        shortStatusName = status;
    }
    for (const [operation, operationResult] of operations) {
        const { _operationMetadataManager: operationMetadataManager } = operationResult;
        // Format a header like this
        //
        // --[ WARNINGS: f ]------------------------------------[ 5.07 seconds ]--
        // leftPart: "--[ WARNINGS: f "
        const subheadingText = `${shortStatusName}: ${operation.name}`;
        const leftPartLength = 4 + subheadingText.length + 1;
        // rightPart: " 5.07 seconds ]--"
        const stopwatch = (_a = operationMetadataManager === null || operationMetadataManager === void 0 ? void 0 : operationMetadataManager.tryRestoreStopwatch(operationResult.stopwatch)) !== null && _a !== void 0 ? _a : operationResult.stopwatch;
        const time = stopwatch.toString();
        const rightPartLength = 1 + time.length + 1 + 3;
        // middlePart: "]----------------------["
        const twoBracketsLength = 2;
        const middlePartLengthMinusTwoBrackets = Math.max(ASCII_HEADER_WIDTH - (leftPartLength + rightPartLength + twoBracketsLength), 0);
        terminal.writeLine(`${terminal_1.Colorize.gray('--[')} ${headingColor(subheadingText)} ${terminal_1.Colorize.gray(`]${'-'.repeat(middlePartLengthMinusTwoBrackets)}[`)} ${terminal_1.Colorize.white(time)} ${terminal_1.Colorize.gray(']--')}\n`);
        const details = operationResult.stdioSummarizer.getReport();
        if (details) {
            // Don't write a newline, because the report will always end with a newline
            terminal.write(details);
        }
        terminal.writeLine('');
    }
}
function writeSummaryHeader(terminal, status, operations, headingColor) {
    // Format a header like this
    //
    // ==[ FAILED: 2 operations ]================================================
    // "2 operations"
    const projectsText = `${operations.length}${operations.length === 1 ? ' operation' : ' operations'}`;
    const headingText = `${status}: ${projectsText}`;
    // leftPart: "==[ FAILED: 2 operations "
    const leftPartLength = 3 + 1 + headingText.length + 1;
    const rightPartLengthMinusBracket = Math.max(ASCII_HEADER_WIDTH - (leftPartLength + 1), 0);
    // rightPart: "]======================"
    terminal.writeLine(`${terminal_1.Colorize.gray('==[')} ${headingColor(headingText)} ${terminal_1.Colorize.gray(`]${'='.repeat(rightPartLengthMinusBracket)}`)}\n`);
}
//# sourceMappingURL=OperationResultSummarizerPlugin.js.map