Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ant

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

The user input value could be "test","dev" or "prod".

I also have the "doIt" target:

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

In my target, I would like to create the following if else condition for my ant script:

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

That's to check which value user has inputted from command line, then, print a message accordingly.

I know with ant-Contrib, I can write ant script with <if> <else> . But for my project, I would like to use pure Ant to implement if else condition. Probably, I should use <condition> ?? But I am not sure how to use <condition> for my logic. Could some one help me please?

like image 533
john123 Avatar asked Mar 13 '13 15:03

john123


1 Answers

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.

like image 173
pepuch Avatar answered Oct 15 '22 16:10

pepuch