September 24, 2010

Gradle Goodness: Define A Short Plugin Id For Custom Plugins

We can extend Gradle easily with the Gradle plugin system. We can write plugins and apply them on our build scripts with the apply() method. We can use the complete classname of the plugin as an argument, but also a short plugin id. For example if we want to apply the Java plugin we can write apply plugin: 'java'. 'java' is the short plugin id for the class org.gradle.api.plugins.JavaPlugin.

We can define a short plugin id for our own custom plugins as well, so it is much easier to apply them in our scripts. In the classpath of our plugin we must add the directory META-INF/gradle-plugins. In this directory we create a properties file where the name is equal to the short plugin id we want to use. Inside the property file we must define a single property implementation-class that points to our plugin class.

Let's see how we can do this in the following sample. We first create a very simple Gradle plugin which only adds a task demo to the project. The task prints out the message MrhakiPlugin says hi!.

// File: buildSrc/src/main/groovy/com/mrhaki/gradle/MrHakiPlugin.groovy
package com.mrhaki.gradle

import org.gradle.api.*

class MrHakiPlugin implements Plugin<Project> {
    def void apply(Project project) {
        project.task('demo') << {
            println "MrhakiPlugin says hi!"

Next we create the properties file, because we want to use mrhaki as the short plugin id.

# File: buildSrc/src/main/resources/META-INF/gradle-plugins/

And that is all we need to do. Let's create a build.gradle script and execute our plugin:

// File: build.gradle
apply plugin: 'mrhaki'
$ gradle -q demo
MrhakiPlugin says hi!