How can I reduce boilerplate when calling a custom task multiple times?

I have a lot of boilerplate code in my build file and I’m wondering if there is a better way of doing what I’m trying to do.

This is what I have:

task buildProject1(type: GradleBuild) {
    dir = "../project1"
     tasks = ["clean", "build"]
    getStartParameter().setExcludedTaskNames(['test']);
}
    task buildAll(dependsOn:
     [
        buildProject1,
         buildProject2,
         ...
    ]
) << {}

The boilerplate comes from repeating the buildProject1 task for 20 or so projects when the only thing that is different is the dir property.

What I would like to be able to do is something like this (forgive me if I get the groovy syntax wrong):

def buildProject(projectDir: String) {
    gradleBuild(dir: projectDir, tasks: ['clean', 'build'], excludedTasks: ['test'])
}
  tasks buildAll << {
    buildProject('../project1')
    buildProject('../project2')
    ...
}

I don’t think its possible to do this as things stand. Is there any other way I can cut down on the boilerplate?

you can create your different GradleBuild tasks dynamically like:

['../project1', '../project2', '../project3'].each{ projectDir ->
    def buildTaskName = "build${projectDir - '../'}"
    task (buildTaskName, type:GradleBuild){
        dir = projectDir
        tasks = ["clean", "build"]
        getStartParameter().setExcludedTaskNames(['test'])
    }
}

to run all GradleBuild tasks, you can create a new task, that depends on all tasks of type GradleBuild:

task buildAll{
   dependsOn tasks.withType(GradleBuild)
}

now you just need to run “Gradle buildAll” to run all your GradleBuild tasks.

hope that helped,

cheers, René

That’s certainly a lot more concise but I’m wondering if it would cause me trouble in other areas.

Is it possible to control the order in which the projects are built?

Is it possible to run some of the GradleBuild tasks but not others?

The order of execution of tasks that another task depends on is not guaranteed in gradle. ‘tasks’ is of type TaskContainer (http://gradle.org/docs/current/javadoc/org/gradle/api/tasks/TaskContainer.html). Have a look at its API to get more methods you can use to filter specific tasks. For example you can use the findAll method if you want to write your own filter:

task buildAll(){

dependsOn tasks.findAll{myTask -> your custom logic for filtering a task or not…} }

Cool, thanks for your help.