gradlepropertiesbuild.gradlegradle-plugingradle.properties

How do you access gradle.ext properties in Plugin Java source code?


I need a property to (one) be available when a plugin is applied and (two) allow for a calculated override value in the settings.gradle file. A project property would be ideal as it can have a default set in gradle.properties:

# gradle.properties
myProp=originalValue

This is great because it can be overrode with a command line argument like -PmyProp=newValue, but I was not able to find a good way to override the property in the settings.gradle file before the build.gradle executes (i.e. before the plugins are applied).

For instance all of these leave rootProject.myProp unaltered at plugin application:

// settings.gradle
rootProject.getProperties.put("myProp", "overrideValue")
settings.ext.myProp = "overrideValue"
settings.extensions.myProp = "overrideValue"
gradle.startParameters.projectProperties.myProp = "overrideValue"

We cannot do any magic in the build.gradle either because no logic can exist before the plugins block:

// build.gradle
plugins {
    id 'com.myCompany.myPlugin' version 1.0.0 // 'myProp' must be set by now
}

One workaround I can think of would be to use:

// settings.gradle
gradle.ext.myProp = "overrideValue"

... but there doesn't seem to be a good way to access gradle.ext properties in Java source code (for a plugin), or is there?


Solution

  • This seems to work for the gradle.ext.myProp use case, but it is surprising to me that the only workable approach is to cast the Gradle object to an ExtensionAware object:

    // MyPlugin.java
    String myProp = (String) project.getRootProject().getProperties().getOrDefault("myProp", null);
    Gradle gradle = project.getRootProject().getGradle();
    if ((myProp == null)  && (gradle instanceof ExtensionAware)) {
        ExtensionAware gradleExtensions = (ExtensionAware) gradle;
        myProp = (String) gradleExtensions.getExtensions().getExtraProperties().get("myProp");
    }
    

    It seems like what I'm trying to do should be commonplace, so is there a better way like solely using project properties?

    If so, then how do you change the values in the settings.gradle file?