14

我是蚂蚁的新手。我的 ant 脚本从命令行接收名为“ env ”的用户输入变量:

例如ant doIt -Denv=test

用户输入值可以是“ test ”、“ dev ”或“ prod ”。

我也有“ doIt”目标:

<target name="doIt">
  //What to do here?
</target>

在我的目标中,我想为我的 ant 脚本创建以下if else条件:

if(env == "test")
  echo "test"
else if(env == "prod")
  echo "prod"
else if(env == "dev")
  echo "dev"
else
  echo "You have to input env"

那是检查用户从命令行输入的值,然后相应地打印一条消息。

我知道ant-Contrib,我可以用<if> <else>. 但是对于我的项目,我想使用纯Ant来实现if else条件。可能,我应该使用<condition>?? 但我不确定如何使用<condition>我的逻辑。有人可以帮我吗?

4

2 回答 2

43

您可以创建几个目标并使用if/unless标签。

<project name="if.test" default="doIt">

    <target name="doIt" depends="-doIt.init, -test, -prod, -dev, -else"></target>

    <target name="-doIt.init">
        <condition property="do.test">
            <equals arg1="${env}" arg2="test" />
        </condition>
        <condition property="do.prod">
            <equals arg1="${env}" arg2="prod" />
        </condition>
        <condition property="do.dev">
            <equals arg1="${env}" arg2="dev" />
        </condition>
        <condition property="do.else">
            <not>
                <or>
                <equals arg1="${env}" arg2="test" />
                <equals arg1="${env}" arg2="prod" />
                <equals arg1="${env}" arg2="dev" />
                </or>
            </not>
        </condition>
    </target>

    <target name="-test" if="do.test">
        <echo>this target will be called only when property $${do.test} is set</echo>
    </target>

    <target name="-prod" if="do.prod">
        <echo>this target will be called only when property $${do.prod} is set</echo>
    </target>

    <target name="-dev" if="do.dev">
        <echo>this target will be called only when property $${do.dev} is set</echo>
    </target>

    <target name="-else" if="do.else">
        <echo>this target will be called only when property $${env} does not equal test/prod/dev</echo>
    </target>

</project>

带有-前缀的目标是私有的,因此用户将无法从命令行运行它们。

于 2013-03-13T16:10:06.497 回答
1

如果你们中的任何人需要一个简单的if/else条件(没有 elseif);然后使用以下内容:

这里我依赖于一个环境变量 DMAPM_BUILD_VER,但是有可能这个变量没有在环境中设置。所以我需要有机制默认为本地值。

    <!-- Read build.version value from env variable DMAPM_BUILD_VER. If it is not set, take default.build.version. -->
    <property name="default.build.version" value="0.1.0.0" />
    <condition property="build.version" value="${env.DMAPM_BUILD_VER}" else="${default.build.version}">
        <isset property="env.DMAPM_BUILD_VER"/>
    </condition>
于 2015-04-21T08:46:36.700 回答