Gradle plugin management

Gradle is an amazing build tool. I've been using it for a long time already. Ever since I've contributed back in 2009, Gradle has become my Swiss army knife for automating just about everything.

Gradle has become my Swiss army knife for automating just about everything.

Today I learned something new with an unexpected nice side effect.

Context

When you create a Gradle plugin but don't release it to the Gradle plugin portal. You can't apply it using the plugin { id("my.private.plugin") } syntax.

This is regretable since it has the downside that plugin extensions can't be configured by their name. But with the more verbose configure<ExtensionType>{ ... } syntax, which also add an additional import.

But today I stumbled upon the plugin management section of the Gradle docs. From this I learned that you can tweak plugin resolution for the better.

The new insight

In your settings.gradle.kts file you can add a pluginManagement section and define a resolutionStrategy to specify what dependency to use for a given plugin id.

pluginManagement {
    resolutionStrategy {
        eachPlugin {
            if (requested.id.id == "my.private.plugin") {
                useModule("my.private:plugin:1.0.0")
            }
        }
    }
    repositories {
        jcenter()
    }
}

This allows you to use the plugin{ id("...") } syntax for you own private Gradle plugin.

And the nice side effect is that the named extension blocks are available! No need to use the configure<...> work-around.

So instead of this in your build.gradle.kts file

import my.private.plugin.MyPluginExtension

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath("my.private:plugin:1.0.0")
    }
}

apply(plugin="my.private.plugin")

configure<MyPluginExtension> {
    // ...
}

You can have a clean build.gradle.kts file like so.

plugins {
    id("my.private.plugin")
}

myPlugin {
    // ...
}

Allowing you to use your private plugin in the same way as published plugins can. Or you can use it as a stepping stone before publishing your private plugin to the Gradle plugin portal.

Property access

Additionally I've learned that you have access to the property values defined in the gradle.properties file in the settings.gradle.kts file with the following syntax.

val someProperty : String by settings

Never really needed it but now that I'm managing a bunch of repositories for Kuberig with dependencies this makes it easier to push version changes downstream.