0

I need a way to call an Ant target if a given version (with dots) is greater than another version. I found greaterThan in ant-contrib, but I think that it only uses a straight string comparison unless the strings are completely numeric. For instance, I need something like "8.2.10" greaterThan "8.2.2" to evaluate to true. Is there anything in ant-contrib I can use, or has anyone ever written a custom script to do this?

Mark O'Connor
  • 76,015
  • 10
  • 139
  • 185
Pat
  • 1

2 Answers2

0
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project basedir="." default="test" name="test">

    <target name="script-definition">
        <scriptdef name="greater" language="javascript">
            <attribute name="v1"/>
            <attribute name="v2"/>
            <![CDATA[

            self.log("value1 = " + attributes.get("v1"));
            self.log("value2 = " + attributes.get("v2"));

            var i, l, d, s = false;

            a = attributes.get("v1").split('.');
            b = attributes.get("v2").split('.');
            l = Math.min(a.length, b.length);

            for (i=0; i<l; i++) {
                d = parseInt(a[i], 10) - parseInt(b[i], 10);
                if (d !== 0) {
                    project.setProperty("compare-result", (d > 0 ? 1 : -1));    
                    s = true;
                    break;
                }
            }

            if(!s){
                d = a.length - b.length;
                project.setProperty("compare-result", (d == 0 ? 0 : (d > 0 ? 1 : -1)));
            }

            ]]>
        </scriptdef>
    </target>

    <target name="test" depends="script-definition">
        <greater v1="8.2.2.1" v2="8.2.2.1.1.101" />
        <echo message="compare-result: ${compare-result}" />
    </target>

</project>

p.s: javascript cheated from here from Lejared's answer.

Community
  • 1
  • 1
guleryuz
  • 2,714
  • 1
  • 15
  • 19
0

Pretty old post but there is the solution using the scriptlet task :

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project basedir="." default="test" name="test">

    <scriptdef name="versioncompare" language="javascript">
        <attribute name="arg1"/>
        <attribute name="arg2"/>
        <attribute name="returnproperty"/>
        <![CDATA[
            importClass(java.lang.Double);
            var num1 = Double.parseDouble(attributes.get("arg1"));
            var num2 = Double.parseDouble(attributes.get("arg2"));
            project.setProperty(attributes.get("returnproperty"), (num1 > num2 ? 1 : (num1 < num2 ? -1 : 0)));
        ]]>
    </scriptdef>

    <target name="test">
        <versioncompare arg1="2.0" arg2="1.9" returnproperty="compareresult"/>
        <echo message="compareresult: ${compareresult}"/>
    </target>

</project>
CrazyMax
  • 781
  • 1
  • 11
  • 24