Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare array/hashmap in gradle.properties file

I'm trying to define an array in the gradle.properties file. When, for example, I do the next in some gradle script:

project.ext.mygroup = [
  myelement1: "myvalue1",
  myelement2: "myvalue2"
]
project.mygroup.put("myelement3", "myvalue3"); // As internally it works like a hashmap

and then I list the properties, I get:

mygroup: {myelement1=myvalue1, myelement2=myvalue2, myelement3=myvalue3}

So, if I try setting a property with the same form in the gradle.properties file:

mytestgroup={myelement1=myvalue1, myelement2=myvalue2}

And then in the gradle script I try to access this property:

project.mytestgroup.put("myelement3", "myvalue3");

I get the next error:

No signature of method: java.lang.String.put() is applicable for argument types: (java.lang.String, java.lang.String) values: [myelement3, myvalue3]

This is because the property "mytestgroup" is being taken as a string instead of an array.

Does any one know what is the correct syntax to declare an array in the gradle.properties file?

Thanks in advance

like image 752
gomerudo Avatar asked Oct 23 '14 22:10

gomerudo


People also ask

What is the use of Gradle properties file?

The gradle. properties helps with keeping properties separate from the build script and should be explored as viable option. It's a good location for placing properties that control the build environment.


3 Answers

The notation {myelement1=myvalue1, myelement2=myvalue2, myelement3=myvalue3} is simply a string representation of the object as the result of calling Map.toString(). It is not syntactically correct Groovy.

Your first example is the correct way to define a Map.

def myMap = [ key : 'value' ]

Defining an array is similar.

def myArray = [ 'val1', 'val2', 'val3' ]
like image 170
Mark Vieira Avatar answered Oct 26 '22 02:10

Mark Vieira


Set the property to JSON string

myHash = {"first": "Franklin", "last": "Yu"}
myArray = [2, 3, 5]

and parse it in build script with JsonSlurper:

def slurper = new groovy.json.JsonSlurper()
slurper.parseText(hash) // => a hashmap
slurper.parseText(array) // => an array
like image 35
Franklin Yu Avatar answered Oct 26 '22 01:10

Franklin Yu


The JsonSlurper way is good, but I wanted a cleaner way to define both a simple string or an array as a property. I solved it by declaring the property as:

mygroup=myvalue1

or:

mygroup=myvalue1,myvalue2,myvalue3

Then inside Gradle retrieve the property with:

Properties props = new Properties()
props.load(new FileInputStream(file('myproject.properties')))
props.getProperty('mygroup').split(",")

And you will get an array of String. Be careful with space characters around the commas.

like image 43
Kazikal Avatar answered Oct 26 '22 03:10

Kazikal