Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gradle use variables in parent task that are defined in child

Tags:

gradle

I have a multiproject gradle build where I declare a task in the parent build that uses a variable that gets declared in the child projects (the value can change depending on the subproject). However, I get an error during the configuration phase that the variable doesn't exist. My setup looks like

build.gradle (top level)

subprojects {
   myTask {
     prop = valueDefinedInChild
   }

}

And then

build.gradle (subproject)

valueDefinedInChild = 'someValue'

Is there a way to do this correctly?

like image 976
Jeff Storey Avatar asked Feb 01 '13 22:02

Jeff Storey


People also ask

How do I set environment variables in Gradle?

Click on Environment variables. After that, click the New option. Now, create user variable, enter the variable name as Gradle_Home and paste the value of the home path e.g., C:\gradle-6.0. 1 in the variable value field.

Do we need to set environment variables for Gradle?

Environment variables are needed to customise the execution of the gradle tasks. Below is the working code in gradle 7.3.

How do you pass arguments in Gradle task?

Here, we don't use properties to pass arguments. Instead, we pass the –args flag and the corresponding inputs there. This is a nice wrapper provided by the application plugin. However, this is only available from Gradle 4.9 onward.

What is subprojects in Gradle?

The subproject producer defines a task named buildInfo that generates a properties file containing build information e.g. the project version. You can then map the task provider to its output file and Gradle will automatically establish a task dependency.


1 Answers

There is a way to do this (project.evaluationDependsOnChildren()), but I recommend to only use it as a last resort. Instead, I'd configure the commonalities at the top level, and the differences at the subproject level:

build.gradle (top level):

subprojects {
    task myTask { // add task to all subprojects
        // common configuration goes here
    }
}

build.gradle (subproject):

myTask {
    prop = 'someValue'
}

Another way to avoid repeating yourself is to factor out common code into a separate script, and have subprojects include it with apply from:. This is a good choice when the logic only applies to selected subprojects, or in cases where it's desirable to avoid coupling between parent project and subprojects (e.g. when using Gradle's new configuration on demand feature).

like image 87
Peter Niederwieser Avatar answered Oct 20 '22 15:10

Peter Niederwieser