【发布时间】:2016-01-30 21:24:42
【问题描述】:
如果给定版本(带点)大于另一个版本,我需要一种调用 Ant 目标的方法。我在 ant-contrib 中发现了greaterThan,但我认为它只使用直接字符串比较,除非字符串完全是数字。例如,我需要“8.2.10”之类的大于“8.2.2”的东西来评估为真。 ant-contrib 中有什么我可以使用的吗,或者有没有人编写过自定义脚本来执行此操作?
【问题讨论】:
标签: ant ant-contrib
如果给定版本(带点)大于另一个版本,我需要一种调用 Ant 目标的方法。我在 ant-contrib 中发现了greaterThan,但我认为它只使用直接字符串比较,除非字符串完全是数字。例如,我需要“8.2.10”之类的大于“8.2.2”的东西来评估为真。 ant-contrib 中有什么我可以使用的吗,或者有没有人编写过自定义脚本来执行此操作?
【问题讨论】:
标签: ant ant-contrib
<?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>
【讨论】:
相当老的帖子,但有使用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>
【讨论】: