小菜毛毛技术分享

与大家共同成长

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  164 Posts :: 141 Stories :: 94 Comments :: 0 Trackbacks

很想把Ant好好的学习一下,最好的学习方法就是看官方文档,所以决定把原版英文文档翻译一下,如果有翻译不对的地方,请大家指出来,谢谢

英文部份为还没有翻译的部份

文档原始地址:http://ant.apache.org/manual/index.html

参考资料:孙鑫老师的JAVA WEB开发详解 

Using Ant

简单的构建文件:

ant的构建文件是xml格式的,每一个构建文件包含一个project和至少一个(缺省)target,目标包含任务(task)元素,构建文件里的每一个任务元素(task)可以指定一个id元素,可以用它的值来引用这个task,这个值是唯一的,

(更多说明,请看下面的 Tasks

Projects(工程)

Project 有三个属性

 

属性 描述 必须
name 工程名 No
default 没有指定target时缺省使用的target名字 No; 然而在Ant 1.6.0后,每个工程包含一个即使使用 -projecthelp 选项也要执行的任务.
basedir

要路径,这个属性可以被先前设置的“basedir"这个属性覆盖,计算其它路径的其路径。如果没有设置这个属性或特性(Property),将使用构建文件(build.xml)的父目录作为基目录。

No

对一个工程的描述(description)可以用顶级的元素<description>(请看description 元素)

每个工程都定义了一个或多个目标(target),目标就是一系列你要执行的任务,当执行ant的时候,你可以选择执行你想要执行的目标,当没有指定目标时,使用<project>元素中default指定的目标。

Targets

一个目标可以依赖其它的目标,例如,你可以有一个编译的目标,一个发布的目标,只有编译之后才可以发布,所以以布目标要依赖于编译,Ant解决这种依赖关系。

应该说明的是,Ant的这种依赖只是指定的目标的执行顺序,这并不影响执行那些没有必要执行的依赖目标。

Ant执行目标的顺序是按照它们从左到右的出现顺序,一个目标比它依赖的目标更早执行是有可能的。

<target name="A"/>
<target name="B" depends="A"/>
<target name="C" depends="B"/>
<target name="D" depends="C,B,A"/>

我们要执行目标D.从依赖属性(depends)看,你可能认为应该先执行目标C,然后是B,最后是A,错了!C依赖B,B依赖A,因此,先执行A,再是B,接着是C,最后是D

上面从给定目标D延伸到依赖的A目标的这个依赖链中,每一个目标只执行一次,即使多个目标依赖一个目标,因此,执行目标D首先会调用C执行,C又会调用B执行,B将会导致A第一次被执行,然后执行B,接着是C,一直执行到依赖链中的D,这个过程中,不会再执行B和A,因为他们已经执行过了,如果B和C没有依赖关系,那么,B和A将在C处理D的依赖时就被执行。

可以设置某个特性(Property)执行目标,例如,这可以依赖系统环境(java 版本,操作系统,命令行特性定义,等)更好的控制构造过程,由特性来添加目标,你应该添加属性if(或者 unless属性),属性值为你要作用于此目标上的特性。注意:Ant仅检查这个特性是否被设置,这个特性的值并不重要,一个空字符串的特性仍然是一个存在的特性。比如:

 

<target name="build-module-A" if="module-A-present"/>
<target name="build-own-fake-module-A" unless="module-A-present"/>

在第一个例子中,如果设置了module-A-present特性(可以是任何值,比如:false),目标都会执行。

在第二个例子中,如果设置了module-A-present(也是任意值),目标都不会被运行。

在if/unless属性中只能指定一个特性,如果想指定多种情况,可以通过依赖目标来计算这种检查结果。

<target name="myTarget" depends="myTarget.check" if="myTarget.run">
<echo>Files foo.txt and bar.txt are present.</echo>
</target>
<target name="myTarget.check">
<condition property="myTarget.run">
<and>
<available file="foo.txt"/>
<available file="bar.txt"/>
</and>
</condition>
</target>

如果不存在if和unless属性,目标总是会被执行。

Important: if和unless属性只是让使用了这二个属性的目标执行或不执行,而不能控制目标依赖的目标的执行。

可选的description属性能对目标进行描述,可以用-projecthelp选项查看,没有Description的目标不会被选项令列出来,除非使用-verbose或-debug选项。

在其它目标依赖的初始化目标(initialization target)中放置 tstamp 是一个好的实践,确保这个目标总是第一个被执行的,在这本手册中,大多数的初始化目标都命名叫“init”。

如果设置了依赖目标和if/unless属性,依赖的属性会先执行。

一个目标(target)有以下属性。

 

属性 描述 必须
name target 的名字 Yes
depends

一系列依赖的目标名字,用逗号分隔

No
if

执行此目标一定要设置的特性(property)名

No
unless

执行些目标一定不要设置的特性(property)名。

No
description 对目标的一个简短描述 No

 

 

A target name can be any alphanumeric string valid in the encoding of the XML file. The empty string "" is in this set, as is comma "," and space " ". Please avoid using these, as they will not be supported in future Ant versions because of all the confusion they cause. IDE support of unusual target names, or any target name containing spaces, varies with the IDE.

Targets beginning with a hyphen such as "-restart" are valid, and can be used to name targets that should not be called directly from the command line.

Tasks

A task is a piece of code that can be executed.

A task can have multiple attributes (or arguments, if you prefer). The value of an attribute might contain references to a property. These references will be resolved before the task is executed.

Tasks have a common structure:

<name attribute1="value1" attribute2="value2" ... />

where name is the name of the task, attributeN is the attribute name, and valueN is the value for this attribute.

There is a set of built-in tasks, along with a number of optional tasks, but it is also very easy to write your own.

All tasks share a task name attribute. The value of this attribute will be used in the logging messages generated by Ant.

Tasks can be assigned an id attribute:

<taskname id="taskID" ... />

where taskname is the name of the task, and taskID is a unique identifier for this task. You can refer to the corresponding task object in scripts or other tasks via this name. For example, in scripts you could do:

<script ... > task1.setFoo("bar"); </script>

to set the foo attribute of this particular task instance. In another task (written in Java), you can access the instance via project.getReference("task1").

Note1: If "task1" has not been run yet, then it has not been configured (ie., no attributes have been set), and if it is going to be configured later, anything you've done to the instance may be overwritten.

Note2: Future versions of Ant will most likely not be backward-compatible with this behaviour, since there will likely be no task instances at all, only proxies.

Properties

A project can have a set of properties. These might be set in the buildfile by the property task, or might be set outside Ant. A property has a name and a value; the name is case-sensitive. Properties may be used in the value of task attributes. This is done by placing the property name between "${" and "}" in the attribute value. For example, if there is a "builddir" property with the value "build", then this could be used in an attribute like this: ${builddir}/classes. This is resolved at run-time as build/classes.

In the event you should need to include this construct literally (i.e. without property substitutions), simply "escape" the '$' character by doubling it. To continue the previous example: <echo>$${builddir}=${builddir}</echo>

 

 

 

will echo this message:

${builddir}=build/classes

 

 

 

 

In order to maintain backward compatibility with older Ant releases, a single '$' character encountered apart from a property-like construct (including a matched pair of french braces) will be interpreted literally; that is, as '$'. The "correct" way to specify this literal character, however, is by using the escaping mechanism unconditionally, so that "$$" is obtained by specifying "$$$$". Mixing the two approaches yields unpredictable results, as "$$$" results in "$$".

Built-in Properties

Ant provides access to all system properties as if they had been defined using a <property> task. For example, ${os.name} expands to the name of the operating system.

For a list of system properties see the Javadoc of System.getProperties.

In addition, Ant has some built-in properties:

basedir the absolute path of the project's basedir (as set with the basedir attribute of <project>). ant.file the absolute path of the buildfile. ant.version the version of Ant ant.project.name the name of the project that is currently executing; it is set in the name attribute of <project>. ant.java.version the JVM version Ant detected; currently it can hold the values "1.2", "1.3", "1.4" and "1.5".

 

 

 

There is also another property, but this is set by the launcher script and therefore maybe not set inside IDEs:

ant.home home directory of Ant

 

 

 

 

<project name="MyProject" default="dist" basedir="."> <description> simple example build file </description> <!-- set global properties for this build --> <property name="src" location="src"/> <property name="build" location="build"/> <property name="dist" location="dist"/> <target name="init"> <!-- Create the time stamp --> <tstamp/> <!-- Create the build directory structure used by compile --> <mkdir dir="${build}"/> </target> <target name="compile" depends="init" description="compile the source " > <!-- Compile the java code from ${src} into ${build} --> <javac srcdir="${src}" destdir="${build}"/> </target> <target name="dist" depends="compile" description="generate the distribution" > <!-- Create the distribution directory --> <mkdir dir="${dist}/lib"/> <!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar file --> <jar jarfile="${dist}/lib/MyProject-${DSTAMP}.jar" basedir="${build}"/> </target> <target name="clean" description="clean up" > <!-- Delete the ${build} and ${dist} directory trees --> <delete dir="${build}"/> <delete dir="${dist}"/> </target> </project>

 

Notice that we are declaring properties outside any target. As of Ant 1.6 all tasks can be declared outside targets (earlier version only allowed <property>,<typedef> and <taskdef>). When you do this they are evaluated before any targets are executed. Some tasks will generate build failures if they are used outside of targets as they may cause infinite loops otherwise (<antcall> for example).

We have given some targets descriptions; this causes the projecthelp invocation option to list them as public targets with the descriptions; the other target is internal and not listed.

Finally, for this target to work the source in the src subdirectory should be stored in a directory tree which matches the package names. Check the <javac> task for details.

A project can have a set of tokens that might be automatically expanded if found when a file is copied, when the filtering-copy behavior is selected in the tasks that support this. These might be set in the buildfile by the filter task.

Since this can potentially be a very harmful behavior, the tokens in the files must be of the form @token@, where token is the token name that is set in the <filter> task. This token syntax matches the syntax of other build systems that perform such filtering and remains sufficiently orthogonal to most programming and scripting languages, as well as with documentation systems.

Note: If a token with the format @token@ is found in a file, but no filter is associated with that token, no changes take place; therefore, no escaping method is available - but as long as you choose appropriate names for your tokens, this should not cause problems.

Warning: If you copy binary files with filtering turned on, you can corrupt the files. This feature should be used with text files only.

Path-like Structures

You can specify PATH- and CLASSPATH-type references using both ":" and ";" as separator characters. Ant will convert the separator to the correct character of the current operating system.

Wherever path-like values need to be specified, a nested element can be used. This takes the general form of:

<classpath> <pathelement path="${classpath}"/> <pathelement location="lib/helper.jar"/> </classpath>

 

The location attribute specifies a single file or directory relative to the project's base directory (or an absolute filename), while the path attribute accepts colon- or semicolon-separated lists of locations. The path attribute is intended to be used with predefined paths - in any other case, multiple elements with location attributes should be preferred.

As a shortcut, the <classpath> tag supports path and location attributes of its own, so:

<classpath> <pathelement path="${classpath}"/> </classpath>

 

can be abbreviated to:

<classpath path="${classpath}"/>

 

In addition, one or more Resource Collections can be specified as nested elements (these must consist of file-type resources only). Additionally, it should be noted that although resource collections are processed in the order encountered, certain resource collection types such as fileset, dirset and files are undefined in terms of order.

<classpath> <pathelement path="${classpath}"/> <fileset dir="lib"> <include name="**/*.jar"/> </fileset> <pathelement location="classes"/> <dirset dir="${build.dir}"> <include name="apps/**/classes"/> <exclude name="apps/**/*Test*"/> </dirset> <filelist refid="third-party_jars"/> </classpath>

 

This builds a path that holds the value of ${classpath}, followed by all jar files in the lib directory, the classes directory, all directories named classes under the apps subdirectory of ${build.dir}, except those that have the text Test in their name, and the files specified in the referenced FileList.

If you want to use the same path-like structure for several tasks, you can define them with a <path> element at the same level as targets, and reference them via their id attribute--see References for an example.

A path-like structure can include a reference to another path-like structure (a path being itself a resource collection) via nested <path> elements:

<path id="base.path"> <pathelement path="${classpath}"/> <fileset dir="lib"> <include name="**/*.jar"/> </fileset> <pathelement location="classes"/> </path> <path id="tests.path"> <path refid="base.path"/> <pathelement location="testclasses"/> </path>

 

The shortcuts previously mentioned for <classpath> are also valid for <path>.For example:

<path id="base.path"> <pathelement path="${classpath}"/> </path>

 

can be written as:

<path id="base.path" path="${classpath}"/>

 

Command-line Arguments

Several tasks take arguments that will be passed to another process on the command line. To make it easier to specify arguments that contain space characters, nested arg elements can be used.

Attribute Description Required
value a single command-line argument; can contain space characters. Exactly one of these.
file The name of a file as a single command-line argument; will be replaced with the absolute filename of the file.
path A string that will be treated as a path-like string as a single command-line argument; you can use ;or :as path separators and Ant will convert it to the platform's local conventions.
pathref Reference to a path defined elsewhere. Ant will convert it to the platform's local conventions.
line a space-delimited list of command-line arguments.

It is highly recommended to avoid the line version when possible. Ant will try to split the command line in a way similar to what a (Unix) shell would do, but may create something that is very different from what you expect under some circumstances.

Examples

<arg value="-l -a"/>

is a single command-line argument containing a space character, not separate commands "-l" and "-a".

<arg line="-l -a"/>

This is a command line with two separate arguments, "-l" and "-a".

<arg path="/dir;/dir2:\dir3"/>

is a single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

References

Any project element can be assigned an identifier using its id attribute. In most cases the element can subsequently be referenced by specifying the refid attribute on an element of the same type. This can be useful if you are going to replicate the same snippet of XML over and over again--using a <classpath> structure more than once, for example.

The following example:

<project ... > <target ... > <rmic ...> <classpath> <pathelement location="lib/"/> <pathelement path="${java.class.path}/"/> <pathelement path="${additional.path}"/> </classpath> </rmic> </target> <target ... > <javac ...> <classpath> <pathelement location="lib/"/> <pathelement path="${java.class.path}/"/> <pathelement path="${additional.path}"/> </classpath> </javac> </target> </project>

could be rewritten as:

<project ... > <path id="project.class.path"> <pathelement location="lib/"/> <pathelement path="${java.class.path}/"/> <pathelement path="${additional.path}"/> </path> <target ... > <rmic ...> <classpath refid="project.class.path"/> </rmic> </target> <target ... > <javac ...> <classpath refid="project.class.path"/> </javac> </target> </project>

All tasks that use nested elements for PatternSets, FileSets, ZipFileSets or path-like structures accept references to these structures as shown in the examples. Using refid on a task will ordinarily have the same effect (referencing a task already declared), but the user should be aware that the interpretation of this attribute is dependent on the implementation of the element upon which it is specified. Some tasks (the property task is a handy example) deliberately assign a different meaning to refid.

Use of external tasks

Ant supports a plugin mechanism for using third party tasks. For using them you have to do two steps:

  1. place their implementation somewhere where Ant can find them
  2. declare them.

Don't add anything to the CLASSPATH environment variable - this is often the reason for very obscure errors. Use Ant's own mechanisms for adding libraries:

  • via command line argument -lib
  • adding to ${user.home}/.ant/lib
  • adding to ${ant.home}/lib

For the declaration there are several ways:

  • declare a single task per using instruction using <taskdef name="taskname" classname="ImplementationClass"/>
    <taskdef name="for" classname="net.sf.antcontrib.logic.For" /> <for ... />
  • declare a bundle of tasks using a properties-file holding these taskname-ImplementationClass-pairs and <taskdef>
    <taskdef resource="net/sf/antcontrib/antcontrib.properties" /> <for ... />
  • declare a bundle of tasks using a xml-file holding these taskname-ImplementationClass-pairs and <taskdef>
    <taskdef resource="net/sf/antcontrib/antlib.xml" /> <for ... />
  • declare a bundle of tasks using a xml-file named antlib.xml, XML-namespace and antlib: protocoll handler
    <project xmlns:ac="antlib:net.sf.antconrib"/> <ac:for ... />

If you need a special function, you should

  1. have a look at this manual, because Ant provides lot of tasks
  2. have a look at the external task page in the manual (or better online)
  3. have a look at the external task wiki page
  4. ask on the Ant user list
  5. implement (and share) your own

 

Token Filters

 

Example Buildfile

posted on 2009-06-02 21:41 小菜毛毛 阅读(1183) 评论(0)  编辑  收藏 所属分类: ANT

只有注册用户登录后才能发表评论。


网站导航: