转: ant condition使用

时间:2022-05-14 11:54:07

评注: 用c语言的方式来,比喻ant...比较好理解

转: http://www.smithfox.com/?e=176

[备忘] Apache Ant中的逻辑判断

[原创链接: http://www.smithfox.com/?e=176 转载请保留此声明, 谢谢!! ]

在写Ant时有时免不了要简单的逻辑, 本文并没有创造什么新的好办法, 只是着眼于将一些 "似懂非懂" 的概念理清一下.

相信第一次遇到这样的问题时, 你一定能搜索到很多的内容, 零散的concept进入了你的脑中: condition, if, else, else if, then, unless, avaliable, ant-contrib.

先不管这些, 看一段  程序员都能看懂的代码:

function test():void {
if( (a!=null && b=="hello") || ( fileExist("/good.txt") ) ) {
printf("11111");
} else {
printf("33333");
}
}

很显然上面这段代码很难直接体现在 Ant这样以XML为载体的描述式脚本中, 再改造一下:

function test():void {
var flag:Boolean = conditaion( or( and(a!=null,b=="hello"), fileExist("/good.txt") ) );
if( flag ) {
printf("11111");
} else {
printf("33333");
}
}

为什么要这样改造, 因为对应的Ant是这样写的:

<?xml version="1.0" encoding="UTF-8"?>

<project name="anttest" default="printf11111">
<!-- 这个Ant Project的默认target是printf11111, 为了使Ant能自动调用 printf33333将 printf33333 放到它的 depends -->
<target name="printf1111" depends="getflag, printf33333" if="flag">
<echo message="11111"/>
</target> <target name="printf33333" depends="getflag" unless="flag">
<echo message="33333"/>
</target> <target name="getflag">
<condition property="flag">
<or>
<and>
<isset property="a"/>
<equals arg1="${b}" arg2="hello" />
</and>
<available file="/good.txt" type="file"/>
</or>
</condition>
</target>
</project>

你肯定会有两点感受: 一是,觉得这个真的很啰嗦, 二是, 这么多的新出来的字眼, 我到哪去找呀?

好吧, 先解决第二个问题, 给几个链接:

http://ant.apache.org/manual/Tasks/conditions.html

http://ant.apache.org/manual/targets.html

再看第一个问题, 在啰嗦中找点规律:

1. Ant的逻辑分支的粒度是 target, 因为 if 和 unless(作用相当于else) 是 target的属性

2. Ant的逻辑体现在 property(相当于变量)上, 因为 if 和 unless 只接受 property

3. condition这个task, 是逻辑组合器, 它的作用相当于: var flag:Boolean = (xxx);

你会发现写一个这么简单的东东, 都要搞好几个target, 主要还是因为: "Ant的逻辑分支持粒度是 target", 在Ant中比target小的粒度是 task, 那有没有task级别的 逻辑分支呢? 这时候 ant-contrib 就华丽登场了.

其实ant-contrib 重用了 Ant的conditions(不是condition task), 而废弃了 condition 这个 task, 代之以 if, else, elseif再加then 这样的task.

用 ant-conrib的例子如下:

<?xml version="1.0" encoding="UTF-8"?>

<project name="anttest" default="print">
<property name="a" value="somevalue"/>
<property name="b" value="hello"/> <taskdef resource="net/sf/antcontrib/antlib.xml" classpath="${basedir}/ant-contrib-1.0b3.jar" /> <target name="print">
<if>
<or>
<and>
<isset property="a"/>
<equals arg1="${b}" arg2="hello" />
</and>
<available file="/good.txt" type="file"/>
</or>
<then>
<echo message="11111" />
</then>
<else>
<echo message="33333" />
</else>
</if>
</target> </project>

你会发现用ant-contrib比直接用 ant内置的简洁多了, 而且可读性也增强了. 这主要是因为, if, else 这样的逻辑分支已经是 ant task 级别了.

[原创链接: http://www.smithfox.com/?e=176 转载请保留此声明, 谢谢!! ]