使用来自 gradle-script-kotlin 的 ant 任务

Using ant tasks from gradle-script-kotlin

如何从我的 build.gradle.kts 脚本访问 ant 任务?特别是,我对 ant.patch 任务感兴趣。

我可以像这样延长它吗?

task("patchSources", Patch::class) {

我可以像这样从其他任务调用它吗?

task("patchSources") {
    doLast {
        ant.patch(...)
    }
}

我在Groovy知道怎么做:How do I apply a patch file in Gradle?

这对我有用:

import org.apache.tools.ant.taskdefs.Patch

val patchConfigTask = task("patchConfig") {
    dependsOn(unzipTask)    

    doLast {
        val resources = projectDir.resolve("src/main/resources")
        val patchFile = resources.resolve("config.patch")

        Patch().apply {
            setPatchfile(patchFile)
            setDir(buildDir.resolve("config/"))
            setStrip(1)  // gets rid of the a/ b/ prefixes
            execute()
        }
    }
}

我不确定这是不是唯一正确的方法。

AntBuilder extends from Groovy's AntBuilder。您可以通过使用 invokeMethod 并提供所需的任务作为第一个参数,并在第二个参数中提供要绑定为映射的属性,将动态方法调用从 groovy(例如 ant.patch())转换为 Kotlin。

例如,对于您的 补丁 用例 (available properties documentation),Kotlin 可能如下所示:

val patchSources by tasks.creating {
  doLast {
    ant.invokeMethod("patch", mapOf(
        "patchfile" to patchFile,
        "dir" to configDir,
        "strip" to 1
    ))
  }
}