在 ant 脚本中定义任务或宏
Defining a task -- or macro -- in ant-script
我们有一个很大的 build.xml
文件,其中有一些任务在多个目标中一字不差地重复——例如冗长的 <echo>
,它用一个文件的内容更新日志文件对象:
<echo file="foo.log" message="${run.name} completed with status ${run.status}. Errors: ${run.errors}, warnings: ${run.warnings}, processed ${run.processed}"/>
这可以变成像 <logrun file="file.log" run=${run}"/>
-- 中的 XML 吗?也就是说,没有我们写 Java-code to implement the new logrun
-task?
简短的回答是肯定的,使用 Ant <macrodef>
任务。
像这样:
<macrodef name="logrun">
<attribute name="file"/>
<attribute name="name"/>
<attribute name="status"/>
<attribute name="errors"/>
<attribute name="warnings"/>
<attribute name="processed"/>
<sequential>
<echo file="@{file}"
message="@{name} completed with status @{status}. Errors: @{errors}, warnings: @{warnings}, processed @{processed}${line.separator}"/>
</sequential>
</macrodef>
<logrun file="foo.log" name="foo.name" status="foo.status" errors="foo.errors" warnings="foo.warnings" processed="foo.processed" />
注意在宏的“主体”中使用 @
前缀引用命名宏参数的方式。我在message参数末尾加了一个${line.separator}
,这样写入文件的行就终止了。您可能希望在 echo 任务中使用 append="true"
,以便每次调用宏时文件不会被完全覆盖。
一个宏可能会满足您所有的属性边缘情况,具体取决于它们的复杂程度。
我们有一个很大的 build.xml
文件,其中有一些任务在多个目标中一字不差地重复——例如冗长的 <echo>
,它用一个文件的内容更新日志文件对象:
<echo file="foo.log" message="${run.name} completed with status ${run.status}. Errors: ${run.errors}, warnings: ${run.warnings}, processed ${run.processed}"/>
这可以变成像 <logrun file="file.log" run=${run}"/>
-- 中的 XML 吗?也就是说,没有我们写 Java-code to implement the new logrun
-task?
简短的回答是肯定的,使用 Ant <macrodef>
任务。
像这样:
<macrodef name="logrun">
<attribute name="file"/>
<attribute name="name"/>
<attribute name="status"/>
<attribute name="errors"/>
<attribute name="warnings"/>
<attribute name="processed"/>
<sequential>
<echo file="@{file}"
message="@{name} completed with status @{status}. Errors: @{errors}, warnings: @{warnings}, processed @{processed}${line.separator}"/>
</sequential>
</macrodef>
<logrun file="foo.log" name="foo.name" status="foo.status" errors="foo.errors" warnings="foo.warnings" processed="foo.processed" />
注意在宏的“主体”中使用 @
前缀引用命名宏参数的方式。我在message参数末尾加了一个${line.separator}
,这样写入文件的行就终止了。您可能希望在 echo 任务中使用 append="true"
,以便每次调用宏时文件不会被完全覆盖。
一个宏可能会满足您所有的属性边缘情况,具体取决于它们的复杂程度。