重构gradle任务“类型:复制”中的重复代码

时间:2019-05-17 11:24:31

标签: gradle groovy build.gradle

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任务)指定相同的目标目录?

1 个答案:

答案 0 :(得分:1)

您可以使用自定义的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")
// ...