Search code examples
gradlegroovyplugins

How to pass arguments to "groovy-gradle-plugin" at build time or run time


I'm new to writing plugins for gradle and am following the examples here:

https://docs.gradle.org/current/userguide/structuring_software_products.html

Under "build-logic/commons/src/main/groovy" there are gradle files which I want to pass a value to for when the file is compiled and a value for when the plugin is being run. How do you do this?

So here is the sample code:

plugins {
    id('java')
}

group = 'com.example.myproduct'

dependencies {
    implementation(platform("com.example.platform:product-platform:${build_version}"))

    testImplementation(platform("com.example.platform:test-platform:${run_version}"))
}

The idea is to specify the value ${build_version} when the "groovy-gradle-plugin" is being run (so the value is compiled into the plugin) and allow the ${run_version} to be specified when the generated plugin is run.

It's not clear to me how to set either of these values (even after lots of searching). Also, as a note, if I hard code values in, the generated plugin works as expected.

I have tried using

ext {
  build_version = "1.0"
}

but nothing seems to work


Solution

  • Following on from the comment by @User51, I needed to add the following to settings.gradle in the application which uses the plugin (this is important as it can't be set before the plugins in the build file):

    gradle.ext.myProp = "overrideValue"
    

    Then my plugin:

    plugins {
        id('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");
    }
    System.out.println("myProp=" + myProp)
    
    group = 'com.example.myproduct'
    
    dependencies {
        implementation(platform("com.example.platform:product-platform:${myProp}"))
    }
    

    Important to note here is the ordering again. We need to define myProp after the plugin block, but before it is used in the dependencies section.