Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to understand gradle project properties

Tags:

gradle

Clearly I don't understand what's going on here.

I guess prop2 and prop3 can't be accessed because they are variables instead of "project properties".

The question arose because I would like the variables prop2 and prop3 to be visible from within the "doTheThing()" method, but I don't want to have to pass them in. I want the variables to be globally accessible to tasks, methods and classes (but only from within in the build script itself) - and I want them to be typed (which is why the defintion of prop1 is not acceptable).

Really, though - I guess what I'm asking for is some help understanding what a Gradle project property is and what the syntax 'prop1 = "blah"' is actually doing.

I have read the Gradle user guide and also Gradle in Action - if they already explain this concept please point me to the right section (maybe I glossed over it at the time not understanding what is was saying).

prop1 = "blah"
String prop2 = "bleah"
def prop3 = "blargh"

task testPropAccess << {
  println "1: $prop1"
  println "2: $prop2"
  println "3: $prop3"
  doTheThing()
}

private void doTheThing(){
  println "4: $prop1"
  println "5: $prop2"  // error: Could not find property 'prop2' on root project 'script'
  println "6: $prop3"  // error: Could not find property 'prop3' on root project 'script'
}
like image 429
Shorn Avatar asked Oct 10 '11 07:10

Shorn


1 Answers

When you declare a variable at the outermost level (as in your second and third statement), it becomes a local variable of the script's run method. This is really just Groovy behavior, and nothing that Gradle can easily change.

If you want the equivalent of a global variable, just assign a value to an unbound variable (as in your first statement). This adds a dynamic property to Gradle's Project object, which is visible throughout the build script (unless shadowed). In other words, prop1 = "blah" is equivalent to project.prop1 = "blah".

If you want the equivalent of a typed global variable, you'll have to wait until Gradle upgrades to Groovy 1.8, which makes this possible with the @Field annotation. Or you write a plugin that mixes a convention object into the Project object (but that's not suitable for ad-hoc scripting).

like image 96
Peter Niederwieser Avatar answered Nov 23 '22 07:11

Peter Niederwieser