Dark theme | Light theme

October 24, 2012

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:

apply plugin: 'java'
apply from: 'http://intranet/source/quality.gradle'

version = '2.1.1'
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.

// File: quality.gradle
allprojects {
    afterEvaluate { project ->
        def groovyProject = project.plugins.hasPlugin('groovy')
        def javaProject = project.plugins.hasPlugin('java')

        if (javaProject) {
            // Add Checkstyle plugin.
            project.apply plugin: 'checkstyle'

            // Task to download common Checkstyle configuration
            // from company intranet.
            task downloadCheckstyleConfig(type: DownloadFileTask) {
                description = 'Download company Checkstyle configuration'
                url = 'http://intranet/source/company-style.xml'
                destinationFile = checkstyle.configFile

            // For each Checkstyle task we make sure
            // the company Checkstyle configuration is 
            // first downloaded.
            tasks.withType(Checkstyle) { 
                it.dependsOn 'downloadCheckstyleConfig'

        if (groovyProject) {
            // Add Codenarc plugin.
            project.apply plugin: 'codenarc'

class DownloadFileTask extends DefaultTask {
    String url

    File destinationFile

    def downloadFile() {
        destinationFile.bytes = new URL(url).bytes

Code written with Gradle 1.2