Optional Ant arg

2019-03-28 07:05发布

问题:

I would like to have an ant arg value optionally included without having to make 2 targets which would be basically the same except for the extra arg. For example:

<target name="A" depends="C">...</target>

<target name="B" depends="C">...</target>

<target name="C">
    <java fork="true" ...>
        <jvmarg .../>
        <arg .../>
        <arg .../>
        ...
        # now, if the dependency is from A, no more args
        # if from B
            <arg value="xxx"/>
    </java>
</target>

回答1:

Rather than depending on task C, you could use the Antcall task to pass the B argument as a param.

<target name="A" >
  <antcall target="C" />
  ....
</target>

<target name="B" >
  <antcall target="C" >
    <param name="extra_arg" value="xxx" />
  </antcall>
  ...
</target>

<target name="C">
    <java fork="true" ...>
        <jvmarg .../>
        <arg .../>
        <arg .../>
        <arg value="${extra_arg}"/>
    </java>
</target>

EDIT: As Nico points out in the comment, this doesn't work if the value is unset from A. The answer can be extended to use the condition task to set the argument to a null string.

<condition property="argToUseIfFromB" else="">
  <isset property="extra_arg" />      
</condition>
<java fork="true" ...>
    <jvmarg .../>
    <arg .../>
    <arg .../>
    <arg value="${argToUseIfFromB}"/>
</java>

FURTHER EDIT: Since we can't get the arguments to be recognised as optional, we can pass in the whole command line from each parent task. Target A would only pass the common arguments; B would pass through an extra argument. The Ant manual on arguments explains it better than me.

<target name="A" >
  <antcall target="C">
    <param name="java_args" value="arg_a arg_b" /> 
  </antcall>
  ....
</target>

<target name="B" >
  <antcall target="C" >
    <param name="java_args" value="arg_a arg_b extra_arg" />
  </antcall>
  ...
</target>

<target name="C">
    <java fork="true" ...>
        <jvmarg .../>
        <arg line="${java_args}"/>
    </java>
</target>