如何在Gradle Kotlin构建中配置processResources任务

Kev*_*dge 4 gradle kotlin gradle-kotlin-dsl

我在基于groovy的构建脚本中有以下内容.如何在基于kotlin的脚本中执行相同的操作?

processResources {

    filesMatching('application.properties'){
        expand(project.properties)
    }

}
Run Code Online (Sandbox Code Playgroud)

mko*_*bit 8

通过更新Kotlin DSL和Gradle版本中的API,您可以执行以下操作:

import org.gradle.language.jvm.tasks.ProcessResources

plugins {
  java
}

tasks {
  "processResources"(ProcessResources::class) {
    filesMatching("application.properties") {
      expand(project.properties)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

并且:

val processResources by tasks.getting(ProcessResources::class) {
  filesMatching("application.properties") {
    expand(project.properties)
  }
}
Run Code Online (Sandbox Code Playgroud)


Rus*_*lan 7

我认为任务应如下所示:

编辑:根据此评论gradle / kotlin-dsl存储库中。任务配置应以这种方式工作:

import org.gradle.language.jvm.tasks.ProcessResources

apply {
    plugin("java")
}

(tasks.getByName("processResources") as ProcessResources).apply {
    filesMatching("application.properties") {
        expand(project.properties)
    }
}
Run Code Online (Sandbox Code Playgroud)

真丑。因此,我建议为此使用以下实用程序功能,直到完成一个上游:

configure<ProcessResources>("processResources") {
    filesMatching("application.properties") {
        expand(project.properties)
    }
}

inline fun <reified C> Project.configure(name: String, configuration: C.() -> Unit) {
    (this.tasks.getByName(name) as C).configuration()
}
Run Code Online (Sandbox Code Playgroud)


SoB*_*ich 5

为什么不只使用“ withType”?我的意思是(恕我直言)

tasks {
  withType<ProcessResources> {
.. 
}
Run Code Online (Sandbox Code Playgroud)

看起来比

tasks {
  "processResources"(ProcessResources::class) {
.. 
}
Run Code Online (Sandbox Code Playgroud)

所以,

tasks.withType<ProcessResources> {
    //from("${project.projectDir}src/main/resources")
    //into("${project.buildDir}/whatever/")
    filesMatching("*.cfg") {
        expand(project.properties)
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

使用较新的版本,您可以执行以下操作:

tasks.processResources {}
Run Code Online (Sandbox Code Playgroud)

要么

tasks { processResources {} }
Run Code Online (Sandbox Code Playgroud)

生成的访问器是“惰性”的,因此它具有所有优点并具有缺点。