Gradle: Passing variable from one task to another

crystallinity picture crystallinity · Nov 24, 2015 · Viewed 18.5k times · Source

I want to pass a variable from one task to another, in the same build.gradle file. My first gradle task pulls the last commit message, and I need this message passed to another task. The code is below. Thanks for help in advance.

task gitMsg(type:Exec){
    commandLine 'git', 'log', '-1', '--oneline'
    standardOutput = new ByteArrayOutputStream()
    doLast {
       String output = standardOutput.toString()
    }
}

I want to pass the variable 'output' into the task below.

task notifyTaskUpcoming << {
    def to = System.getProperty("to")
    def subj = System.getProperty('subj') 
    def body = "Hello... "
    sendmail(to, subj, body)
}

I want to incorporate the git message into 'body'.

Answer

Rene Groeschke picture Rene Groeschke · Nov 24, 2015

I think global properties should be avoided and gradle offers you a nice way to do so by adding properties to a task:

task task1 {
     doLast {
          task1.ext.variable = "some value"
     }
}

task task2 {
    dependsOn task1
    doLast { 
        println(task1.variable)
    }
}