Read project version number dynamically, from a file?

We are porting another legacy system to gradle. This system is sufficiently complex that it seems like it would be easier to have the gradle build script simply execute a shell script to build the main archive, which is an rpm file. This works well enough.

But then we want to bolt on some gradle extensions for further processing.

The version number which is encoded in the RPM comes from another file. I would like to write some groovy (or java) code to read this file and pull the version number out of it and set project.version equal to this value.

Can this even be done, and when, in the evaluate/configure/run cycle should it be done?

Many projects read the version from a simple text file (including Gradle itself, but with a lot more logic on the actual version number read). It’s basically the following:

version = rootProject.file('version.txt').text.trim()

Normally this is seen just like that, in the configuration phase, but nothing would stop you from doing it only in a task that needs it so long as you have it when you need it.

Of course you can add any more complex logic you need after reading the file, if there’s some decoding to do.

Thanks. I’ve been burnt so many times by the evaluate/configure/run cycle that I wanted some reassurance before I dived in.

version does not need to be a String, it can be any class you want, as long as toString returns an appropriate version String.

For example:

class MyVersion {
    def major
    def minor
    String toString() {
        return "${major}.${minor}"

version = new MyVersion( major: 5, minor: 2 )

task doSomething {
    doLast {
        // assuming we know the version is of type MyVersion
        println "do something specific with the ${version.major} number"

You could make the class do whatever you need, perhaps its constructor reads in the details of the file.
Put that class in a plugin/buildscript classpath dependency and you can share and include it as necessary across projects.

We’re using this technique to make version numbers automatically reflect CI vs development environments as well as consume a few alternate sources of input for the base version number.

1 Like