2015-11-03 20 views
1

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

我们需要一个正确的条件在以下块检查,如果任务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任务来收集组装战争的资源,并且在这种情况下可能不会完全禁用。可以将代码移动到依赖于docker的单独任务,并在输出目录processResources上运行,但在运行war之前,然而,这样的构造对于这样一个简单的事情将导致更少的清晰度。

回答

0

您可以简单地为docker任务添加附加依赖项,以使其不仅依赖于build任务,还依赖于processResources。在这种情况下,只有在应执行docker时才会调用您的processResources任务。

另一种解决方案是使用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' 
     } 
} 

此外,您可以尝试配置您的自定义任务,使之通过设置禁用启用属性设置为false,如果docker任务是不是在执行图。在这种情况下,您不必在执行阶段提供一些标志和逻辑。像:

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

但是,如果没有一些额外的配置,将无法单独运行此自定义任务。

+0

感谢您的回答。您能否请您根据我的问题添加到您的提示中,并在必要时进行更新。如果我理解正确,保留任务并且仅使代码块有条件的最优雅的解决方案是使用通过TaskExecutionGraph初始化的标志。会尝试让知道。 –

+0

@Oleg这个标志有一个问题,它只在执行阶段可用,但是你的任务很像复制任务,你提供的逻辑是在配置阶段执行的。我想,根据你在最新的问题中的说明,最好的解决方案是将它分成2个任务,并在图形准备就绪后禁用其中的一个,就像在最后一个例子中完成的那样。只要不要忘记在任务上方留下评论,即可能在其他地方禁用该评论。当然,如果你能够将你的逻辑转移到执行阶段,那么flag就是解决方案 – Stanislav

相关问题