5

How can I find out which of two numeric properties is the greatest?

Here's how to check wheather two are equal:

<condition property="isEqual">
    <equals arg1="1" arg2="2"/>
</condition>
martin clayton
  • 76,436
  • 32
  • 213
  • 198
Industrial
  • 41,400
  • 69
  • 194
  • 289

3 Answers3

8

The Ant script task allows you to implement a task in a scripting language. If you have JDK 1.6 installed, Ant can execute JavaScript without needing any additional dependent libraries. For example, this JavaScript reads an Ant property value and then sets another Ant property depending on a condition:

<property name="version" value="2"/>

<target name="init">
  <script language="javascript"><![CDATA[
    var version = parseInt(project.getProperty('version'));
    project.setProperty('isGreater', version > 1);
  ]]></script>

  <echo message="${isGreater}"/>
</target>
Chin Huang
  • 12,912
  • 4
  • 46
  • 47
4

Unfortunately, Ant's built in condition task does not have an IsGreaterThan element. However, you could use the IsGreaterThan condition available in the Ant-Contrib project. Another option would be to roll out your own task for greater than comparison. I'd prefer the former, because it's easier and faster, and you also get a host of other useful tasks from Ant-Contrib.

AbdullahC
  • 6,649
  • 3
  • 27
  • 43
  • Trying to use this currently. Do you have an example of setting a property with this ? Trying to simply set a boolean property to the result of the isgreaterthan task, or use in an if task – Ro. Dec 01 '11 at 12:31
2

If you don't want to (or cannot) use the Ant-Contrib libraries, you can define a compare task using javascript:

<!-- returns the same results as Java's compareTo() method: -->
<!-- -1 if arg1 < arg2, 0 if arg1 = arg2, 1 if arg1 > arg2 -->
<scriptdef language="javascript" name="compare">
    <attribute name="arg1" />
    <attribute name="arg2" />
    <attribute name="result" />
    <![CDATA[
    var val1 = parseInt(attributes.get("arg1"));
    var val2 = parseInt(attributes.get("arg2"));
    var result = (val1 > val2 ? 1 : (val1 < val2 ? -1 : 0));
    project.setProperty(attributes.get("result"), result);
    ]]>
</scriptdef>

You can use it like this:

<property name="myproperty" value="20" />
...
<local name="compareResult" />
<compare arg1="${myproperty}" arg2="19" result="compareResult" />
<fail message="myproperty (${myproperty}) is greater than 19!">
    <condition>
        <equals arg1="${compareResult}" arg2="1" />
    </condition>
</fail>
user3151902
  • 3,154
  • 1
  • 19
  • 32