简体   繁体   English

使用其他任务中的参数调用 Gradle 任务

[英]Call Gradle task with parameters inside other task

I have a Gradle task which looks like this (it collects inputs from user and then passes them to the second task):我有一个看起来像这样的 Gradle 任务(它收集用户的输入,然后将它们传递给第二个任务):

task A() {
    doFirst {
        ant.input(message: "Version:", addproperty: 'version')
        tasks.b "-Pversion=${ant.properties.version}" //attempt to invoke task B()
    }
}

The second task just print the passed variables:第二个任务只是打印传递的变量:

task B() {
    doFirst {
        println "Version: ${version}"
    }
}

The problem is, that the task A does not invoke task B. I've tried with finalizedBy and doLast but I couldn't find a solution how to pass arguments while executing the task inside the other task.问题是,任务 A 不会调用任务 B。我已经尝试使用finalizedBydoLast ,但我找不到如何在另一个任务中执行任务时传递参数的解决方案。 When I execute the task B via command line like:当我通过命令行执行任务 B 时,例如:

gradle B -Pversion=1.0.0

it works fine, and params are passed correctly.它工作正常,并且参数传递正确。

It's not possible to 'invoke' task B from task A - Gradle tasks are not like functions.从任务 A 中“调用”任务 B 是不可能的——Gradle 任务不像函数。

The only way to pass data from one task to another is if将数据从一个任务传递到另一个任务的唯一方法是

  1. the first task saves the variables to a file,第一个任务将变量保存到文件中,
  2. then the second task reads the file produced by the first task.然后第二个任务读取第一个任务生成的文件。

There is an example in the docs , which you can adjust to capture user input 文档中有一个示例,您可以对其进行调整以捕获用户输入

abstract class Producer extends DefaultTask {
    @OutputFile
    abstract RegularFileProperty getOutputFile()

    @TaskAction
    void produce() {
        // capture user input
        ant.input(message: "Version:", addproperty: 'version')
        String message = ant.properties.version
        // save the user input to a file
        def output = outputFile.get().asFile
        output.text = message
        logger.quiet("Wrote '${message}' to ${output}")
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM