Generate and configure tasks in custom gradle plugin


(Patel) #1

Hello everyone,

I’m new to gradle, please pardon me if I’m not very clear :blush:. So I’m working on a custom gradle plugin for my organisation. We have +300 projects and we are moving from Ant to Gradle.
In that plugin I want to generate and configure custom tasks related to the plugin extension.

Please imagine the following configuration.

my {
    batches {
        main {
            mainClass = "my.custom.class"
        second {
            mainClass = "my.custom.otherclass"
        // ... more...and more

Will generate the following task for example : buildMainBatch, deployMainBatch, buildSecondBatch

So I create the following plugin

class MyPlugin implements Plugin<Project> {

    void apply(Project project) {

        def batches = project.container(Batch)
        def extension = project.extensions.create(MyExtension.EXTENSION_NAME, MyExtension, batches)

        // Only java
        project.plugins.withType(JavaPlugin) {

            project.with {
                ext.buildBatch = BuildBatchTask
                ext.deployBatch = DeployBatchTask

        project.afterEvaluate {
            batches.all { batch ->
                // build batch
                def buildTaskName = "build${name.capitalize()}Batch"
                project.task(buildTaskName, type: BuildBatchTask, group: EXTENSION_NAME) {
                    mainClass = batch.mainClass

                // deploy batch
                def deployTaskName = "deploy${name.capitalize()}Batch"
                project.task(deployTaskName, dependsOn: buildTaskName, type: DeployBatchTask, group: EXTENSION_NAME)

The extension class

class MyExtension {

    static final String EXTENSION_NAME = "my"

    final NamedDomainObjectContainer<Batch> batches

    MyExtension(batches) {
        this.batches = batches

    def batches(Closure closure) {

and this is the task

class BuildBatchTask extends Jar {

    String mainClass = "my.default.mainclass"

    BuildBatchTask() {

         project.afterEvaluate {
            doFirst {

    public void applyManifest() {
        manifest.attributes("Main-Class" : mainClass)

The problem is that the task is not executed properly. I guess the fact that I have two project.afterEvaluate in my code is the reason why it can’t work.

Is somebody can help me understand why this doesn’t work and maybe help me find a solution.

Best regards :slight_smile:

(Stefan Oehme) #2

Hi Eva,

Can you provide some more information on what is not working?

One thing that might be wrong is this subtle typo:

Instead of name.capitalize() (which refers to you probably wanted