Apache Ant – Define your custom Ant Task using MacroDef

We can define custom task in Apache Ant using the <macrodef> which makes use of the <sequential> nested task as a template.

Try the following build.xml and run ant to get a rough idea on how it works.
build.xml

<project name="Ant MarcoDef Example" default="run" basedir=".">
  <!-- Parameter as attribute -->
  <macrodef name="attr-example">
    <attribute name="who" default="mum"/>
    <sequential>
      <echo message="******************"/>
      <echo message="*  attr-example  *"/>
      <echo message="******************"/>
      <echo message="Hello @{who}!"/>
    </sequential>
  </macrodef>

  <!-- Parameter as text -->
  <macrodef name="text-example">
    <text name="who"/>
    <sequential>
      <echo message="******************"/>
      <echo message="*  text-example  *"/>
      <echo message="******************"/>
      <echo message="Hello @{who}!"/>
    </sequential>
  </macrodef>

  <!-- Parameter as element -->
  <macrodef name="element-example">
    <element name="args"/>
    <sequential>
      <echo message="*******************"/>
      <echo message="* element-example *"/>
      <echo message="*******************"/>
      <exec executable="cmd">
        <args />
      </exec>
    </sequential>
  </macrodef>

  <!-- Parameter as implicit element -->
  <macrodef name="implicit-element-example">
    <element name="args" implicit="yes"/>
    <sequential>
      <echo message="****************************"/>
      <echo message="* implicit-element-example *"/>
      <echo message="****************************"/>
      <exec executable="cmd">
        <args />
      </exec>
    </sequential>
  </macrodef>

  <!-- Run all task defined by MarcoDef above -->
  <target name="run">
    <attr-example who="Eureka!" />
    <echo message=""/>

    <text-example>World</text-example>
    <echo message=""/>

    <element-example>
      <!-- Run "ant -version" in cmd -->
      <args>
        <arg value="/c"/>
        <arg value="ant.bat"/>
        <arg value="-version"/>
      </args>
    </element-example>
    <echo message=""/>

    <implicit-element-example>
      <!-- Run "ant -version" in cmd -->
      <arg value="/c"/>
      <arg value="ant.bat"/>
      <arg value="-version"/>
    </implicit-element-example>
  </target>
</project>

 

Check it out.
ant-define-custom-task-by-marcodef
 

Done =)

Reference:

Advertisements

3 thoughts on “Apache Ant – Define your custom Ant Task using MacroDef”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s