Automatic Versioning

Hi all,

I’m quite new to Gradle and I’m trying to write a task which will read my version number from a file, increment it, and write it to the same file (not sure if this is the best approach, I’m happy to listen to advice on this too).

def versionFile = new File("src/main/java/version.txt")
        if(versionFile.canRead()) {
            String versionNumber = new File("src/main/java/version.txt").text
            def (major, minor, patch) = versionNumber.tokenize('.')
            println major + "|" + minor + "|" + patch
            def temp = major.toInteger() + 1
            versionNumber = "${temp}.${minor}.${patch}"
            println versionNumber
        }
        else {
           throw new GradleException("Can not read file.")
        }

That’s what I have so far but I haven’t had any luck putting the versionNumber back in.

Edit:So I also found the <<
so for example just after "println versionNumber"
putting versionFile << versionNumber will append the file but I need something which will OVERWRITE the file.

Thanks for reading!

Here’s an example:

task incVersion {
    ext {
        versionFile = file( 'src/main/java/version.txt' )
    }
    doLast {
        if( versionFile.canRead() ) {
            String versionNumber
            // Assuming version is only ever on the first line.
            // (did this to make sure blank lines aren't accumulated, could strip them some other way if you want)
            versionFile.withReader { reader ->
                versionNumber = reader.readLine()
            }
            def (major, minor, patch) = versionNumber.tokenize('.')
            println major + "|" + minor + "|" + patch
            def temp = major.toInteger() + 1
            versionNumber = "${temp}.${minor}.${patch}"
            println versionNumber
            versionFile.withWriter { writer ->
                writer.println versionNumber
            }
        } else {
           throw new GradleException( 'Can not read file.' )
        }
    }
}

Some references:
https://docs.gradle.org/current/dsl/org.gradle.api.Project.html#org.gradle.api.Project:file(java.lang.Object)
http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/File.html#withReader(groovy.lang.Closure)
http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/File.html#withWriter(groovy.lang.Closure)

Magnificent, this is exactly what I was hoping for.

Thanks Chris!