October 15, 2010

Gradle Goodness: Custom Version Object

The project version in a Gradle project is not limited to a String value, but can be any Object. We must implement the toString() method of the object so Gradle can use it for example in naming JAR files.

In the following build script we define a custom Version class. We create an instance of the Version class and assign it to the project version. In the task listJars we print out the project version and the name of the generated JAR file, which should contain our custom version number.

apply plugin: 'java'

version = new Version(major: 2, minor: 3, releaseType: 'beta', bugfix: 2)

task listJars << {
    println "Project version: $project.version"
    configurations.archives.allArtifactFiles.files.each {
        println "Artifact: $it.name"
listJars.dependsOn 'assemble'

class Version {
    int major
    int minor
    int bugfix
    String releaseType
    String toString() {
        "$major.$minor-$releaseType${bugfix ?: ''}"

We can run our script and get the following output:

$ gradle -q listJars
Project version: 2.3-beta2
Artifact: gradle-2.3-beta2.jar