svenjacobs
06/16/2025, 11:48 AMconst val VERSION = "1.0.0"
in my code that can be specified during compile time. Of course I could use sed
or something similar to dynamically edit a file before compilation but is there maybe a nicer way, something that the Kotlin Gradle plugin offers, maybe?Didier Villevalois
06/16/2025, 12:09 PMsvenjacobs
06/16/2025, 12:10 PMsvenjacobs
06/16/2025, 12:11 PMAdam S
06/16/2025, 8:17 PMVampire
06/17/2025, 12:29 AMI think this is the one (excellent) Gradle plugin that everyone is using for that task
Definitely not. I only know very few people using it. I usually just use existing things, no extra plugins, no extra tasks. Just a
foo.properties
file in the normal resources directory with placeholders,
configuring the processResources
task with filesMatching
, expand
(or any other filter), and filteringCharset
to fill in the placeholders,
and then reading the file from classpath at runtime.Didier Villevalois
06/17/2025, 6:46 AMsvenjacobs
06/17/2025, 8:36 AMand then reading the file from classpath at runtime.I would actually prefer a compiled file to not introduce any (performance) overhead here for reading a file.
I would like to see how that goes in Kotlin multiplatformThat's a very good point because I actually need a solution for KMP. Reading via classpath probably only works for Android & JVM targets at the moment.
Rob Elliot
06/18/2025, 10:10 AMval templateKotlin by tasks.registering(Sync::class) {
from(layout.projectDirectory.dir("src/main/kotlin-templates"))
into(layout.buildDirectory.dir("generated/src/from-templates"))
filteringCharset = "UTF-8"
expand(
"VERSION" to (System.getenv("VERSION") ?: ""),
)
}
sourceSets {
main {
kotlin.srcDir(templateKotlin)
}
}
Where src/main/kotlin-templates
contains a single file `Version.kt`:
package my.app
val version = VersionInfo(
version = "${VERSION}".takeUnless { it.isEmpty() },
)
my.app.VersionInfo
being a data class in `src/main/kotlin`:
package my.app
data class VersionInfo(
val version: String?,
)
Then we just use my.app.version
directly in code.Vampire
06/18/2025, 8:33 PMidea-ext
Gradle plugin, ...
But besides that, generating code should also be fine if living with the drawbacks is fine, especially when you maybe anyway also generate other code.Rob Elliot
06/19/2025, 8:30 AMsvenjacobs
06/19/2025, 8:43 AMyou need to ensure to generate the code before trying to use IDE on the project, for example using idea-ext Gradle plugin, ...
This is what the buildconfig plugin ensures, for example.
Rob Elliot
06/19/2025, 9:41 AMVampire
06/19/2025, 11:55 AMRob Elliot
06/19/2025, 12:45 PMRob Elliot
06/19/2025, 12:46 PMVampire
06/20/2025, 2:46 AM