Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Zip Task Multiple Times In Gradle

Tags:

gradle

I need to update 9 zip files and the code to do it is about 15 lines. I'd rather not have to repeat the same 15 lines 9 times in the build script with just different variable names.

Is it possible to call a Zip task in a loop from another task?

Using dynamic tasks seems to be one way but it requires me to list the array of tasks twice which I can see causing an error in future when an extra item is added.

[war1, war2, war3, war4, war5, war6, war7, war8, war9].each { warName ->
    task "task$warName"(type: Zip) {
        archiveName = "${warName}.war"          
        //etc etc
    }
}
task all(dependsOn: [taskwar1, taskwar2, taskwar3, taskwar4, taskwar5, taskwar6, taskwar7, taskwar8, taskwar9]) {

}

Is there any alternative?

like image 310
opticyclic Avatar asked Dec 24 '22 23:12

opticyclic


1 Answers

Firs of all your code might be simplified just to:

task allWars

(1..9).each { id ->
   task "taskwar${id}"(type: Zip) {
      archiveName = "war${id}.war"
   } 
   allWars.dependsOn "taskwar${id}"
}

And a solution with task rules:

tasks.addRule('Pattern: taskwar<ID>') { String taskName ->
    if (taskName.startsWith('taskwar')) {
        task(taskName, type: Zip) {
            archiveName = "${taskName - 'task'}.war"
        }
    }
}

task allWars {
   dependsOn << (1..9).collect { "taskwar$it" }
}

There are almost no obvious pros and cons - when it comes to functionality. Basically solution without rules is shorter as you can see, so if you represent attitude less code is better that's the way to go. However task rules were created in gradle for this kind of situations - where there are lots of predefined tasks. First solution is more groovier while the second one is more gradler ;)

like image 123
Opal Avatar answered Dec 31 '22 11:12

Opal