One of the great things of Gradle is that the build scripts are code. We can use all the features of the Groovy language, we can refactor our build scripts to make them more maintainable, we can use variables and properties to define values and much more, just like our application code. In this post we see how we can create a class to define a version in our build script. To set the version of a Gradle project we only have to assign a value to the version property. Normally we use a String value, but we can also assign an object. Gradle will use the toString() method of the object to get the String value for a version. In the following build script we define a new class Version in our build script. We create an instance of the class and assign it to the version property. With the task printVersion we can see the value of the version property:

version = new Version(major: 2, minor: 1, revision: 14)

task printVersion {
    doFirst {
        println "Project version is $version"
    }
}

defaultTasks 'printVersion'

class Version {
    int major, minor, revision

    String toString() {
        "$major.$minor.$revision"
    }
}

When we execute the task from the command-line we see the following output:

$ gradle -q printVersion
Project version is 2.1.14

We can even extend the class definition and include a boolean property release. If the value is true the version stays the same, but if it is false the String value -SNAPHSOT is appended to the version. In the following example build file we check if a release task is part of the Gradle build execution and if so the release property of the Version object is set to true:

version = new Version(major: 2, minor: 1, revision: 14)

gradle.taskGraph.whenReady { taskGraph ->
    // Set version as release version
    // when release task is to be executed.
    version.release = taskGraph.hasTask(release)
}

task printVersion {
    doFirst {
        println "Project version is $version"
    }
}

task release {
    doFirst {
        println "Releasing application $version"
    }
}

defaultTasks 'printVersion'

class Version {
    int major, minor, revision
    boolean release

    String toString() {
        "$major.$minor.$revision${release ? '' : '-SNAPSHOT'}"
    }
}

When we invoke the release and printVersion tasks together or just the printVersion task we get the following output:

$ gradle -q printVersion release
Project version is 2.1.14
Releasing application 2.1.14
$ gradle -q
Project version is 2.1.14-SNAPSHOT

Original article

shadow-left