"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getNxProjectGraphLines = getNxProjectGraphLines;
const devkit_1 = require("@nx/devkit");
const exec_gradle_1 = require("../../utils/exec-gradle");
async function getNxProjectGraphLines(gradlewFile, gradleConfigHash, gradlePluginOptions) {
    let nxProjectGraphBuffer;
    const gradlePluginOptionsArgs = Object.entries(gradlePluginOptions ?? {})?.map(([key, value]) => `-P${key}=${value}`) ?? [];
    try {
        nxProjectGraphBuffer = await (0, exec_gradle_1.execGradleAsync)(gradlewFile, [
            'nxProjectGraph',
            `-Phash=${gradleConfigHash}`,
            '--no-configuration-cache', // disable configuration cache
            '--parallel', // add parallel to improve performance
            '--build-cache', // enable build cache
            '--warning-mode',
            'none',
            ...gradlePluginOptionsArgs,
            `-PworkspaceRoot=${devkit_1.workspaceRoot}`,
            process.env.NX_GRADLE_VERBOSE_LOGGING ? '--info' : '',
        ]);
    }
    catch (e) {
        if (e.toString()?.includes('ERROR: JAVA_HOME')) {
            throw new devkit_1.AggregateCreateNodesError([
                [
                    gradlewFile,
                    new Error(`Could not find Java. Please install Java and try again: https://www.java.com/en/download/help/index_installing.html.\n\r${e.toString()}`),
                ],
            ], []);
        }
        else if (e.toString()?.includes(`Task 'nxProjectGraph' not found`)) {
            throw new devkit_1.AggregateCreateNodesError([
                [
                    gradlewFile,
                    new Error(`Could not run 'nxProjectGraph' task. Please run 'nx generate @nx/gradle:init' to add the necessary plugin dev.nx.gradle.project-graph.\n\r${e.toString()}`),
                ],
            ], []);
        }
        else {
            throw new devkit_1.AggregateCreateNodesError([
                [
                    gradlewFile,
                    new Error(`Could not run 'nxProjectGraph' Gradle task. Please install Gradle and try again: https://gradle.org/install/.\r\n${e.toString()}`),
                ],
            ], []);
        }
    }
    const projectGraphLines = nxProjectGraphBuffer
        .toString()
        .split(exec_gradle_1.newLineSeparator)
        .filter((line) => line.trim() !== '');
    if (process.env.NX_VERBOSE_LOGGING === 'true') {
        devkit_1.output.log({
            title: `Successfully ran 'nxProjectGraph' task using ${gradlewFile} with hash ${gradleConfigHash}`,
            bodyLines: projectGraphLines,
        });
    }
    return projectGraphLines;
}
