Gradle Goodness: Init Script for Adding Extra Plugins to Existing Projects

Gradle Goodness: Init Script for Adding Extra Plugins to Existing Projects

Gradle is very flexible. One of the ways to alter the build configuration is with initialization or init scripts. These are like other Gradle scripts but are 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 directory or USER_HOME/.gradle directory or place a file init.gradle in our 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 an init script on our company intranet to be shared by all developers, then we can include the script with the apply(from:) method. In the following build file we use this syntax to include the script:

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 an init script where we add the Checkstyle plugin to projects with the Java plugin and the Codenarc 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 the Checkstyle configuration that needs to be used by the Checkstyle tasks.

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

posted on 2014-12-27 09:47  为梦飞翔  阅读(263)  评论(0编辑  收藏  举报

导航