Replace tokens from one file to another using Ant

2019-08-31 08:16发布

问题:

I am trying to replace few tokens from one resource bundle (.messages file) to another one using the below ant's filterchain and replacetoken.

<copy file="dev.properties" tofile="messages.properties">
    <filterchain>
    <replaceregex pattern="\$\{" replace="{" />
    <filterreader classname="org.apache.tools.ant.filters.ReplaceTokens">
            <param type="propertiesfile" value="properties.txt"/>
            <param type="tokenchar" name="begintoken" value="{"/>
            <param type="tokenchar" name="endtoken" value="}"/>
    </filterreader>
    </filterchain>
</copy>

The target runs fine but nothing gets copied. Here are my files.

dev.properties

server.name=myServerName
server.ip=127.0.0.1

messages.properties

SERVER_NAME="@server.name@"
SERVER_IP="@server.ip@"

Please note that messages.properties is what gets deployed to the server. It has other entries which are common to all the environments. I am using Jenkins to deploy the projects to diff environments. My plan is call this ANT target/task as a post deployment step, replace the environment/server specific variables as port, name etc in messages.properties and then do the build to app server using Jenkins.

回答1:

You can try this:

<project name="MyProject" default="useregex" basedir=".">
    <target name="useregex">
        <property file="dev.properties"/>
        <replace  file="messages.properties" token="@server.name@" value="${server.name}" />
        <replace  file="messages.properties" token="@server.ip@" value="${server.ip}" />
    </target>
</project>


回答2:

This is what worked for me. I was hoping for a better answer from somebody on filterchain.

  <target name="replaceLocalTokens">
    <property file="local.properties"/>
    <replace file="messages.properties" token="@build-number@" value="${build.number}"/>
    <replace file="messages.properties" token="@build-date@" value="${build.date}"/>
    <replace file="messages.properties" token="@server-name@" value="${server.name}"/>
    <replace file="messages.properties" token="@ssl-port@" value="${ssl.port}"/>
  </target>