How to share a global variable in a splitted gradle script

Given this minimal example:

File build.gradle

apply from: 'foo.gradle'    
def tmp = [ 1, 2, 3 ]

File foo.gradle

task myTask {
            tmp.each { item ->
                    println(item)
            }
}

When I run gradle myTask the variable tmp can not be accessed. I tried to put it in and read from project.ext. I also tried to put the variable within buildscript { } because I read that this part is executed first because it sets the classpath for the execution or something like this.

I learnt that apply from: ‘foo.bar’ is not like including the text in there. Each seems to exist in its own variable scope.

My questions:

  1. What is the reason that I cannot access the variable within the task defined in foo.gradle?
  2. Is there a way to achive what I try here? To split a build.gradle in several files that exist in the same variable scope.

Hey,

each script plugin has it’s variable scope and even its own
classloader. What you can do is to assign that variable as a project
extension:

File build.gradle

apply from: 'scriptplugin.gradle'

ext.tmp = [ 1, 2, 3 ]

File foo.gradle

task myTask {
    doLast {
    tmp.each { item ->
        println(item)
}
}

the ordering plays a role here. if you want to use the tmp field in the
script plugin during configuration phase, you need to ensure the
extension is already added.

Thanks a lot for that hint! I tried to put it in ext, but was not aware to work with the variable in doLast do make sure it has been assigned.

Is there a more detailed documentation about the build and execution phases? In special what task parts are run in what phase?

I found:
https://gradle.org/docs/current/userguide/build_lifecycle.html

But this is a very short explaination, and if possible I don’t want to extract this infos from gradle source codes.

Edit: Found this link http://stackoverflow.com/questions/24638691/when-gradles-hooks-are-added-in-build-lifecycle. Are any other resources known?

You might want to have a look at the free available book “building & testing with gradle”. It is available here https://gradle.org/books/ and it is really a good and comprehensive introduction to gradle.