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

时间:2015-11-24 15:27:44

标签: git variables groovy gradle task

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

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

我想传递变量'输出'进入下面的任务。

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

我想将git消息合并到&#39; body&#39;中。

2 个答案:

答案 0 :(得分:42)

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

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

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

答案 1 :(得分:12)

您可以在output方法之外定义doLast变量,但在脚本根目录中,然后只需在其他任务中使用它。仅举例:

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

这里定义了2个任务。 Task2取决于Task1,这意味着第二个将仅在第一个之后运行。 String类型的variable在构建脚本root中声明,并在task1 doLast方法中初始化(注意,<<等于doLast)。然后变量被初始化,任何其他任务都可以使用它。