来自ant manual:
从 Ant 1.9.1 开始,可以在所有属性上添加 if 和 unless 属性
使用特殊命名空间的任务和嵌套元素。
直到现在还没有在宏定义中使用新的 if 和 unless 属性,但以下 sn-p 有效:
<project xmlns:if="ant:if" xmlns:unless="ant:unless">
<property name="foo" value="true"/>
<macrodef name="foobar">
<attribute name="bla"/>
<attribute name="whentrue"/>
<sequential>
<echo if:true="${@{whentrue}}">@{bla}</echo>
</sequential>
</macrodef>
<echo>${ant.version}</echo>
<foobar whentrue="foo" bla="yada,yada"/>
</project>
注意 => 属性语法<echo if:true="${@{whentrue}}">,仅在使用@{whentrue} 时不起作用。
输出:
[echo] Apache Ant(TM) version 1.9.1 compiled on May 15 2013
[echo] yada,yada
我的另一个尝试:
<macrodef name="foobar" if:true="foo">
<attribute name="bla"/>
<sequential>
<echo>@{bla}</echo>
</sequential>
</macrodef>
<echo>${ant.version}</echo>
<foobar bla="yada,yada"/>
没用:
... Problem: failed to create task or type foobar
Cause: The name is undefined.
Action: Check the spelling.
Action: Check that any custom tasks/types have been declared.
Action: Check that any <presetdef>/<macrodef> declarations have taken place.
还假设像 <foobar bla="yada,yada" if:true="foo"/> 这样的东西会起作用:
<project xmlns:if="ant:if" xmlns:unless="ant:unless">
<property name="foo" value="true"/>
<macrodef name="foobar">
<attribute name="bla"/>
<sequential>
<echo>@{bla}</echo>
</sequential>
</macrodef>
<echo>${ant.version}</echo>
<foobar bla="yada,yada" if:true="foo"/>
</project>
输出,没有错误但没有执行宏定义:
[echo] Apache Ant(TM) version 1.9.1 compiled on May 15 2013
BUILD SUCCESSFUL
似乎该区域仍有一些不一致之处,因为此功能是全新的。
也许我们应该提交一个错误!?
-- 编辑 (1) --
刚刚在 ant bug 数据库中找到了一个comment from 2007 by Peter Reilly(他实现了 if / unless 功能),提供了一个带有宏定义的 sn-p。
-- 编辑 (2) --
尽管 2013 年 12 月 29 日发布的新 Ant 1.9.3 (see releasenotes here) 修复了与新 if: and unless: 属性 (https://issues.apache.org/bugzilla/show_bug.cgi?id=55885) 相关的错误,但我们的问题仍然存在。因此我打开了一个错误报告,请参阅 ant 错误数据库 bugid 55971。
-- 编辑 (3) --
终于找到了解决办法。除了Bugid 55885 的错误修复,Ant Release 1.9.3 还为新的 if: and unless: attributes => Bugid 55359 的文档提供了错误修复,表明必须使用 if:true="${propertyname}" 而不是 if:true="propertyname"。
因此,在 Ant 1.9.3 上升级后,您的宏应该可以正常工作:
<property name="test.templates" value="true"/>
....
<target name="test.templates"
description="Test the autoconfiguration templates and answers">
<test.templates
if:true="${test.templates}"
template.root.dir="${main.dir}"
answers.dir="${main.config.dir}"/>
</target>