gpt4 book ai didi

gradle - gradle.processResources 中的代码块取决于是否请求了另一个任务

转载 作者:行者123 更新时间:2023-12-03 04:36:24 24 4
gpt4 key购买 nike

我们有一个可选的 gradle 任务 docker这取决于任务 war ,如果执行,需要生成一个带有额外文件的war文件。这个额外的文件可以添加到 processResources 中的资源中。任务(或可能直接在 war 任务中)。但是,如果任务 docker,则不能运行相应的代码块。未被请求且不会运行。

我们需要一个 正确条件 在以下 block 中检查任务 docker正在筹备中:

processResources {
if (/* CONDITION HERE: task docker is requested */) {
from ("${projectDir}/docker") {
include "app.properties"
}
}
}

task docker(type: Dockerfile) {
dependsOn build
...

澄清 : processResourceswar 的标准依赖项任务,后者是 build 的标准依赖项任务。 processResources总是在 build 上执行, 有或没有 docker收集用于组装 war 的资源的任务,在这种情况下可能不会完全禁用。可以将有问题的代码移动到依赖于 docker 的单独任务中。并处理 processResources 的输出目录, 在 war 之前但是,运行这样的结构会导致这样一个简单的事情变得不那么清晰。

最佳答案

您可以简单地向您的 docker 添加额外的依赖项。任务,使其不仅依赖于build任务,但也在 processResources .在这种情况下,您的 processResources只有在 docker 时才会调用任务应该被执行。

另一种解决方案是使用 TaskExecutionGraph .这使您可以初始化一些变量,该变量可以告诉您是否将执行某些任务。但是您必须了解,该图仅在所有配置完成后才准备好,您只能在执行阶段依赖它。这是一个简短的例子,它是如何使用的:

//some flag, whether or not some task will be executed
def variable = false

//task with some logic executed during the execution phase
task test1 << {
if (variable) {
println 'task2 will be executed'
} else {
println 'task2 will not be executed'
}
}

//according to whether or not this task will run or not,
//will differs test1 task behavior
task test2(dependsOn: test1) {

}

//add some logic according to task execution graph
gradle.taskGraph.whenReady {
taskGraph ->
//check the flag and execute only if it's true
if (taskGraph.hasTask(test2)) {
variable = true
println 'task test2 will be executed'
}
}

此外,如果 docker,您可以尝试配置您的自定义任务,通过将启用属性设置为 false 来禁用它。任务不在执行图中。在这种情况下,您不必在执行阶段提供一些标志和逻辑。像:
task test1 {       
//some logic for execution
doLast {
println "execute some logic"
}
}

task test2(dependsOn: test1) {

}

gradle.taskGraph.whenReady {
taskGraph ->
if (!taskGraph.hasTask(test2)) {
//Disable test1 task if test2 will not run
test1.enabled = false
}
}

但是如果没有一些额外的配置,就不可能单独运行这个自定义任务。

关于gradle - gradle.processResources 中的代码块取决于是否请求了另一个任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33503145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com