git Gradle:将变量从一个任务传递到另一个任务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33897544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 11:33:08  来源:igfitidea点击:

Gradle: Passing variable from one task to another

gitvariablesgroovygradletask

提问by crystallinity

I want to pass a variable from one task to another, in the same build.gradle file. My first gradle task pulls the last commit message, and I need this message passed to another task. The code is below. Thanks for help in advance.

我想在同一个 build.gradle 文件中将一个变量从一个任务传递到另一个任务。我的第一个 gradle 任务会提取最后一条提交消息,我需要将此消息传递给另一个任务。代码如下。提前感谢您的帮助。

task gitMsg(type:Exec){
    commandLine 'git', 'log', '-1', '--oneline'
    standardOutput = new ByteArrayOutputStream()
    doLast {
       String output = standardOutput.toString()
    }
}

I want to pass the variable 'output' into the task below.

我想将变量“输出”传递到下面的任务中。

task notifyTaskUpcoming << {
    def to = System.getProperty("to")
    def subj = System.getProperty('subj') 
    def body = "Hello... "
    sendmail(to, subj, body)
}

I want to incorporate the git message into 'body'.

我想将 git 消息合并到“正文”中。

采纳答案by Stanislav

You can define an outputvariable outside of the doLastmethod, but in script root and then simply use it in another tasks. Just for example:

您可以outputdoLast方法之外定义一个变量,但在脚本根目录中,然后在其他任务中简单地使用它。举个例子:

//the variable is defined within script root
def String variable

task task1 << {
    //but initialized only in the task's method
    variable = "some value"
}

task task2 << {
    //you can assign a variable to the local one
    def body = variable
    println(body)

    //or simply use the variable itself
    println(variable)
}
task2.dependsOn task1

Here are 2 tasks defined. Task2depends on Task1, that means the second will run only after the first one. The variableof String type is declared in build script root and initialized in task1doLastmethod (note, <<is equals to doLast). Then the variable is initialized, it could be used by any other task.

这里定义了 2 个任务。Task2取决于Task1,这意味着第二个只会在第一个之后运行。该variable字符串类型在构建脚本根和宣布,以初始化task1doLast方法(注意,<<是等于doLast)。然后变量被初始化,它可以被任何其他任务使用。

回答by Rene Groeschke

I think global properties should be avoided and gradle offers you a nice way to do so by adding properties to a task:

我认为应该避免全局属性,而 gradle 通过向任务添加属性为您提供了一种很好的方法:

task task1 {
     doLast {
          task1.ext.variable = "some value"
     }
}

task task2 {
    dependsOn task1
    doLast { 
        println(task1.variable)
    }
}