Search code examples
gradlegradle-kotlin-dsl

Gradle Kotlin DSL Replace Token


In my code there is const val VERSION = $version.
I want to replace $version with real version string which is in my build.gradle.kts.
How can I do this?


Solution

  • Working example here.

    One way is to use a template file (stored outside of src tree). Let's call it 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:

    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:

    version=5.1.50
    

    It is trivially easy to add more fields to Version.kt, such as a build-timestamp.

    (Edit: This has been updated with a proper generateVersion task that will detect changes to gradle.properties. The compileKotlin task will invoke this task).