Ant 映射器

映射器常用于<uptodate>、<move>、<copy>和<apply>等任务,实现了文件重命名算法。

Identity映射器

    目标文件和源文件名称一致。

    它是<copy>和<move>任务的默认映射器,所以下面两种Copy的声明是等价的:

    

<?xml version="1.0" encoding="UTF-8"?>
<project name="junit" default="clean">

	<property name="from.dir" location="src"/>
	<property name="to.dir" location="mapper"/>

	<target name="copy" depends="clean">
	<!--	两种Copy是等价的	-->
	<!--
		<copy todir="${to.dir}">
			<fileset dir="${from.dir}" includes="**/*.java"/>
			<identitymapper/>
		</copy>
	-->
		<copy todir="mapper">
			<fileset dir="src" includes="**/*.java"/>
		</copy>
	
	</target>

	<target name="clean">
		<mkdir dir="${to.dir}"/>
		<delete includeemptydirs="true">
			<fileset dir="${to.dir}">
				<include name="**/*"/>
			</fileset>
		</delete>
	</target>

</project>

Flatter映射器

    目标文件和源文件名称一致,但是路径信息只保留到顶级目录(扁平化)。

    如果源文件集中有多个文件的名字相同,它们中只有一个会被映射到目标目录中,而且无法预期会是哪个。

<?xml version="1.0" encoding="UTF-8"?>
<project name="junit" default="clean">

	<property name="from.dir" location="src"/>
	<property name="to.dir" location="mapper"/>

	<target name="copy" depends="clean">
		<copy todir="${to.dir}">
			<fileset dir="${from.dir}" includes="**/*.java"/>
			<flattenmapper/>
		</copy>
	</target>

	<target name="clean">
		<mkdir dir="${to.dir}"/>
		<delete includeemptydirs="true">
			<fileset dir="${to.dir}">
				<include name="**/*"/>
			</fileset>
		</delete>
	</target>

</project>

Glob映射器

    from模式中使用的一个星号(*)指代部分由to模式中的内容替代,只对匹配from模式的文件进行操作

    下例中将所有Java文件的扩展名替换为.java.bak

<?xml version="1.0" encoding="UTF-8"?>
<project name="junit" default="clean">

	<property name="from.dir" location="src"/>
	<property name="to.dir" location="mapper"/>

	<target name="copy" depends="clean">
		<copy todir="${to.dir}">
			<fileset dir="${from.dir}" includes="**/*.java"/>
			<globmapper from="*.java" to="*.java.bak"/>
		</copy>
	</target>

	<target name="clean">
		<mkdir dir="${to.dir}"/>
		<delete includeemptydirs="true">
			<fileset dir="${to.dir}">
				<include name="**/*"/>
			</fileset>
		</delete>
	</target>

</project>

Regexp映射器

    from和to模式都被定义为正则表达式,而只对匹配from模式的文件进行操作

    用\0可以实现源文件名的完全匹配,从\1到\9则匹配from模式中用括号括起来的部分。

    下例复制src中的Java文件,并将Java文件的名称加前缀2和后缀3,并修改文件扩展名。

<?xml version="1.0" encoding="UTF-8"?>
<project name="junit" default="clean">

	<property name="from.dir" location="src"/>
	<property name="to.dir" location="mapper"/>

	<target name="copy" depends="clean">
		<copy todir="${to.dir}">
			<fileset dir="${from.dir}" includes="**/*.java"/>
			<regexpmapper from="^(.*)\\(.*)\.java$" to="\1\\2\23.java.bak"/>
		</copy>
	</target>

	<target name="clean">
		<mkdir dir="${to.dir}"/>
		<delete includeemptydirs="true">
			<fileset dir="${to.dir}">
				<include name="**/*"/>
			</fileset>
		</delete>
	</target>

</project>

Package映射器

    glob映射器的子集,不同之处在于它将分隔符用点位符(.)替换,这样可以将一个分层结构的包目录文件映射为扁平目录结构,而其包结构保存在文件名中。

    还有一个与package映射器相反的映射器unpackagemapper

    

<?xml version="1.0" encoding="UTF-8"?>
<project name="junit" default="clean">

	<property name="from.dir" location="src"/>
	<property name="to.dir" location="mapper"/>

	<target name="copy" depends="clean">
		<copy todir="${to.dir}">
			<fileset dir="${from.dir}" includes="**/*.java"/>
			<packagemapper from="*.java" to="*.java"/>
		</copy>
	</target>

	<target name="unpackage" depends="copy">
		<copy todir="${to.dir}/unpackage">
			<fileset dir="${to.dir}" includes="**/*.java"/>
			<unpackagemapper from="*.java" to="*.java"/>
		</copy>
	</target>

	<target name="clean">
		<mkdir dir="${to.dir}"/>
		<delete includeemptydirs="true">
			<fileset dir="${to.dir}">
				<include name="**/*"/>
			</fileset>
		</delete>
	</target>

</project>

Merge映射器

    所有的源文件被映射到一个由to属性指定的文件中。

    

<?xml version="1.0" encoding="UTF-8"?>
<project name="ant" default="clean">

	<property name="from.dir" location="src"/>
	<property name="to.dir" location="mapper"/>

	<target name="uptodate">
		<uptodate property="zip.notRequired">
			<srcfiles dir="${from.dir}" includes="**/*.java"/>
			<mergemapper to="${to.dir}/all.zip"/>
		</uptodate>
		<echo message="zip:${zip.notRequired}"/>
	</target>

	<target name="zip" depends="uptodate" unless="zip.notRequired">
		<zip destFile="${to.dir}/all.zip">
			<zipfileset dir="${from.dir}">
				<include name="**/*.java"/>
			</zipfileset>
		</zip>
	</target>

	<target name="clean">
		<mkdir dir="${to.dir}"/>
		<delete includeemptydirs="true">
			<fileset dir="${to.dir}">
				<include name="**/*"/>
			</fileset>
		</delete>
	</target>

</project>

 输出:

<!-- 第一次运行 -->
E:\workspace\Diary>ant -f build_mapper.xml zip
Buildfile: E:\workspace\Diary\build_mapper.xml

clean:

uptodate:
     [echo] zip:${zip.notRequired}

zip:
      [zip] Building zip: E:\workspace\Diary\mapper\all.zip

BUILD SUCCESSFUL
Total time: 0 seconds

<!-- 第二次运行 -->
E:\workspace\Diary>ant -f build_mapper.xml zip
Buildfile: E:\workspace\Diary\build_mapper.xml

uptodate:
     [echo] zip:true

zip:

BUILD SUCCESSFUL
Total time: 0 seconds

<!-- 添加新类后运行 -->
E:\workspace\Diary>ant -f build_mapper.xml zip
Buildfile: E:\workspace\Diary\build_mapper.xml

uptodate:
     [echo] zip:${zip.notRequired}

zip:
      [zip] Building zip: E:\workspace\Diary\mapper\all.zip

BUILD SUCCESSFUL
Total time: 0 seconds

<!-- 无修改再次运行 -->
E:\workspace\Diary>ant -f build_mapper.xml zip
Buildfile: E:\workspace\Diary\build_mapper.xml

uptodate:
     [echo] zip:true

zip:

BUILD SUCCESSFUL
Total time: 0 seconds

<!-- 修改某个类后运行 -->
E:\workspace\Diary>ant -f build_mapper.xml zip
Buildfile: E:\workspace\Diary\build_mapper.xml

uptodate:
     [echo] zip:${zip.notRequired}

zip:
      [zip] Building zip: E:\workspace\Diary\mapper\all.zip

BUILD SUCCESSFUL
Total time: 0 seconds

Composite映射器

    并行应用所有的内嵌映射器。

<?xml version="1.0" encoding="UTF-8"?>
<project name="ant" default="clean">

	<property name="from.dir" location="src"/>
	<property name="to.dir" location="mapper"/>

	<target name="copy" depends="clean">
		<copy todir="${to.dir}">
			<fileset dir="${from.dir}" includes="**/*.java"/>
			<compositemapper>
				<!-- 从上到下处理,上面处理过的文件,下面将不再处理 -->
				<packagemapper from="*Service.java" to="*Service.java"/>
				<identitymapper/>
			</compositemapper>
		</copy>
	</target>

	<target name="clean">
		<mkdir dir="${to.dir}"/>
		<delete includeemptydirs="true">
			<fileset dir="${to.dir}">
				<include name="**/*"/>
			</fileset>
		</delete>
	</target>

</project>

Chained映射器

    串行应用所有的内嵌映射器。

    

<?xml version="1.0" encoding="UTF-8"?>
<project name="ant" default="clean">

	<property name="from.dir" location="src"/>
	<property name="to.dir" location="mapper"/>

	<target name="copy" depends="clean">
		<copy todir="${to.dir}">
			<fileset dir="${from.dir}" includes="**/*.java"/>
			<chainedmapper>
				<!-- 从上到下处理,下面的映射器只会处理上面处理过的文件 -->
				<packagemapper from="*Service.java" to="*Service.java"/>
				<unpackagemapper from="*Service.java" to="*Service.java"/>
				<flattenmapper/>
			</chainedmapper>
		</copy>
	</target>

	<target name="clean">
		<mkdir dir="${to.dir}"/>
		<delete includeemptydirs="true">
			<fileset dir="${to.dir}">
				<include name="**/*"/>
			</fileset>
		</delete>
	</target>

</project>

Filter映射器

    对每个文件名应用一系列“管道”命令。

Script映射器

    通过脚本语言的运行代码创建一个输出的文件名。

Mapping File Names

Some tasks take source files and create target files. Depending on the task, it may be quite obvious which name a target file will have (using javac, you know there will be .class files for your .java files) - in other cases you may want to specify the target files, either to help Apache Ant or to get an extra bit of functionality.

While source files are usually specified as filesets, you don't specify target files directly - instead, you tell Ant how to find the target file(s) for one source file. An instance of org.apache.tools.ant.util.FileNameMapper is responsible for this. It constructs target file names based on rules that can be parameterized with from and to attributes - the exact meaning of which is implementation-dependent.

These instances are defined in <mapper> elements with the following attributes:

AttributeDescriptionRequired
typespecifies one of the built-in implementations.Exactly one of these
classnamespecifies the implementation by class name.
classpaththe classpath to use when looking up classname.No
classpathrefthe classpath to use, given as reference to a path defined elsewhere.No
fromthe from attribute for the given implementation.Depends on implementation.
tothe to attribute for the given implementation.Depends on implementation.

Note that Ant will not automatically convert / or \ characters in the to and from attributes to the correct directory separator of your current platform. If you need to specify this separator, use ${file.separator} instead. For the regexpmapper, ${file.separator}will not work, as on windows it is the '\' character, and this is an escape character for regular expressions, one should use thehandledirsep attribute instead.

Parameters specified as nested elements

The classpath can be specified via a nested <classpath>, as well - that is, a path-like structure.

Since Ant 1.7.0, nested File Mappers can be supplied via either <mapper> elements or <typedef>'d implementations oforg.apache.tools.ant.util.FileNameMapper. If nested File Mappers are specified by either means, the mapper will be implicitly configured as a composite mapper.


The built-in mapper types are:

All built-in mappers are case-sensitive.

As of Ant 1.7.0, each of the built-in mapper implementation types is directly accessible using a specific tagname. This makes it possible for filename mappers to support attributes in addition to the generally available to and from.
The <mapper type|classname="..."> usage form remains valid for reasons of backward compatibility.

identity

The target file name is identical to the source file name. Both to and from will be ignored.

Examples:

<mapper type="identity"/>
<identitymapper/>
Source file nameTarget file name
A.javaA.java
foo/bar/B.javafoo/bar/B.java
C.propertiesC.properties
Classes/dir/dir2/A.propertiesClasses/dir/dir2/A.properties

flatten

The target file name is identical to the source file name, with all leading directory information stripped off. Both to and from will be ignored.

Examples:

<mapper type="flatten"/>
<flattenmapper/>
Source file nameTarget file name
A.javaA.java
foo/bar/B.javaB.java
C.propertiesC.properties
Classes/dir/dir2/A.propertiesA.properties

merge

The target file name will always be the same, as defined by to - from will be ignored.

Examples:
<mapper type="merge" to="archive.tar"/>
<mergemapper to="archive.tar"/>
Source file nameTarget file name
A.javaarchive.tar
foo/bar/B.javaarchive.tar
C.propertiesarchive.tar
Classes/dir/dir2/A.propertiesarchive.tar

glob

Both to and from are required and define patterns that may contain at most one *. For each source file that matches the frompattern, a target file name will be constructed from the to pattern by substituting the * in the to pattern with the text that matches the *in the from pattern. Source file names that don't match the from pattern will be ignored.

Examples:

<mapper type="glob" from="*.java" to="*.java.bak"/>
<globmapper from="*.java" to="*.java.bak"/>
Source file nameTarget file name
A.javaA.java.bak
foo/bar/B.javafoo/bar/B.java.bak
C.propertiesignored
Classes/dir/dir2/A.propertiesignored
<mapper type="glob" from="C*ies" to="Q*y"/>
<globmapper from="C*ies" to="Q*y"/>
Source file nameTarget file name
A.javaignored
foo/bar/B.javaignored
C.propertiesQ.property
Classes/dir/dir2/A.propertiesQlasses/dir/dir2/A.property

The globmapper mapper can take the following extra attributes.

AttributeDescriptionRequired
casesensitiveIf this is false, the mapper will ignore case when matching the glob pattern. This attribute can be true or false, the default is true. Since Ant 1.6.3.No
handledirsepIf this is specified, the mapper will ignore the difference between the normal directory separator characters - \ and /. This attribute can be true or false, the default is false. This attribute is useful for cross-platform build files. Since Ant 1.6.3.No

An example:

<pathconvert property="x" targetos="unix">
        <path path="Aj.Java"/>
        <mapper>
        <chainedmapper>
          <flattenmapper/>
          <globmapper from="a*.java" to="*.java.bak" casesensitive="no"/>
        </chainedmapper>
        </mapper>
      </pathconvert>
      <echo>x is ${x}</echo>

will output "x is j.java.bak".

and

<pathconvert property="x" targetos="unix">
        <path path="d/e/f/j.java"/>
        <mapper>
          <globmapper from="${basedir}\d/e\*" to="*" handledirsep="yes"/>
        </mapper>
      </pathconvert>
      <echo>x is ${x}</echo>

will output "x is f/j.java".

regexp

Both to and from are required and define regular expressions. If the source file name (as a whole or in part) matches the frompattern, the target file name will be constructed from the to pattern, using \0 to \9 as back-references for the full match (\0) or the matches of the subexpressions in parentheses. The to pattern determines the whole file name, so if you wanted to replace the extension of a file you should not use from="\.old$" to=".new" but rather from="(.*)\.old$" to="\1.new" (or rather use a glob mapper in this case).

Source files not matching the from pattern will be ignored.

Note that you need to escape a dollar-sign ($) with another dollar-sign in Ant.

The regexp mapper needs a supporting library and an implementation of org.apache.tools.ant.util.regexp.RegexpMatcher that hides the specifics of the library. Since Ant 1.8.0 Ant requires Java 1.4 to run, so the implementation based on the java.util.regexpackage will always be available. You can still use the now retired Jakarta ORO or Jakarta Regex instead if your provide the corresponding jar in your CLASSPATH.

For information about using gnu.regexp or gnu.rex with Ant, see this article.

If you want to use one of the regular expression libraries other than java.util.regex you need to also use the corresponding ant-[apache-oro, apache-regexp].jar from the Ant release you are using. Make sure, both will be loaded from the same classpath, that is either put them into your CLASSPATHANT_HOME/lib directory or a nested <classpath> element of the mapper - you cannot haveant-[apache-oro, apache-regexp].jar in ANT_HOME/lib and the library in a nested <classpath>.

Ant will choose the regular-expression library based on the following algorithm:

  • If the system property ant.regexp.matcherimpl has been set, it is taken as the name of the class implementingorg.apache.tools.ant.util.regexp.RegexpMatcher that should be used.
  • If it has not been set, uses the JDK 1.4 classes.

Examples:

<mapper type="regexp" from="^(.*)\.java$$" to="\1.java.bak"/>
<regexpmapper from="^(.*)\.java$$" to="\1.java.bak"/>
Source file nameTarget file name
A.javaA.java.bak
foo/bar/B.javafoo/bar/B.java.bak
C.propertiesignored
Classes/dir/dir2/A.propertiesignored
<mapper type="regexp" from="^(.*)/([^/]+)/([^/]*)$$" to="\1/\2/\2-\3"/>
<regexpmapper from="^(.*)/([^/]+)/([^/]*)$$" to="\1/\2/\2-\3"/>
Source file nameTarget file name
A.javaignored
foo/bar/B.javafoo/bar/bar-B.java
C.propertiesignored
Classes/dir/dir2/A.propertiesClasses/dir/dir2/dir2-A.properties
<mapper type="regexp" from="^(.*)\.(.*)$$" to="\2.\1"/>
<regexpmapper from="^(.*)\.(.*)$$" to="\2.\1"/>
Source file nameTarget file name
A.javajava.A
foo/bar/B.javajava.foo/bar/B
C.propertiesproperties.C
Classes/dir/dir2/A.propertiesproperties.Classes/dir/dir2/A
<mapper type="regexp" from="^(.*?)(\$$[^/\\\.]*)?\.class$$" to="\1.java"/>
<regexpmapper from="^(.*?)(\$$[^/\\\.]*)?\.class$$" to="\1.java"/>
Source file nameTarget file name
ClassLoader.classClassLoader.java
java/lang/ClassLoader.classjava/lang/ClassLoader.java
java\lang\ClassLoader$1.classjava\lang\ClassLoader.java
java/lang/ClassLoader$foo$1.classjava/lang/ClassLoader.java

The regexpmapper mapper can take the following extra attributes.

AttributeDescriptionRequired
casesensitiveIf this is false, the mapper will ignore case when matching the pattern. This attribute can be true or false, the default is true. Since Ant 1.6.3.No
handledirsepIf this is specified, the mapper will treat a \ character in a filename as a / for the purposes of matching. This attribute can be true or false, the default is false. This attribute is useful for cross-platform build files.Since Ant 1.6.3.No

An example:

<pathconvert property="x" targetos="unix">
        <path path="Aj.Java"/>
        <chainedmapper>
          <flattenmapper/>
          <regexpmapper from="a(.*)\.java" to="\1.java.bak" casesensitive="no"/>
        </chainedmapper>
      </pathconvert>
      <echo>x is ${x}</echo>

will output "x is j.java.bak".

and

<pathconvert property="hd.prop" targetos="windows">
      <path path="d\e/f\j.java"/>
      <chainedmapper>
        <regexpmapper from="${basedir}/d/e/(.*)" to="\1" handledirsep="yes"/>
      </chainedmapper>
    </pathconvert>

will set hd.prop to "f\j.java".

package

Sharing the same syntax as the glob mapper, the package mapper replaces directory separators found in the matched source pattern with dots in the target pattern placeholder. This mapper is particularly useful in combination with <uptodate> and <junit>output.

The to and from attributes are both required.

Example:

<mapper type="package" from="*Test.java" to="TEST-*Test.xml"/>
<packagemapper from="*Test.java" to="TEST-*Test.xml"/>
Source file nameTarget file name
org/apache/tools/ant/util/PackageMapperTest.javaTEST-org.apache.tools.ant.util.PackageMapperTest.xml
org/apache/tools/ant/util/Helper.javaignored

unpackage (since Ant 1.6.0)

This mapper is the inverse of the package mapper. It replaces the dots in a package name with directory separators. This is useful for matching XML formatter results against their JUnit test test cases. The mapper shares the sample syntax as the glob mapper.

The to and from attributes are both required.

Example:

<mapper type="unpackage" from="TEST-*Test.xml" to="${test.src.dir}/*Test.java">
<unpackagemapper from="TEST-*Test.xml" to="${test.src.dir}/*Test.java">
Source file nameTarget file name
TEST-org.acme.AcmeTest.xml${test.src.dir}/org/acme/AcmeTest.java

composite (since Ant 1.7.0)

This mapper implementation can contain multiple nested mappers. File mapping is performed by passing the source filename to each nested <mapper> in turn, returning all results. The to and from attributes are ignored.

Starting with Ant 1.8.0 the order of the mapped results is the same as the order of the nested mappers; prior to Ant 1.8.0 the order has been undefined.

Examples:

<compositemapper>
  <identitymapper/>
  <packagemapper from="*.java" to="*"/>
</compositemapper>
Source file nameTarget file names
foo/bar/A.javafoo/bar/A.java
foo.bar.A

The composite mapper has no corresponding <mapper <strong>type</strong>> attribute.

chained (since Ant 1.7.0)

This mapper implementation can contain multiple nested mappers. File mapping is performed by passing the source filename to the first nested mapper, its results to the second, and so on. The target filenames generated by the last nested mapper comprise the ultimate results of the mapping operation. The to and from attributes are ignored.

Examples:

<chainedmapper>
  <flattenmapper/>
  <globmapper from="*" to="new/path/*"/>
  <mapper>
    <globmapper from="*" to="*1"/>
    <globmapper from="*" to="*2"/>
  </mapper>
</chainedmapper>
Source file nameTarget file names
foo/bar/A.javanew/path/A.java1
new/path/A.java2
boo/far/B.javanew/path/B.java1
new/path/B.java2

The chained mapper has no corresponding <mapper <strong>type</strong>> attribute.

filtermapper (since Ant 1.6.3)

This mapper implementation applies a filterchain to the source file name.

Examples:

<filtermapper>
  <replacestring from="\" to="/"/>
</filtermapper>
Source file nameTarget file names
foo\bar\A.javafoo/bar/A.java
<filtermapper>
  <scriptfilter language="beanshell">
    self.setToken(self.getToken().toUpperCase());
  </scriptfilter>
</filtermapper>
Source file nameTarget file names
foo\bar\A.javafoo\bar\A.java

The filtermapper has no corresponding <mapper <strong>type</strong>> attribute.

scriptmapper (since Ant 1.7)

This mapper executes a script written in Apache BSF or JSR 223 supported language, once per file to map.

The script can be declared inline or in a specified file.

See the Script task for an explanation of scripts and dependencies.

AttributeDescriptionRequired
languageScripting languageYes
managerThe script engine manager to use. See the script task for using this attribute.No - default is "auto"
srcFile containing the scriptNo
setbeanswhether to have all properties, references and targets as global variables in the script. since Ant 1.8.0No, default is "true".
classpathThe classpath to pass into the script.No
classpathrefThe classpath to use, given as a reference to a path defined elsewhere.No

This filename mapper can take a nested <classpath> element. See the script task on how to use this element.

Example:

<scriptmapper language="javascript">
  self.addMappedName(source.toUpperCase());
  self.addMappedName(source.toLowerCase());
</scriptmapper>
Source file nameTarget file names
foo\bar\A.javafoo\bar\A.java
foo\bar\A.java

To use this mapper, the scripts need access to the source file, and the ability to return multiple mappings. Here are the relevant beans and their methods. The script is called once for every source file, with the list of mapped names reset after every invocation.

Script beanDescription
source: StringThe file/path to map
selfthe scriptmapper itself
self.addMappedName(String name)Add a new mapping
self.clear()Reset the list of files.

The scriptmapper has no corresponding <mapper <strong>type</strong>> attribute.

firstmatchmapper (since Ant 1.8.0)

This mapper supports an arbitrary number of nested mappers and returns the results of the first mapper that matches. This is different from composite mapper which collects the results of all matching children.

Examples:

<firstmatchmapper>
  <globmapper from="*.txt" to="*.bak"/>
  <globmapper from="*A.*" to="*B.*"/>
</firstmatchmapper>
Source file nameTarget file names
foo/bar/A.txtfoo/bar/A.bak
foo/bar/A.javafoo/bar/B.java

The firstmatchmapper has no corresponding <mapper <strong>type</strong>> attribute.

cutdirsmapper (since Ant 1.8.2)

This mapper strips a configured number of leading directories from the source file name.

Examples:

<cutdirsmapper dirs="1"/>
Source file nameTarget file names
foo/bar/A.txtbar/A.txt

The cutdirsmapper has no corresponding <mapper <strong>type</strong>> attribute.

AttributeDescriptionRequired
dirsNumber of directories to strip (must be a positive number).Yes