Gradles project model provides a consistent way of expressing a version of an artifact. The following task uses the version number and makes it accessible to application code. Furthermore it adds the number of the build given by the Jenkins CI server.
/** * Read the version number from gradle (multi-) project definition * and add the build number from Jenkins-ci if available, otherwise use "IDE" */ task injectVersion << { def lineSep = System.getProperty("line.separator", "n") def file = file("$sourceSets.main.output.resourcesDir/version.properties") file.newWriter().withWriter { w -> w << "version=" << rootProject.version << lineSep w << "buildNumber=" << (System.getenv("BUILD_NUMBER") as String ?: "IDE") << lineSep } } // the inject version task requires the output folders to be already created injectVersion.mustRunAfter processResources // the version properties file have to be added to the classpath resource classes.dependsOn injectVersion
It is worth to notice that the inject version task relies on the existence of the resource output directory from the „main“ source set. Therefore it is not allowed to run before the processResources
has been completed and it depends on the classes
task.
Someone might consider extending the processResources
task putting the version.properties
file creation into the doLast
step like:
processResources.doLast { def lineSep = System.getProperty("line.separator", "n") def file = file("$sourceSets.main.output.resourcesDir/version.properties") file.newWriter().withWriter { w -> w << "version=" << rootProject.version << lineSep w << "buildNumber=" << (System.getenv("BUILD_NUMBER") as String ?: "IDE") << lineSep } }
This works well except for changing numbers without cleaning, because gradle could not decide whether the build number has changed or is still unchanged during its configuration phase.
References
- Get the build number from Jenkins – http://blog.jensdriller.com/how-to-include-jenkins-ci-build-number-in-android-apk-name/