gpt4 book ai didi

gradle - 重构gradle任务 “type: Copy”中的重复代码

转载 作者:行者123 更新时间:2023-12-03 05:07:07 26 4
gpt4 key购买 nike

gradle项目包含几个类似的任务type:Copy,其中一些需要额外的检查。

task copyPackage1(type: Copy) {
from buildPackage1
into "/pkgs/"
eachFile {
if (it.relativePath.getFile(destinationDir).exists()) {
throw new GradleException("Probably version was no updated. File exists: " + it)
}
}
}
...
task copyPackage2(type: Copy) {
from buildPackage2
into "/pkgs/"
eachFile {
if (it.relativePath.getFile(destinationDir).exists()) {
throw new GradleException("Probably version was no updated. File exists: " + it)
}
}
}

如何重构重复的检查并为所有类似任务(但不是所有 Copy任务)指定相同的目标目录?

最佳答案

您可以使用自定义的Gradle插件(如Gradle论坛上的this similar question中所建议的)来实现此目标,也可以使用简单的Groovy方法来创建和配置任务,如下所示:

// define a "task creator" method 
ext.createCopyToPkgTask = { String taskName , String fromDir ->
return project.tasks.create(taskName, Copy.class){
from fromDir
into "/pkgs"
eachFile {
if (it.relativePath.getFile(destinationDir).exists()) {
throw new GradleException("Probably version was no updated. File exists: " + it)
}
}
}
}

/* declare your similar tasks using the creator method above */
createCopyToPkgTask("copyPackage1","buildPackage1")
createCopyToPkgTask("copyPackage2","buildPackage2")
// ...

关于gradle - 重构gradle任务 “type: Copy”中的重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56185430/

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