Search code examples
antant-contrib

Call a <macrodef> for each <pathelement> in a <path> in Ant


I have a path as follows:

<path refid="myjarlocation"/>

Now I want to iterate over this path and for each value present in the path I want to call a macrodef with that value as one of the property to be used inside the marcodef.

In case of target we can easily do it as follows:

<foreach target="mytarget" param="jarloc">
    <path refid="myjarlocation"/>
</foreach>

I cannot use for each because I need to pass multiple parameters , so I am using macrodef. So, therefore the question how to iterate over a path and call a macrodef instead of a target.


Solution

  • I've made something similar work by using ant-contrib's for task to iterate a path and passing the path element along to a macrodef.

    First get ant-contrib in your project - see http://ant-contrib.sourceforge.net/

    Next, define your macrodef in your ant build however you want including some attribute that will take your path element. eg:

    <macrodef name="awesome-macro">
        <attribute name="path-to-deal-with"/>
        <attribute name="unrelated-attribute"/>
        <sequential>
            ...
        </sequential>
    </macrodef>
    

    Then, use the for task to iterate the path into pathelements and invoke the macro:

    <for param="path.element">
        <fileset dir="${jars.dir}">
            <include name="*.jar"/>
        </fileset>
        <sequential>
            <awesome-macro path-to-deal-with="@{path.element}" unrelated-attribute="whatever"/>
        </sequential>
    </for>
    

    Note the use of @{path.element} as opposed to ${path.element} inside the for loop to refer to the looping parameter!