Search code examples
javagradlegroovybuild

How to share parameters between different gradle tasks


Let's say I have two gradle tasks: foo and beforeFoo.

Not a surprise - beforeFoo action must be done before foo and I have this:

task foo << {
    dependsOn 'beforeFoo'
}

Than I started to feel that my beforeFoo should get some information which is visible for foo and isn't for beforeFoo and I need to pass it somehow. Tasks defined in separated .gradle files which are linked together by root build.gradle by apply from expression.

What I've already tried:

1

foo and beforeFoo defined in different .gradle files and non of them is root, so it's not possible to reuse project.ext.myInformation between tasks

2

to make 'beforeFoo' a class extended of DefaultTask and create something like

task `beforeFoo` (type: BeforeFooClass){
   myInfo='info'
}

no way, BeforeFooClass is not visible if it's defined somewhere not in current .gradle file

Can't believe I cannot easily specify arguement for a.dependsOn b expression. I would be so happy if get help.


Solution

  • I may not understand the question, but given build.gradle:

    apply from: 'before.foo.gradle'
    apply from: 'foo.gradle'
    

    and before.foo.gradle:

    task beforeFoo() << {
        println "executing beforeFoo"
        println "value is: " + project.ext.value
    }
    

    and foo.gradle (with separate code for 'configuration' phase and 'execution' phase):

    task foo(dependsOn: "beforeFoo") {
        println "configuring foo"
        project.ext.value = "is set by foo"
    }
    
    foo << {
        println "executing foo"
    }
    

    Observe this result:

    bash$ gradle foo
    configuring foo
    :beforeFoo
    executing beforeFoo
    value is: is set by foo
    :foo
    executing foo
    

    That is, given the Gradle lifecycle (init phase, config phase, execution phase):

    • foo sets the value in the configuration phase
    • beforeFoo reports the value in the execution phase
    • foo prints text in execution phase