Gradle:将变量从一个任务传递到另一个任务
Gradle: Passing variable from one task to another
我想在同一个 build.gradle 文件中将一个变量从一个任务传递到另一个任务。我的第一个 gradle 任务提取最后一条提交消息,我需要将此消息传递给另一个任务。代码如下。提前感谢您的帮助。
task gitMsg(type:Exec){
commandLine 'git', 'log', '-1', '--oneline'
standardOutput = new ByteArrayOutputStream()
doLast {
String output = standardOutput.toString()
}
}
我想将变量 'output' 传递到下面的任务中。
task notifyTaskUpcoming << {
def to = System.getProperty("to")
def subj = System.getProperty('subj')
def body = "Hello... "
sendmail(to, subj, body)
}
我想将 git 消息合并到 'body' 中。
您可以在 doLast
方法之外定义一个 output
变量,但在脚本根目录中,然后在其他任务中简单地使用它。举个例子:
//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
在构建脚本根目录中声明,在task1
doLast
方法中初始化(注意,<<
等同于doLast
)。然后变量被初始化,它可以被任何其他任务使用。
我认为应该避免使用全局属性,gradle 通过向任务添加属性为您提供了一种很好的方法:
task task1 {
doLast {
task1.ext.variable = "some value"
}
}
task task2 {
dependsOn task1
doLast {
println(task1.variable)
}
}
我想在同一个 build.gradle 文件中将一个变量从一个任务传递到另一个任务。我的第一个 gradle 任务提取最后一条提交消息,我需要将此消息传递给另一个任务。代码如下。提前感谢您的帮助。
task gitMsg(type:Exec){
commandLine 'git', 'log', '-1', '--oneline'
standardOutput = new ByteArrayOutputStream()
doLast {
String output = standardOutput.toString()
}
}
我想将变量 'output' 传递到下面的任务中。
task notifyTaskUpcoming << {
def to = System.getProperty("to")
def subj = System.getProperty('subj')
def body = "Hello... "
sendmail(to, subj, body)
}
我想将 git 消息合并到 'body' 中。
您可以在 doLast
方法之外定义一个 output
变量,但在脚本根目录中,然后在其他任务中简单地使用它。举个例子:
//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
在构建脚本根目录中声明,在task1
doLast
方法中初始化(注意,<<
等同于doLast
)。然后变量被初始化,它可以被任何其他任务使用。
我认为应该避免使用全局属性,gradle 通过向任务添加属性为您提供了一种很好的方法:
task task1 {
doLast {
task1.ext.variable = "some value"
}
}
task task2 {
dependsOn task1
doLast {
println(task1.variable)
}
}