如何根据环境变量的值执行ant目标?

时间:2018-10-12 13:32:42

标签: if-statement ant environment-variables target

我想在两台不同的计算机上执行一个蚂蚁脚本。根据计算机的名称,应执行两个目标之一。以下操作无效:

<project name="import" default="all">
  <property environment="env"/>    
  <target name="staging" if="${env.COMPUTERNAME}='STG'">
    <echo>executed on staging</echo>
  </target>      
  <target name="production" if="${env.COMPUTERNAME}='PRD'">
    <echo>executed on production</echo>
  </target>      
  <target name="all" depends="staging,production" description="STG or PRD"/>
</project>

据我了解,“ if”只能与属性一起使用,它会检查是否设置了属性。但是,有没有一种方法可以根据属性的值来建立条件?

1 个答案:

答案 0 :(得分:0)

我建议编写一个“ init”目标,该目标设置了以后构建步骤所需的任何条件,并且如果某些必需的属性未达到预期的效果,也将使构建失败。

例如:

<target name="all" depends="staging,production,init" />

<target name="staging" if="staging.environment" depends="init">
    <echo message="executed on staging" />
</target>

<target name="production" if="production.environment" depends="init">
    <echo message="executed on production" />
</target>

<target name="init">
    <condition property="staging.environment">
        <equals arg1="${env.COMPUTERNAME}" arg2="STG" />
    </condition>

    <condition property="production.environment">
        <equals arg1="${env.COMPUTERNAME}" arg2="PRD" />
    </condition>

    <fail message="Neither staging nor production environment detected">
        <condition>
            <not>
                <or>
                    <isset property="staging.environment" />
                    <isset property="production.environment" />
                </or>
            </not>
        </condition>
    </fail>
</target>