Autoincrement version number on Gradle

I have just started working with a Gradle project, that needs a simple way of incrementing its version. And I came up with a simple solution.

Project’s version is following the standard: major.minor.patch. So, first of all create a version.properties file that looks like this:

MAJOR=0
MINOR=1
PATCH=0
VERSION_BUILD=0.1.0

And then add the following configuration to build.gradle:

// This block must be before version
ext {
    externalProjectVersion = { gradle.taskGraph.afterTask {readVersion} }
}

group = 'info.ernestas'
version = project.externalProjectVersion // Replace original version with property

// ...
task increaseMinor {
    doLast {
        def versionPropsFile = file('version.properties')

        if (versionPropsFile.canRead()) {
            Properties versionProps = new Properties()
            versionProps.load(new FileInputStream(versionPropsFile))
            def major = versionProps['MAJOR'].toInteger()
            def minor = versionProps['MINOR'].toInteger() + 1
            def patch = versionProps['PATCH'].toInteger()
            versionProps['MINOR'] = minor.toString()

            def version = String.format("%d.%d.%d", major, minor, patch)
            versionProps['VERSION_BUILD'] = version
            versionProps.store(versionPropsFile.newWriter(), null)
            project.externalProjectVersion = version
        } else {
            throw new GradleException("Could not read version.properties!")
        }
    }
}

task readVersion {
    def versionPropsFile = file('version.properties')

    if (versionPropsFile.canRead()) {
        Properties versionProps = new Properties()
        versionProps.load(new FileInputStream(versionPropsFile))
        return versionProps['VERSION_BUILD']
    } else {
        throw new GradleException("Could not read version.properties!")
    }
}

So, every time you want to increase minor version, simply execute: ./gradlew increaseMinorversion.properties file will be automatically regenerated.

Be First to Comment

Leave a Reply

Your email address will not be published.