Using task output as variable for another task in same script?

Here is section of gradle file:

task gitRevision(type: Exec) {
commandLine “git”, “log”, “-1”, “–format=’%H’”
}

task rpm(type: Rpm) {
dependsOn tasks.build, tasks.copyRpmPreInstallScriptlet, tasks.copyRpmPostInstallScriptlet, tasks.gitRevision

packageDescription “built from branch ${buildBranch} commit ${gitRevision}”

}

In my build output i get:

built from branch 3 commit task ‘:reporting:server:gitRevision’

How do i get the result (the actual hash)?

result from command line:
git log -1 --format=’%H’
b2b9bbdfc7c4bb75f601682d9c8a4d0c46918125

Thank you.

1 Like

Hi, @erichanzl

I made a sample script, but to ease the problem, I minified the problem for getting hash.

  1. take hash
  2. write hash to file

The following is my sample script.

plugins {
    id 'base'
}

ext {
    charset = 'UTF-8'
    groupName = 'sample'
}

task gitRev(type: Exec) {
    commandLine 'git', 'log', '-1', '--format=%H'
    standardOutput = new ByteArrayOutputStream()
    ext.hash = {
        standardOutput.toString(charset)
    }
}

task writeHash(dependsOn: 'gitRev', group: groupName) {
    def result = file("${buildDir}/hash.txt")
    outputs.file result
    doLast {
        if(!buildDir.exists()) {
            buildDir.mkdirs()
        }
        def hash = tasks.gitRev.hash()
        println hash
        result.write(hash, charset)
    }
}

And this is execution result.

$ gradle wH
:gitRev
:writeHash
474181e3015ed3b92e2177bb34553131b549d4fe


BUILD SUCCESSFUL

Total time: 0.885 secs
$ cat build/hash.txt 
474181e3015ed3b92e2177bb34553131b549d4fe

The point is using Exec task’s standardOutput property, and ext.hash closure. As Exec task’s ext property, more details is available at DSL guide of Exec.

2 Likes

Thank you I now have a better understanding of standard output.

So to continue to the original requirement is it now possible to use this ‘hash’ variable in the create rpm task? ie ${hash}

To use the value of another task in GString, use

"the commit is ${tasks.gitRev.hash()}"

or

def hash = tasks.gitRev.hash()
"the commit is ${hash}"
1 Like