我有一个执行过滤器复制的ant任务,我只更改参数多次调用它。这是为各种环境创建属性文件。
我想简化调用目标,这样我可以做更少的复制和粘贴。
这是调用目标
<target name="create_local_property_files" depends="clean,prepare">
<!-- create first machine property files -->
<antcall target="property.filter.copy" inheritAll="false">
<param name="tmp.dom" value="machine1" />
</antcall>
<!-- create second machine property files -->
<antcall target="property.filter.copy" inheritAll="false">
<param name="tmp.dom" value="machine2" />
</antcall>
[...] <!-- to the n'th machine property file -->
</target>
我想打一个电话,然后传递一份机器清单。有什么建议吗?这是用于完整性的过滤器复制目标
<target name="property.filter.copy">
<copy todir="${local.property.file.dir}" failonerror="true" verbose="true" overwrite="true">
<filterset>
<!-- Uses the same filters files as scripts -->
<filtersfile file="${property.variables.dir}/${tmp.dom}.properties" />
</filterset>
<fileset dir="${property.file.dir}">
<include name="cnmp.properties" />
<include name="cnmp.jdo.properties" />
</fileset>
<!-- Deployment script looks for hostname.rest_of_filename-->
<globmapper from="*" to="${tmp.dom}.*" />
</copy>
</target>
我建议对重复的代码段使用macrodef
<project name="demo" default="copy">
<macrodef name="propertyFilterCopy">
<attribute name="tmp.dom"/>
<attribute name="local.property.file.dir" default="build/properties"/>
<attribute name="property.variables.dir" default="build/variables"/>
<attribute name="property.file.dir" default="build/files"/>
<sequential>
<copy todir="@{local.property.file.dir}" failonerror="true" verbose="true" overwrite="true">
<filterset>
<filtersfile file="@{property.variables.dir}/@{tmp.dom}.properties" />
</filterset>
<fileset dir="@{property.file.dir}">
<include name="cnmp.properties" />
<include name="cnmp.jdo.properties" />
</fileset>
<globmapper from="*" to="@{tmp.dom}.*" />
</copy>
</sequential>
</macrodef>
<target name="copy" depends="gen-data">
<propertyFilterCopy tmp.dom="machine1"/>
<propertyFilterCopy tmp.dom="machine2"/>
</target>
<target name="gen-data">
<mkdir dir="build/properties"/>
<mkdir dir="build/variables"/>
<mkdir dir="build/files"/>
<echo file="build/files/cnmp.properties">x=1</echo>
<echo file="build/files/cnmp.jdo.properties">x=1</echo>
<echo file="build/variables/machine1.properties">x=1</echo>
<echo file="build/variables/machine2.properties">x=1</echo>
</target>
<target name="clean">
<delete dir="build"/>
</target>
</project>
macrodef的第二个优点是它们可以打包成antlib,这进一步增加了可重用构建逻辑的可移植性。
在ant-contrib中有一些循环可以很好地完成这项工作。
查看foreach
任务的实例