Setting environment variables from Gradle

2019-04-06 13:41发布

问题:

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?

回答1:

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"


回答2:

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' 


回答3:

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)