"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = gradleExecutor;
const devkit_1 = require("@nx/devkit");
const exec_gradle_1 = require("../../utils/exec-gradle");
const node_path_1 = require("node:path");
const run_commands_impl_1 = require("nx/src/executors/run-commands/run-commands.impl");
const get_exclude_task_1 = require("./get-exclude-task");
async function gradleExecutor(options, context) {
    let projectRoot = context.projectGraph.nodes[context.projectName]?.data?.root ?? context.root;
    const customGradleExecutableDirectory = (0, exec_gradle_1.getCustomGradleExecutableDirectoryFromPlugin)(context.nxJsonConfiguration);
    let gradlewPath = (0, exec_gradle_1.findGradlewFile)((0, node_path_1.join)(projectRoot, 'project.json'), devkit_1.workspaceRoot, customGradleExecutableDirectory); // find gradlew near project root
    gradlewPath = (0, node_path_1.join)(context.root, gradlewPath);
    if (options.taskName && options.taskName?.includes(' ')) {
        throw new Error(`Task "${options.taskName}" contains spaces. Only a single Gradle task is allowed per executor invocation.`);
    }
    let args = typeof options.args === 'string'
        ? options.args.trim().split(' ')
        : Array.isArray(options.args)
            ? options.args
            : [];
    if (options.testClassName) {
        args.push(`--tests`, options.testClassName);
    }
    // Pass any additional options not defined in the schema as gradle arguments
    const knownOptions = new Set([
        'taskName',
        'testClassName',
        'args',
        'excludeDependsOn',
        'includeDependsOnTasks',
        '__unparsed__',
    ]);
    Object.entries(options).forEach(([key, value]) => {
        if (!knownOptions.has(key) && value !== undefined && value !== false) {
            if (value === true) {
                // Boolean flags like --continuous
                args.push(`--${key}`);
            }
            else {
                // Flags with values like --max-workers=4
                args.push(`--${key}=${value}`);
            }
        }
    });
    if (options.excludeDependsOn) {
        const includeDependsOnTasks = new Set(options.includeDependsOnTasks ?? []);
        (0, get_exclude_task_1.getExcludeTasks)(new Set([`${context.projectName}:${context.targetName}`]), context.projectGraph.nodes, new Set(), includeDependsOnTasks).forEach((task) => {
            if (task) {
                args.push('--exclude-task', task);
            }
        });
    }
    try {
        const { success } = await (0, run_commands_impl_1.default)({
            command: `${gradlewPath} ${options.taskName}`,
            cwd: (0, node_path_1.dirname)(gradlewPath),
            args: args,
            __unparsed__: options.__unparsed__ || [],
        }, context);
        return { success };
    }
    catch (e) {
        return { success: false };
    }
}
