Use pure Ant to implement if else condition (check command line input)

前端 未结 2 951
梦如初夏
梦如初夏 2020-12-14 20:24

I am a newbie in Ant. My ant script receives a user input variable named \"env\" from command line:

e.g. ant doIt -Denv=test

Th

相关标签:
2条回答
  • 2020-12-14 21:05

    You can create few targets and use if/unless tags.

    <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>
    

    Targets with - prefix are private so user won't be able to run them from command line.

    0 讨论(0)
  • 2020-12-14 21:17

    If any of you require a plain if/else condition (without elseif); then use the below:

    Here I am dependent on a env variable DMAPM_BUILD_VER, but it may happen that this variable is not set in the env. So I need to have mechanism to default to a local value.

        <!-- 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>
    
    0 讨论(0)
提交回复
热议问题