1

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}
creemama
  • 6,559
  • 3
  • 21
  • 26
Stimsoni
  • 3,166
  • 2
  • 29
  • 22

1 Answers1

6

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
creemama
  • 6,559
  • 3
  • 21
  • 26
  • When reading from an external properties file the echo just prints out ${params.${env-prefix}.home-url} instead of the value for that property in the file. – Stimsoni May 25 '12 at 04:39
  • I tried it also from an external properties file, and it worked. I updated my answer to reflect what I did. If the property didn't exist in the properties file, I would get `${params.dev.home-url}`. What version of Ant are you using (`${ant.version}`)? I am using 1.8.2. – creemama May 25 '12 at 04:46
  • Ah, I get the behavior you're seeing if `env-prefix` is not defined. If you're trying to execute the Ant build file from the command line, do `ant -Denv-prefix=dev`. – creemama May 25 '12 at 05:00
  • Also, if `env-prefix` is in your properties file, specify `from="params.${params.env-prefix}.home-url"`. – creemama May 25 '12 at 05:06
  • Yep looked like that did it. Thank you muchly – Stimsoni May 25 '12 at 05:07