在 Ant 1.9.1 中,您可以使用 if and unless attributes在大多数任务上。
我已经定义了一个宏,我试图在其中运行这些任务:
<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>
但是,这不会运行我的宏——即使属性
test.templates
设置为真。如果我删除该行,我的 test.template 宏将起作用。使用
if:true
有问题吗?在用户定义的宏中?解决此问题的最佳方法是什么?
最佳答案
来自 ant manual :
Since Ant 1.9.1 it is possible to add if and unless attributes on all tasks and nested elements using special namespaces.
直到现在才在宏定义中使用新的 if 和除非属性,但以下代码段有效:
<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>
输出,没有错误但macrodef没有被执行:
[echo] Apache Ant(TM) version 1.9.1 compiled on May 15 2013
BUILD SUCCESSFUL
似乎该区域仍然存在一些不一致之处,因为此功能是全新的。
也许我们应该提交一个错误!?
-- 编辑 (1) --
刚找到一个 comment from 2007 by Peter Reilly (他已经在 ant bug 数据库中实现了 if/unless 功能)提供了一个带有宏定义的片段。
-- 编辑 (2) --
尽管 2013 年 12 月 29 日发布的新 Ant 版本 1.9.3 ( see releasenotes here ) 修复了与新 if: 和除非: 属性 ( https://issues.apache.org/bugzilla/show_bug.cgi?id=55885 ) 相关的错误,但我们的问题仍然存在。因此我打开了一个错误报告,请参阅 Ant 错误数据库 bugid 55971 .
-- 编辑 (3) --
终于找到了解决办法。除了 Bugid 55885 的错误修复Ant 版本 1.9.3 还为新的 if:andunless: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>
关于Ant if :true. 将属性设置为 true 不会导致任务执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20102601/