Gradle Goodness: Set Default Values With Rule Based Model Configuration
When we use Rule based model configuration in our Gradle project we can give Gradle rules on how to manage objects from the model space. These rules are defined in a class that extends RuleSource
. When we want to set some default values for properties of a model object (in Gradle terms this is a subject) we can use the @Defaults
annotation. Rules annotated with @Defaults
are invoked right after the object is created and before any other methods that can mutate the state of the object.
The method, to set the default values, must have the type of the object as first parameter. Other parameters are considered input parameters and can be used to set a default value based on other model objects.
In a previous post we worked with a managed object VersionFile
. Let's add a default value for the version
property. We want the version
default value to be the unspecified
:
// File: buildSrc/src/main/groovy/mrhaki/gradle/VersionFileTaskRules.groovy
package mrhaki.gradle
import org.gradle.api.Task
import org.gradle.model.Defaults
import org.gradle.model.Model
import org.gradle.model.ModelMap
import org.gradle.model.Mutate
import org.gradle.model.Path
import org.gradle.model.RuleSource
class VersionFileTaskRules extends RuleSource {
@Model
void versionFile(final VersionFile versionFile) { }
/**
* Method to set default values for {@link VersionFile} object
* created by the {@link #versionFile} method.
*
* @param versionFile First argument is the type we want to set default values for
*/
@Defaults
void defaultsVersionFile(
final VersionFile versionFile) {
// Set default value for version property to.
versionFile.version = 'unspecified'
}
@Mutate
void createVersionFileTask(final ModelMap tasks, final VersionFile versionFile) {
tasks.create('generateVersionFile', VersionFileTask) { task ->
task.version = versionFile.version
task.outputFile = versionFile.outputFile
}
}
}
When we run the model
task we can see Gradle knows the defaultsVersionFile
methods was used to change the state of the VersionFile
instance:
$ gradle -q model
...
+ versionFile
| Type: mrhaki.gradle.VersionFile
| Creator: VersionFileTaskRules#versionFile(VersionFile)
| Rules:
⤷ VersionFileTaskRules#defaultsVersionFile(VersionFile)
+ outputFile
| Type: java.io.File
| Value: /Users/mrhaki/Projects/sample/build/version.txt
| Creator: VersionFileTaskRules#versionFile(VersionFile)
+ version
| Type: java.lang.String
| Value: null
| Creator: VersionFileTaskRules#versionFile(VersionFile)
...
$
Written with Gradle 3.2.