简体   繁体   English

Gradle Kotlin DSL 替换令牌

[英]Gradle Kotlin DSL Replace Token

In my code there is const val VERSION = $version .在我的代码中有const val VERSION = $version
I want to replace $version with real version string which is in my build.gradle.kts .我想用我的build.gradle.kts真实版本字符串替换$version
How can I do this?我怎样才能做到这一点?

Working example here .工作示例在这里

One way is to use a template file (stored outside of src tree).一种方法是使用模板文件(存储在src树之外)。 Let's call it TemplateVersion.kt :我们称之为TemplateVersion.kt

class Version() {
    val version = "__VERSION";
}

and then in build.gradle.kts , as initial part of the compileKotlin task, we generate Version.kt from TemplateVersion.kt :然后在build.gradle.kts ,作为compileKotlin任务的初始部分,我们从TemplateVersion.kt生成Version.kt

val sourceFile = File(rootDir.absolutePath + "/resources/TemplateVersion.kt")
val propFile = File(rootDir.absolutePath + "/gradle.properties")
val destFile = File(rootDir.absolutePath + "/src/main/kotlin/${targetPackage}/Version.kt")

tasks.register("generateVersion") {
    inputs.file(sourceFile)
    inputs.file(propFile)
    outputs.file(destFile)

    doFirst {
        generateVersion()
    }
}

tasks.named("compileKotlin") {
    dependsOn("generateVersion") 
}

fun generateVersion() {
    val version: String by project
    val rootDir: File by project

    val inputStream: InputStream = sourceFile.inputStream()

    destFile.printWriter().use { out -> 
        inputStream.bufferedReader().forEachLine { inputLine ->
            val newLine = inputLine.replace("__VERSION", version)
            out.println(newLine) 
        }
    }

    inputStream.close()
}

where gradle.properties is:其中gradle.properties是:

version=5.1.50

It is trivially easy to add more fields to Version.kt , such as a build-timestamp.Version.kt添加更多字段非常容易,例如构建时间戳。

( Edit: This has been updated with a proper generateVersion task that will detect changes to gradle.properties . The compileKotlin task will invoke this task). 编辑:这已通过适当的generateVersion任务进行更新,该任务将检测gradle.properties更改compileKotlin任务将调用此任务)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM