Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Gradle | Gradle カスタムPluginの作成方法

概要

Gradle カスタムPluginの作成方法

内容

標準出力するだけのPluginをサンプルとして作成します。
Plugin名:Sample
タスク名:hoge

サンプルコード

build.gradle
def defaultEncoding = 'UTF-8'

apply plugin: 'groovy'
apply plugin: 'eclipse'

sourceCompatibility = 1.7
targetCompatibility = 1.7

group = 'gr.java_conf.tb'
archivesBaseName = 'sample'
version = '1.0-SNAPSHOT'

repositories { mavenCentral() }

dependencies {
  compile gradleApi()
  groovy localGroovy()
}

apply plugin: 'maven'

uploadArchives {
  repositories {
    mavenDeployer {
      repository(url: 'file://' + new File(System.getProperty('user.home'), '.m2/repository').absolutePath)
    }
  }
}
Sample.groovy
package gr.java_conf.tb

import org.gradle.api.Plugin
import org.gradle.api.Project

class Sample implements Plugin<Project> {

  @Override
  public void apply(Project target) {
    target.task('hoge', type: SampleTask)
  }
}
SampleTask.groovy
package gr.java_conf.tb
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction

class SampleTask extends DefaultTask {
  @TaskAction
  def hoge() {
    println "hoge"
  }
}

利用側プロジェクトのサンプルコード

build.gradle

※下記を追記

buildscript {
  repositories {
    mavenRepo urls: 'file://' + new File(System.getProperty('user.home'), '.m2/repository').absolutePath
  }
  dependencies { classpath 'gr.java_conf.tb:sample:1.0-SNAPSHOT' }
}

apply plugin: 'sample'
Sampleのhogeタスク出力
[sts] -----------------------------------------------------
[sts] Starting Gradle build for the following tasks: 
[sts]      :hoge
[sts] -----------------------------------------------------
:hoge
hoge

BUILD SUCCESSFUL

Total time: 1.012 secs
[sts] -----------------------------------------------------
[sts] Build finished succesfully!
[sts] Time taken: 0 min, 1 sec
[sts] -----------------------------------------------------