ant-contrib - if/then/else task

Francesco picture Francesco · Feb 25, 2011 · Viewed 62.6k times · Source

I am using ant, and I have a problem with if/then/else task, (ant-contrib-1.0b3.jar). I am running something that can be simplified with build.xml below.

I am expecting to obtain from 'ant -Dgiv=Luke' the message

input name: Luke
should be overwritten with John except for Mark: John

but it seems property "giv" is not overwritten inside if/then/else..

input name: Luke
should be overwritten with John except for Mark: Luke

Is it depending from the fact I am using equals task with ${giv} ? Otherwise what is wrong in my code?

build.xml CODE:

<project name="Friend" default="ifthen" basedir=".">

<property name="runningLocation" location="" />
<taskdef resource="net/sf/antcontrib/antcontrib.properties">
    <classpath>
        <pathelement location="${runningLocation}/antlib/ant-contrib-1.0b3.jar" />
    </classpath>
</taskdef>

<target name="ifthen">
<echo message="input name: ${giv}" />
<if>
    <equals arg1="${giv}" arg2="Mark" />
    <then>
    </then>
    <else>
        <property name="giv" value="John" />
    </else>
</if>
<echo message="should be overwritten with John except for Mark: ${giv}" />
</target>
</project>

Answer

р&#252;ффп picture рüффп · Feb 25, 2011

In Ant a property is always set once, after that variable is not alterable anymore.

Here follows a solution using standard Ant (without ant-contrib) which could be useful for the people who does not want an extra dependency.

<target name="test"  >
    <echo message="input name: ${param}" />

    <condition property="cond" >
        <equals arg1="${param}" arg2="Mark" />
    </condition>
</target>

<target name="init" depends="test" if="cond"> 
    <property name="param2" value="Mark" />
</target>

<target name="finalize" depends="init"> 
    <property name="param2" value="John" />
    <echo message="should be overwritten with John except for Mark: ${param2}" />
</target>