I added a custom property in gradle.properties
:
libraryVersion=0.1.0-beta
How do I read this in the code I'm publishing? I would like to use this value in my Kotlin library without hardcoding it.
I found the answer I was looking for after digging for a while
Here's the solution:
build.gradle.kts:
import java.io.FileOutputStream
import java.util.Properties
version = "1.0.0"
val generatedVersionDir = "$buildDir/generated-version"
sourceSets {
main {
kotlin {
output.dir(generatedVersionDir)
}
}
}
tasks.register("generateVersionProperties") {
doLast {
val propertiesFile = file("$generatedVersionDir/version.properties")
propertiesFile.parentFile.mkdirs()
val properties = Properties()
properties.setProperty("version", "$version")
val out = FileOutputStream(propertiesFile)
properties.store(out, null)
}
}
tasks.named("processResources") {
dependsOn("generateVersionProperties")
}
Library.kts:
private val versionProperties = Properties()
val version: String
get() {
return versionProperties.getProperty("version") ?: "unknown"
}
init {
val versionPropertiesFile = this.javaClass.getResourceAsStream("/version.properties")
versionProperties.load(versionPropertiesFile)
}