将字符串列表传递给gradle任务属性而不使用括号

时间:2016-02-10 03:15:58

标签: gradle groovy build.gradle

我有一个build.gradle,只有一点点自定义任务:

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
        }
    }
}

test.testLogging区块中events:我们可以传递以逗号分隔的字符串列表,不带括号

test {
    outputs.upToDateWhen { false }
    testLogging {
        showStandardStreams true
        exceptionFormat 'short'
        events 'passed', 'failed', 'skipped' // this is beautiful
    }
}

我的问题是:如何撰写我的ExampleTask以便我可以将TheList写为逗号分隔字符串的简单列表省略括号

我的完美世界场景是能够像这样表达任务:

task ListOfStrings(type: ExampleTask, description: 'Prove we can pass string list without parentheses') {
    TheList 'one', 'two', 'three'
}

2 个答案:

答案 0 :(得分:3)

您从test.testlogging提供的示例和您显示的代码示例略有不同 - 因为testlogging正在使用扩展并且您正在创建任务。以下是如何定义用作任务输入的自定义扩展:

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'
}

现在正在运行gradle printStrings

gradle printstrings
:printStrings
one
two
three

BUILD SUCCESSFUL

Total time: 3.488 secs

答案 1 :(得分:2)

您不需要定义自定义DSL /扩展来解决此问题。您需要定义方法而不是字段。这是一个有效的例子:

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)
    }
}