4

I am using exec to invoke a command line program multiple times from an ant build.xml. This command line program takes variable number of arguments for different cases.

At the moment I am calling this external program multiple time using exec and code looks cluttered. For example:

<exec dir="./deploy_abc/bin" executable="python" failonerror="true" >
    <arg line="tests.py"/>
    <arg line="-h aaa"/>
    <arg line="-u bbb"/>
    <arg line="-p ccc"/>
</exec>

<exec dir="./deploy_abc/bin" executable="python" failonerror="true" >
    <arg line="tests.py"/>
    <arg line="-h ddd"/>
    <arg line="-u eee"/>
    <arg line="-p fff"/>
    <arg value="this is second test"/>
</exec>

<exec dir="./deploy_abc/bin" executable="python" failonerror="true" >
    <arg line="tests.py"/>
    <arg line="-u bbb"/>
    <arg line="-p ccc"/>
    <arg value="this is another test"/>
</exec>

So I am planning to refactor this build.xml file using macrodef.

My question is how to pass variable number of parameters to macrodef. As it is shown above I need to pass different arguments to the exec-ed program based on the scenario.

Exploring
  • 2,493
  • 11
  • 56
  • 97

1 Answers1

10

You can use a macrodef element to support this:

This is used to specify nested elements of the new task. The contents of the nested elements of the task instance are placed in the templated task at the tag name.

For example, you might define your macro like this:

<macrodef name="call-exec">
   <attribute name="dir"/>
   <attribute name="executable"/>
   <attribute name="failonerror"/>
   <element name="arg-elements"/>
   <sequential>
      <exec dir="@{dir}" executable="@{executable}"
                       failonerror="@{failonerrer}" >
         <arg-elements />
      </exec>
   </sequential>
</macrodef>

And call it like this:

<call-exec dir="./deploy_abc/bin" executable="python" failonerror="true" >
  <arg-elements>
    <arg line="tests.py"/>
    <arg line="-u bbb"/>
    <arg line="-p ccc"/>
    <arg value="this is another test"/>
  </arg-elements>
</call-exec>
martin clayton
  • 76,436
  • 32
  • 213
  • 198
  • Very helpful, particularly in combination with `if:true`/`unless:true` (described in [this](https://stackoverflow.com/a/18243290/6251951) answer) for scripts which need to be invoked differently by operating system. – neuralmer Jun 07 '17 at 17:55