Wednesday, March 21, 2012

Ant practice on how to build your file with substituing the @tokens@

The usual need of a person going to build the code is to keep the certain properties in separate file and move the property values to certain files on build stage. This is what the article about. Let's look and the very small example.

Assume we have the following property file (let's name it "configuration properties")
user.role=admin
user.login=superuser
user.password=whoifnotme

and the following file we're going to build (settings.xml)
<settings>
 <users>
  <user id="@user.login@">
   <role>@user.role@</role>
   <password>@user.password@</password>
  </user>
 </users>
</settings>

Let's place the files above to d:/temp/props_src and would like to build the file settings.xml to the folder d:/temp/props_build.

Here is how the ant script should look like

<project name="testBuildCodeWithProperties" default="start" basedir=".">

 <property name="sourceDir" value="d:/temp/props_src"/>
 <property name="targetDir" value="d:/temp/props_build"/>
 
 <target name="start">
  <copy todir="${targetDir}" overwrite="true">
   <fileset dir="${sourceDir}" includes="*.xml"/>
   <filterset filtersfile="${sourceDir}/configuration.properties"/>
  </copy>
 </target>
 
</project>

Note that we should not write any specific script to substitute the values. The only inbound data we need to have to build the file is actually the template of a file to build and the property file to be used in filter set. The @ symbol is used by default to point out the tokens in the template file. However you may change it by specifying begintoken and endtoken attributes of filterset.