Setting environment variables from Gradle

2019-04-06 13:32发布

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?

3条回答
Ridiculous、
2楼-- · 2019-04-06 14:04

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"
查看更多
啃猪蹄的小仙女
3楼-- · 2019-04-06 14:28

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' 
查看更多
淡お忘
4楼-- · 2019-04-06 14:28

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)
查看更多
登录 后发表回答