2012-08-07 42 views
10

我只使用apache-ant基于变量的值EXEC任务不ant-contrib参数传递给Apache的蚂蚁

我有一个ant目标

<target name="stop" depends="init" > 
... 
</target> 

中,我想调用exec任务。

如果一个变量HOST_NAMEall

<exec executable="${executeSSH.shell}" > 
    <arg value="-h ${HOST_NAME}" /> 
    <arg value="-i ${INSTANCE}" /> 
    <arg value="-w 10" /> 
    <arg value="-e ${myOperation.shell} " /> 
    <arg value=" -- " /> 
    <arg value="${INSTANCE} ${USERNAME} ${PASSWORD}" /> 
</exec> 

如果一个变量HOST_NAMEanything else

<exec executable="${executeSSH.shell}"> 
    <arg value="-h ${HOST_NAME}" /> 
    <arg value="-i ${INSTANCE}" /> 
    <arg value="-e ${myOperation.shell} " /> 
    <arg value=" -- " /> 
    <arg value="${INSTANCE} ${USERNAME} ${PASSWORD}" /> 
</exec> 

但我想只写一个任务,而不是重复exec。我已经使用HOST_NAME参数,但是如何处理第二个参数-w 10,这两个参数在两个调用中都不相同。

我尝试了几种方法,通过使用conditionif else来搜索SO,但似乎没有什么适用于execarg

回答

6

尝试使用macrodef。以下示例未经测试。

<macrodef name="callSSH"> 
    <element name="extArgs" optional="y"/> 
    <sequential> 
     <exec executable="${executeSSH.shell}" > 
      <arg value="-h ${HOST_NAME}" /> 
      <arg value="-i ${INSTANCE}" /> 
      <extArgs/> 
      <arg value="-e ${myOperation.shell} " /> 
      <arg value=" -- " /> 
      <arg value="${INSTANCE} ${USERNAME} ${PASSWORD}" /> 
     </exec> 
    </sequential> 
</macrodef> 
<target name="stop" depends="init" > 
    <if> 
     <equals arg1="${HOST_NAME}" arg2="all"/> 
     <then> 
      <callSSH> 
       <extArgs> 
        <arg value="-w 10" /> 
       </extArgs> 
      </callSSH> 
     </then> 
     <else> 
      <callSSH> 
       <extArgs/> 
      </callSSH> 
     </else> 
    </if> 
</target> 

或者,如果你不使用贡献:

<target name="sshExecWithHost" if="HOST_NAME"> 
    <callSSH> 
     <extArgs> 
      <arg value="-w 10" /> 
     </extArgs> 
    </callSSH> 
</target> 

<target name="sshExecNoHost" unless="HOST_NAME"> 
    <callSSH/> 
</target> 

<target name="sshSwitch" depends="sshExecNoHost,sshExecWithHost"> 
</target> 

<target name="stop" depends="init,sshSwitch" > 
</target> 
10

您可以使用条件任务:

<condition property="my.optional.arg" value="-w 10" else=""> 
    <equals arg1="${HOST_NAME}" arg2="all" /> 
</condition> 

<exec executable="${executeSSH.shell}" > 
    <arg value="-h ${HOST_NAME}" /> 
    <arg value="-i ${INSTANCE}" /> 
    <arg line="${my.optional.arg}" /> 
    <arg value="-e ${myOperation.shell} " /> 
    <arg value=" -- " /> 
    <arg value="${INSTANCE} ${USERNAME} ${PASSWORD}" /> 
</exec> 
+2

非常有益的,尝试了一千种不同的变化,这是最后做了什么诀窍。 – 2014-04-07 22:55:56

+0

这是伟大而紧凑的。我用它来根据构建参数有条件地生成代码覆盖率报告。 – 2014-08-27 19:42:23