I have a build.gradle
like so, with a tiny little custom task:
task ListOfStrings(type: ExampleTask, description: 'Prove we can pass string list without parentheses') {
TheList ('one', 'two', 'three') // this works but it's not beautiful
}
public class ExampleTask extends DefaultTask {
public void TheList(String... theStrings) {
theStrings.each {
println it
}
}
}
In the test.testLogging
block is events
: and we can pass a comma-separated list of strings without parentheses.
test {
outputs.upToDateWhen { false }
testLogging {
showStandardStreams true
exceptionFormat 'short'
events 'passed', 'failed', 'skipped' // this is beautiful
}
}
My question is: how do I write my ExampleTask
so I can write TheList
as a simple list of comma-separated strings omitting the parentheses?
My perfect-world scenario is to be able to express the task like so:
task ListOfStrings(type: ExampleTask, description: 'Prove we can pass string list without parentheses') {
TheList 'one', 'two', 'three'
}
That's not true that you need to define custom DSL/extension to solve this problem. You need to define a method instead of a field. Here's a working example:
task ListOfStrings(type: ExampleTask, description: 'Prove we can pass string list without parentheses') {
theList 'one', 'two', 'three'
}
public class ExampleTask extends DefaultTask {
List l = []
@TaskAction
void run() {
l.each { println it }
}
public void theList(Object... theStrings) {
l.addAll(theStrings)
}
}
The example you provided from test.testlogging
and the code example you are showing are slightly different - in that testlogging is using an extension and you are creating a task. Here's how you can define a custom extension that serves as an input to a task:
public class CustomExtension{
final Project project
CustomExtension(final Project project) {
this.project = project
}
public void theList(String... theStrings){
project.tasks.create('printStrings'){
doLast{
theStrings.each { println it }
}
}
}
}
project.extensions.create('List', CustomExtension, project)
List{
theList 'one', 'two', 'three'
}
Now running gradle printStrings
gives:
gradle printstrings
:printStrings
one
two
three
BUILD SUCCESSFUL
Total time: 3.488 secs