Gradle task to write hg revision to file

10,175

Solution 1

There are two issues with this build script:

  1. the command line needs to be split; gradle's trying to execute a binary named hg id -i -b t instead of hg with arguments id, -i, -b and t
  2. The standard output needs to be captured; you can make it a ByteOutputStream to be read later

Try this:

task versionInfo(type:Exec){
    commandLine 'hg id -i -b -t'.split()
    ext.versionfile = new File('bin/$baseName-buildinfo.properties')
    standardOutput = new ByteArrayOutputStream()

    doLast {
        versionfile.text = 'build.revision=' + standardOutput.toString()
    }
}

Solution 2

Here I have a little bit different approach, which uses javahg to get revision. And add task "writeRevisionToFile"

I wrote brief post on my blog Gradle - Get Hg Mercurial revision.

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.aragost.javahg:javahg:0.4'
    }
}

task writeRevisionToFile << {
    new File(projectDir, "file-with-revision.txt").text = scmRevision
}


import com.aragost.javahg.Changeset
import com.aragost.javahg.Repository
import com.aragost.javahg.commands.ParentsCommand

String getHgRevision() {
    def repo = Repository.open(projectDir)
    def parentsCommand = new ParentsCommand(repo)
    List<Changeset> changesets = parentsCommand.execute()
    if (changesets == null || changesets.size() != 1) {
        def message = "Exactly one was parent expected. " + changesets
        throw new Exception(message)
    }
    return changesets[0].node
}

ext {
    scmRevision = getHgRevision()
}
Share:
10,175
cmh
Author by

cmh

Updated on June 03, 2022

Comments

  • cmh
    cmh about 2 years

    Is there a simple way to write to file the mercurial version (or similar external command) in a gradle task:

    I'm not yet groovy/gradle conversant, but my current effort looks like this:

    task versionInfo(type:Exec){
        commandLine 'hg id -i -b -t'
        ext.versionfile = new File('bin/$baseName-buildinfo.properties')
    
        doLast {
            versionfile.text = 'build.revision=' + standardOutput.toString()
        }
    }
    
  • cmh
    cmh over 11 years
    This works, thanks. There was a typo in my original hg command which you may want to note in your answer for future references. It also seems that I need versionfile, not ext.versionfile