Variables from properties file in Ant

2020-03-30 09:57发布

问题:

I have an Android app that needs to be built for different environments (e.g., UAT, staging, production, etc.). Each environment needs different properties (e.g., URLs, packages, etc.).

I would like to put all the different parameters into a single properties file and prefix each parameter with the environment it matches to.

For example, the properties file will contain dev.home-url = http://home_dev.com for the development environment and prod.home-url = http://home.com for the production environment.

I use the below to create a property that points to the properties file with a prefix of params:

<property file="parameters.properties" prefix="params" />

And to use a property, I use:

${params.home-url}

The problem comes when I need to add the prefix of the environment to the parameter. It would end up looking like this, which obviously can't be done:

${params.${env-prefix}.home-url}

回答1:

A frequently asked question about Ant is:

How can I do something like <property name="prop" value="${${anotherprop}}"/> (double expanding the property)?

The following Ant build file was inspired by that FAQ.

parameters.properties

dev.home-url = http://home_dev.com
prod.home-url = http://home.com

build.xml

<project default="example">
    <property name="env-prefix" value="dev" />
    <property file="parameters.properties" prefix="params" />

    <macrodef name="propertycopy">
        <attribute name="name" />
        <attribute name="from" />
        <sequential>
            <property name="@{name}" value="${@{from}}" />
        </sequential>
    </macrodef>

    <target name="example">
        <propertycopy name="local.property" from="params.${env-prefix}.home-url" />
        <echo>${local.property}</echo>
    </target>
</project>

Executing the example task outputs:

Buildfile: /workspace/build.xml
example:
     [echo] http://home_dev.com
BUILD SUCCESSFUL
Total time: 405 milliseconds


标签: android ant