Gradle Init Scripts
This is a nice hack taken from Jamie Tanna on her blog.
You can create top-level Gradle tasks using initialization scripts to apply common actions anytime Gradle is ran.
Gradle will look for init scripts (and execute them) in the following order:
init.gradle
in the$GRADLE_USER_HOME/
directory.*.gradle
in the$GRADLE_USER_HOME/init.d/
directory.*.gradle
in the$GRADLE_HOME/init.d/
directory, in the Gradle distribution.
You can also invoke init scripts using the --init-script
or -I
flag:
gradle --init-script init.gradle
See Configuring the Gradle Build Environment for more info.
Here’s an example for a ~/.gradle/init.d/spotless.gradle
file:
allprojects {
afterEvaluate {
def spotless = tasks.findByName('spotlessApply')
if (spotless) {
tasks.withType(JavaCompile) {
finalizedBy(spotless)
}
}
}
}
Note the use of allprojects
.
This above snippet will do the following:
- If Spotless exists in a given project, it will apply the Spotless configuration:
- after the code has successfully compiled
- before any other configured tasks
Running tests or other static analysis tools could be applied in a similar fashion.