Passing variables from one task to another


(Joe Singray) #1

Hello community,

I’m having the following structure in build.gradle:

def var1
def var2
  task t << {
    //task logic
    var1 = ...
    var2 = ...
    //more task logic
}
  task t2 << {
    //do stuff with var1 and var2
}

The problem is, when I call var1 and/or var2 in t2 (which depends on t1), they do not seem to have the value which was assigned to them in t1. How can I solve this? I would like to avoid using an external file (f.e. gradle.properties).

Thanks for your help!

~ Joe


(Luke Daley) #2

You need to make ‘t2’ depend on ‘t1’.


(Joe Singray) #3

As stated in the original question, that’s already the case.


(René Groeschke) #4

how do you reference var1 and var2 from t2?


(Joe Singray) #5

@Rene: Below is the code snippet from the original question in a little more detail, to answer your question.

def var1
def var2 = new Date(Long.MIN_VALUE)
task t1 << {
    //unimportant task logic...
    if(...){
        var1 = someValue;
        var2 = someOtherValue;
    }
    //more unimportant task logic...
}
  task t2(type: Copy) {
    println 'var1: ' + var1 + " var2: " + var2
    File f = new File(var1.path)
    f = f.listFiles().first()
          from file(f)
    into file(dir) //dir is a property being read from the gradle.properties file
      rename { String fileName ->
        return removeTimeStamp(fileName)
    }
}

The println statement in t2 displays the following:

var1: null var2: Sun Dec 02 17:47:04 CET 292269055

If I’m correct, this means the variable values are not changed (or the changes are undone after the task is being completed).

Reminder: t2 still depends on t1.

EDIT: I have already tried to remove the “def” declaration (to widen the scope?), with no result.

Regards,

~ Joe


(René Groeschke) #6

the problem is, that the configuration closure of t2 is executed before the task action of t1 is executed. Have a look at the build phases chapter of the gradle userguide for more information about this: http://www.gradle.org/docs/current/userguide/build_lifecycle.html#sec:build_phases

hope that helps, cheers, René


(Joe Singray) #7

I forgot about the phases! I didn’t notice one of both was being executed on config phase, while the other was being executed at execute phase.

This perfectly solves my problem.

Thank you very much!

Regards,

~ Joe