Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing all tokens based on properties file with ANT

Tags:

tokenize

ant

I'm pretty sure this is a simple question to answer and ive seen it asked before just no solid answers.

I have several properties files that are used for different environments, i.e xxxx-dev, xxxx-test, xxxx-live

The properties files contain something like:

server.name=dummy_server_name
server.ip=127.0.0.1

The template files im using look something like:

<...>
   <server name="@server.name@" ip="@server.ip@"/>
</...>

The above is a really primitive example, but im wondering if there is a way to just tell ANT to replace all tokens based on the properties file, rather than having to hardcode a token line for each... i.e

<replacetokens>
   <token key="server.name" value="${server.name}"/>
   <token key="server.ip" value="${server.ip}"/>
</replacetokens>

Any help would be great!

like image 845
Grofit Avatar asked Dec 22 '10 10:12

Grofit


2 Answers

You can specify the properties file from which to read the list of tokens for the 'replace' task using replacefilterfile:

<replace file="input.txt" replacefilterfile="properties.txt"/>

Similarly, in a filter chain, you can use 'replacetokens' propertyfile:

This will treat each properties file entry in sample.properties as a token/key pair:

<loadfile srcfile="${src.file}" property="${src.file.replaced}">
  <filterchain>
    <filterreader classname="org.apache.tools.ant.filters.ReplaceTokens">
      <param type="propertiesfile" value="sample.properties"/>
    </filterreader>
  </filterchain>
</loadfile>
like image 200
martin clayton Avatar answered Oct 14 '22 03:10

martin clayton


With the replace task by itself I missed the @ delimiters around tokens so I came up with the following solution. You can use any ant property in the template file

<project name="replace" default="replace">

<property file="build.properties" />
<target name="replace">

    <!-- create temp file with properties -->
    <tempfile property="temp.replace" suffix=".properties"/>
    <echoproperties destfile="${temp.replace}" />
    <!-- replace name=value with @name@=value -->
    <replaceregexp file="${temp.replace}" match="([^=]*)=" replace="@\1@=" byline="true" />

    <!-- copy template and replace properties -->
    <copy file="template.txt" tofile="replaced.txt" />
    <replace file="replaced.txt" replacefilterfile="${temp.replace}" />

</target>

with a template

ANT home @ant.home@
ANT version @ant.java.version@
server name @server.name@ ip @server.ip@

this results in

ANT home /usr/share/ant
ANT version 1.7
server name dummy_server_name ip 127.0.0.1
like image 22
carl verbiest Avatar answered Oct 14 '22 03:10

carl verbiest