Gradle goodness:init Script for Adding Extra Plugins to Existing Projects
Gradle is very flexible. One of the ways to alter the build configuration was with initialization or init scripts. These is like other Gradle scripts but is executed before the build. We can use different ways to add the init script to a build. For example we can use the command-line option -I or --init-script , place the script in the init.d directory of our GRADLE_HOME direct Ory or USER_HOME/.gradle directory or place a file into our init.gradle USER_HOME/.gradle directory.
We can also use the apply(from:) method to include such a script in our build file. We can reference a file location, but also a URL. Imagine we place a init script on our company intranet to is shared by all developers and then we can include the script wit H the apply(from:) method. The following build file we use this syntax to include the script:
View Sourceprint?
0.
apply plugin:
‘java‘
1.
apply from:
‘http://intranet/source/quality.gradle‘
2.
3.
version =
‘2.1.1‘
4.
group = ‘com.mrhaki.gradle.sample
The following script is a init script where we add the Checkstyle plugin to projects with the Java plugin and the Codenar C plugin to projects with the Groovy plugin. Because The Groovy plugin extends the Java plugin the Checkstyle plugin is added to the groovy project as well.
Notice We also add the downloadCheckstyleConfig task. With this task we download from the intranet of the Checkstyle configuration that needs to be used by the Checkstyle tasks.
View Sourceprint?
00.
// File: quality.gradle
01.
allprojects {
02.
afterEvaluate { project ->
03.
def
groovyProject = project.plugins.hasPlugin(
‘groovy‘
)
04.
def
javaProject = project.plugins.hasPlugin(
‘java‘
)
05.
06.
if
(javaProject) {
07.
// Add Checkstyle plugin.
08.
project.apply plugin:
‘checkstyle‘
09.
10.
// Task to download common Checkstyle configuration
11.
// from company intranet.
12.
task downloadCheckstyleConfig(type: DownloadFileTask) {
13.
description =
‘Download company Checkstyle configuration‘
14.
15.
url =
‘http://intranet/source/company-style.xml‘
16.
destinationFile = checkstyle.configFile
17.
}
18.
19.
// For each Checkstyle task we make sure
20.
// the company Checkstyle configuration is
21.
// first downloaded.
22.
tasks.withType(Checkstyle) {
23.
it.dependsOn
‘downloadCheckstyleConfig‘
24.
}
25.
}
26.
27.
if
(groovyProject) {
28.
// Add Codenarc plugin.
29.
project.apply plugin:
‘codenarc‘
30.
}
31.
}
32.
}
33.
34.
class
DownloadFileTask
extends
DefaultTask {
35.
@Input
36.
String url
37.
38.
@OutputFile
39.
File destinationFile
40.
41.
@TaskAction
42.
def
downloadFile() {
43.
destinationFile.bytes =
new
URL(url).bytes
44.
}
45.
}
Code written with Gradle 1.2
Gradle goodness:init Script for Adding Extra Plugins to Existing Projects