I have a webservice coded in kotlin and managed by gradle for the build/dependencies etc...
I want to do a simple thing: When someone call the version
REST endpoint of my webservice, it returns the version.
Since gradle already handle the version with the version
properties in build.gradle
, I thought it would be easy to get this value but it seems it is not... I've been searching google for hours and everything seems so complicated.
Any idea how to handle the version the good way?
Here is what I have right now:
build.gradle
version = "1.0.0"
...
StatusService.kt
class StatusService : IStatusService {
//TODO: Here I would like to get the version from the gradle
//file instead of maintaining 2 places for the version
//Something like Gradle.getProperties("version") for example
override fun getVersion() : String = "1.0.0"
}
I may be completely wrong about this so if you have another equivalent solution, I will accept it too! Thanks
One approach to this is to output a version file as part of your Gradle build to a location in your classpath that is accessible as a resource within your application.
For example:
You can add this to your build.gradle file which will generate a properties file containing the project version number and add it to your applications source set so that it is available in the classpath.
def generatedVersionDir = "${buildDir}/generated-version"
sourceSets {
main {
output.dir(generatedVersionDir, builtBy: 'generateVersionProperties')
}
}
task generateVersionProperties {
doLast {
def propertiesFile = file "$generatedVersionDir/version.properties"
propertiesFile.parentFile.mkdirs()
def properties = new Properties()
properties.setProperty("version", rootProject.version.toString())
propertiesFile.withWriter { properties.store(it, null) }
}
}
processResources.dependsOn generateVersionProperties
Then in your code you will be able to access it by reading in the properties file:
class StatusService : IStatusService {
private val versionProperties = Properties()
init {
versionProperties.load(this.javaClass.getResourceAsStream("/version.properties"))
}
override fun getVersion() : String = versionProperties.getProperty("version") ?: "no version"
}
Of course you might find it simpler and more appropriate to just output a String to the version file, and then read in the entire file as a String in your code instead of using a properties file.