"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ciWorkflowGenerator = ciWorkflowGenerator;
const devkit_1 = require("@nx/devkit");
const path_1 = require("path");
const nx_cloud_utils_1 = require("nx/src/utils/nx-cloud-utils");
const default_base_1 = require("nx/src/utils/default-base");
function getCiCommands(ci) {
    switch (ci) {
        case 'circleci': {
            return [
                {
                    comments: [
                        `# Nx Affected runs only tasks affected by the changes in this PR/commit. Learn more: https://nx.dev/ci/features/affected.`,
                    ],
                },
                {
                    command: `./nx affected --base=$NX_BASE --head=$NX_HEAD -t verify-ci`,
                },
                getNxCloudFixCiCommand(),
            ];
        }
        default: {
            return [
                {
                    comments: [
                        `Nx Affected runs only tasks affected by the changes in this PR/commit. Learn more: https://nx.dev/ci/features/affected.`,
                    ],
                    command: `./nx affected -t verify-ci`,
                },
                getNxCloudFixCiCommand(),
            ];
        }
    }
}
function getNxCloudFixCiCommand() {
    return {
        comments: [
            `Nx Cloud recommends fixes for failures to help you get CI green faster. Learn more: https://nx.dev/ci/features/self-healing-ci`,
        ],
        command: `./nx fix-ci`,
        alwaysRun: true,
    };
}
async function ciWorkflowGenerator(tree, schema) {
    const ci = schema.ci;
    const options = getTemplateData(tree, schema);
    (0, devkit_1.generateFiles)(tree, (0, path_1.join)(__dirname, 'files', ci), '', options);
    await (0, devkit_1.formatFiles)(tree);
}
function getTemplateData(tree, options) {
    const { name: workflowName, fileName: workflowFileName } = (0, devkit_1.names)(options.name);
    let nxCloudHost = 'nx.app';
    try {
        const nxCloudUrl = (0, nx_cloud_utils_1.getNxCloudUrl)((0, devkit_1.readNxJson)(tree));
        nxCloudHost = new URL(nxCloudUrl).host;
    }
    catch { }
    const mainBranch = (0, default_base_1.deduceDefaultBase)();
    const commands = options.commands ?? getCiCommands(options.ci);
    const connectedToCloud = (0, nx_cloud_utils_1.isNxCloudUsed)((0, devkit_1.readNxJson)(tree));
    return {
        workflowName,
        workflowFileName,
        commands,
        mainBranch,
        nxCloudHost,
        connectedToCloud,
    };
}
exports.default = ciWorkflowGenerator;
