In Gradle, you can pass properties to a build script in many different ways. You could pass it via gradle.properties, you could pass through the -D (jvm params) options, or you could pass through the -P option (project properties).

I was facing a situation where I needed to call one Gradle build script from my current build script.

For example, I had my build script (build script #1) which displayed “This is $first $second first build script”, and from that build script, I wanted to call a different build script (build script #2) which displayed “This is $first $last second build script”. However, I did not define these three parameters in my gradle.properties, and I wanted to define them using Gradle’s -P option.

The end goal would be for me to be in the root directory of the first build script and type: “gradle build -Pfirst=marco -Plast-coronas” and the console would print: “This is marco coronas first build script. This is marco coronas second build script”.

In order to call one build script from a another build script, you need to define a task with the type “GradleBuild”:

task CallOtherBuildScript(type: GradleBuild){
buildFile = "${PathToTheBuildFile}"
tasks = ['clean','build']
startParameter.projectProperties = project.getGradle().getStartParameter().getProjectProperties()
}

Within a GradleBuild typed task, you can define many things; one essential variable to set is the build file, which corresponds to the other ‘gradle.build’ you are trying to call. Another essential variable to set is the tasks, which correspond to which tasks you want to run from this build script. Finally we get to the point of this blog, we want to propagate our -P parameters to the other build script. This is done by setting the startParameter’s project properties, which is shown on the last line of code.

Leave a comment

Your email address will not be published. Required fields are marked *

X