Search code examples
javabuildpropertiesantantbuilder

How to read section from .properties file in ant build?


I have .properties file with variables=values, I want to override few of them based on environment/mode (DEV, QA, PROD)

I want to read properties from file based on section. Want to read all default properties which are out of any section and some some properties should be override as per given section name which I can pass from ant script while reading properties file.

---project.properties file (can be modified)---

#default
var1=val1
url=abc.xyz
un=un_default
pwd=pwd_default

#Mode prod
[PROD]
un=un_dev
pwd=pwd_prod
[PROD.END]

#Mode dev
[DEV]
url=xyz.dev
un=un_dev
pwd=pwd_dev
[DEV.END]

#Mode qa
[QA]
un=un_qa
pwd=pwd_qa
[QA.END]

------ ant -----

<property environment="env" />
<echo>Mode : ${env.MODE} </echo>

<loadproperties srcfile="project.properties">
</loadproperties>

Now how to pass ${env.MODE} while reading the properties file so that all default and mode/section properties should load, if default is already there then should be override by value in section.


Solution

  • Ant has a "first read is the value approach", so you cannot read a defaults and then attempt to override; rather you read the specifics and then the defaults, and the defaults won't replace anything already set. There are some ways to go around this issue, but it is easier to accept the once set will not change approach.

    I am not aware of anyway to read a section of a file. Rather, the approach generally is to put each of the dev/qa/prod into separate files, and then construct the file name using the particular mode and read it in.

    Here is an example I just ripped out of one of our projects. The idea is that one can have a series of places where a value may be set, in this case allowing one to adjust based upon the username plus the host, just the user, or the defaults:

    <property environment="env" />
    <property name="env.HOSTNAME" value="${env.COMPUTERNAME}" />
    
    <property file="${user.name}-${env.HOSTNAME}-build.properties" />
    <property file="${user.name}-build.properties" />
    <property file="${basedir}/build.properties" />