Setting Java compiler options from plugins {} block in Kotlin DSL


(Ross Goldberg) #1

TL;DR
I found a solution for my immediate question, which I’ve posted in a reply.

What is the best way to configure Java compiler options from a plugin?

Detail
I’m using the Kotlin DSL.

I’ve created a Plugin<Project> with id = "my-config" using the java-gradle-plugin.

The plugin sets various standard settings for my projects in its Plugin<Project>#apply(Project) method.

I have successfully applied my plugin using the following at the top of my build.gradle.kts (and using the plugin-to-included-build-artifact redirection code reproduced at the bottom of this post):

plugins {
    java
    id("my-config") version "1.0"
}

Setting project-level settings works fine, but when I try to set Java compiler options using project.getTasks().withType(JavaCompile.class).forEach(...), no tasks are defined yet on my project, so I cannot configure them.

What is the best way to configure Java compiler options from a plugin?

I assume that I must configure them using some variant of the aforementioned JavaCompile task loop. If there are other high-level ways to configure Java compiler options, please let me know.

Is there any way to make the tasks available to my plugin’s apply(Project) method? Either by changing the plugin, by changing how I apply it, or otherwise?

Would a Plugin<JavaCompile> work? If so, could I use its apply(JavaCompile)? Can I bundle said Plugin<JavaCompile> with a Plugin<Project> to have both applied with only one reference? If not, where would I apply a Plugin<JavaCompile>?

If the above won’t work, would I need to define some task in my-config, and then manually call that task from my build script? I’d prefer to only require one reference to my plugin per build file (like solely from the plugins {} block), but I guess I might have to have more than one line…

settings.gradle.kts redirection code:
Is there any simpler way to redirect from a plugin id to an included build?

pluginManagement {
    repositories {
        gradlePluginPortal()
    }

    resolutionStrategy {
        eachPlugin {
            if (requested.id.id == "my-config") {
                useModule(mapOf("group" to "my-group", "name" to "my-config", "version" to requested.version))
            }
        }
    }
}

(Ross Goldberg) #2

I found the answer:

project.afterEvaluate(
    p -> {
        p.getTasks().withType(JavaCompile.class).forEach(
            javaCompile -> {
                // config compiler options here
            }
        )
    }
);