Sergey
Sergey

Reputation: 3721

Setting environment variables from Gradle

I need to execute from Gradle an Ant script which relies on environment variables. Ant uses <property environment="env"/> for it.

I tried to do env.foo="bar" in Gradle, but it throws a Groovy exception.

What is the proper way to pass environment variables from Gradle to Ant?

Upvotes: 10

Views: 20134

Answers (3)

Hubbitus
Hubbitus

Reputation: 5349

Accepted solution from @Sergey:

ant.project.properties['env.foo'] = 'bar'

Does not work for me on gradle 2.9 and ant 1.9.7. That did not thrown any error, but do nothing. Indeed if you are look at code it implemented as:

public Hashtable<String, Object> getProperties() {
    return PropertyHelper.getPropertyHelper(this).getProperties();
}

where org.apache.tools.ant.PropertyHelper#getProperties is:

public Hashtable<String, Object> getProperties() {
    //avoid concurrent modification:
    synchronized (properties) {
        return new Hashtable<String, Object>(properties);
    }
}

So it make explicit copy and it can't work.

The way do it correctly in gradle file:

ant.project.setProperty('env.foo', 'bar')

Documentation mention few other ways (note, without project):

ant.buildDir = buildDir
ant.properties.buildDir = buildDir
ant.properties['buildDir'] = buildDir
ant.property(name: 'buildDir', location: buildDir)

Upvotes: 2

dre
dre

Reputation: 1434

From the gradle 2.0 docs, i see something like this is possible

test {
  environment "LD_LIBRARY_PATH", "lib"
}

Or in this case could use this

systemProperty "java.library.path", "lib"

Upvotes: 13

Sergey
Sergey

Reputation: 3721

It is impossible to set environment variables from Gradle or JVM in general, but it is possible to trick Ant like this:

ant.project.properties['env.foo'] = 'bar' 

Upvotes: 4

Related Questions