Search code examples
antfor-loopbuildant-contrib

how to call multiple ant targets for foreach


here is what am trying to do, I want to replace name and address from my large number of property files during build, but unfortunately I cant do this, is there a better way of doing this without having to copy paste the foreach twice. can someone help?

<target name="replace" >
<foreach target="replace.name,replace.address" param="foreach.file" inheritall="true">
    <path>
                <fileset dir="${build.tmp.dir}/resource">
                <!-- some complicated conditions go here -->
    </path>
</foreach>
</target>

<target name="replace.address">
    <echo>replacing #Address# for ${foreach.file}</echo>
    <replace file="${foreach.file}" token="#Address#" value="${address}" />
</target>

<target name="replace.name">
    <echo>replacing #Name# for ${foreach.file}</echo>
    <replace file="${foreach.file}" token="#Name#" value="${Name}" />
</target>

.properties file looks like

name=#Name#
address=#Address#

Solution

  • target of foreach is not designed to take more than one target name. It only iterates through the provided list, not the provided targets.

    To make the implementation more DRY, you may

    • use a for loop instead of foreach with two antcalls;
    • use macrodef with for loop -- macrodef can pack several ant xml code into a task-like thing

    Actually, for the two targets -- replace.address and replace.name, are you sure that you want to call them from the commandline? If not, name them -replace.address and -replace.name or use macrodef -- exposing the iteration body of foreach is not a good practice.