第一章:Getting Started
l Ant默认的构建文件为build.xml
l Ant构建文件中的根XML元素为project,project可用属性为:
Attribute
Description
Required
name
Defines the project name
No
default
The target to invoke if no target is explicitly specified
Yes
basedir
The base directory from which all relative paths are resolved
No
l Ant工程(project)中由若干个构建目标(target)组成,构建目标是一组相关任务(Tasks)的集合,如编译文件、创建目录、打包等,构建目标之间可以建立依赖关系,构建目标执行之前必须先执行所有所依赖的构建目标。Ant工程通过project的default属性指定默认的构建目标名称。构建目标的XML元素为target,其可用的属性为:
Attribute
Description
Required
name
Defines the target name
Yes
depends
Comma-separated list of targets to execute before this target
No
if
Name of a property needed to run this task
No
unless
Name of a property that can not be set before running this task
No
description
Description of this target's purpose
No
l 构建任务(Tasks)是构建目标(target)的基本组成部分,是Ant构建的基本执行单元。Ant中存在很多内建的构建任务,如下表所示:
Task Name
Description
ant
Executes Ant
antcall
Executes a target from the current build file
antstructure
From a given build file, creates a DTD reflecting all of the tasks Ant currently knows about
apply [execon]
Invokes a native executable
available
Sets a Boolean value in a property according to the availability of desired resource
basename
Sets a property to the last element of a specified path in an effort to determine a file's name without directory structure
buildnumber
Manages build numbers
bunzip2
Expands GZip or BZip2 archives
bzip2
Packs GZip or BZip2 archives
checksum
Creates checksums for one or more files
chmod
Modifies file permissions on Unix
concat
Concatenates multiple files
condition
Checks the result of a condition and sets the result to in a property
copy [copydir, copyfile]
Copies files
cvs
Interacts with a CVS repository
cvschangelog
Converts a series of CVS change logs into an XML report
cvspass
Adds entries to a .cvspass file
cvstagdiff
Creates an XML report highlighting the differences between tags
cvsversion
Finds the CVS software version
defaultexcludes
Modifies the list of default exclude patterns, affecting which files are automatically excluded from processing by file-related tasks
delete [deltree]
Delete files and folders
dependset
Deletes target files that are older than new source files
dirname
Assigns a file's directory path to a property
ear
Extends the jar task to support handling files for an Enterprise Application archive (EAR)
echo
Echoes text to System.out or to a file
exec
Invokes a native executable
fail
Halts and exits a build by throwing a BuildException
filter
Sets a token filter that can be used by filter-related tasks such as copy
fixcrlf
Adds or remove tabs, carriage returns, linefeeds, and EOF characters from a set of files
genkey
Adds a new key to a given keystore
get
Retrieves files using FTP, HTTP, and more from a URL
gunzip
Unpacks a GZip file
gzip
Packs a GZip file
import
Allows the use of other Ant files
input
Displays a message and reads a line of input from the console, allowing for user input during the build process
jar
Creates a JAR archive similar to Java's jar command
java
Executes the Java interpreter to run a class or application
javac
Compiles the specified source file(s)
javadoc [javadoc2]
Invokes the javadoc tool to create documentation
loadfile
Sets a property file to the entire contents of a text file
loadproperties
Loans an entire property file into Ant properties
macrodef
Defines a new task as a macro built-up upon other tasks
Sends SMTP mail messages
manifest
Creates an archive's manifest file
mkdir
Makes a new directory
move [rename]
Moves a file to another directory
parallel
Contains other Ant tasks that can be run simultaneously by multiple Java threads
patch
Uses the patch command (assuming it is on the path) to apply diff files to a source file (or files)
pathconvert
Converts paths between platforms
presetdef
Defines a new task based on an existing task with certain options preset as defaults
property
Sets one or more properties to new values
record
Runs a listener that records the logging output of the build process to a file
replace
Replaces a string with another in all files in a directory
rmic
Invokes the rmic compiler
sequential
A container task that can contain other Ant tasks and run them in sequence
signjar
Uses the JarSigner to securely sign ZIP and JAR archives
sleep
Suspends execution for a specified period of time
sql
Runs SQL statements against a database
subant
Runs Ant within all subdirectories of the project directory
sync
Synchronizes two directory trees
tar
Makes a new TAR archive
taskdef
Creates a new task definition and adds it to the current project
tempfile
Sets a temporary filename to an Ant property
tstamp
Sets time-based properties to the current time
typedef
Creates a new task or data type for use in the current project
unjar
Unpacks a JAR file
untar
Unpacks a TAR file
unwar
Unpacks a WAR file
unzip
Unpacks a ZIP file
uptodate
Sets a property value to true if a given target file is newer than a set of source files
waitfor
Halts a build and continues when specified conditions are met
war
Creates WAR archive files (an extension of the jar task)
whichresource
Locates a class or resource, either on the current class path or the system class path
xmlproperty
Loads Ant properties from an XML property file
xslt [style]
Transforms a set of documents via XSLT
zip
Creates and packs a new ZIP archive
Ant除了核心任务(Core Tasks)之外还可以使用可选任务,但使用可选任务时需要额外的jar库文件的支持,这些库文件需要存放在Ant的lib目录下。有了这些可选任务Ant可以做更多的事情,如ftp、编译.Net工程,使用ClearCase等。
l 工程属性(properties)是除了构建目标(target)、构建任务(tasks)之外的另一个Ant支柱,工程属性其实是一个名称-值对,可以在构建任务的XML元素中使用,使用方式为:${property-name}。工程属性的XML元素为property,其可用的XML属性为:
Attribute
Description
Required
classpath
The classpath to use when looking for a resource.
No
classpathref
The classpath to use when looking for a resource, which can then be given as a reference to a path element later in the build file.
No
environment
The prefix to use when retrieving environment variables. For example, if you specify environment="env", you will be able to access operating-system-specific environment variables as property names like ${env.PATH}.
A resource, file, url, or environment attribute is required when not using the name attribute.
file
The name of a property file to load values from.
A resource, file, url, or environment attribute is required when not using the name attribute.
location
Sets the property to the absolute filename of the given file. If an absolute path is supplied, it's left unchanged (with / and \ characters converted for the current platforms). Otherwise, the supplied filename is taken as a path relative to the project's base directory and then expanded.
A value, location, or refid element is required when using the name attribute.
name
The name of the property to set.
No
prefix
The prefix to add to properties loaded from a file or a resource. A . is appended to the prefix if none is specified.
No
refid
A reference to a (previously) defined object.
A value, location, or refid element is required when using the name attribute.
resource
The resource name of the property file, used for searching the classpath.
A resource, file, url, or environment attribute is required when not using the name attribute.
url
The URL from which to read properties.
A resource, file, url, or environment attribute is required when not using the name attribute.
value
The value of this property.
A value, location, or refid element is required when using the name attribute.
l Ant的内建属性:
ant.file
Contains the absolute path of the build file
ant.java.version
Contains the JVM version Ant is using (can hold only 1.1, 1.2, 1.3, 1.4 and [as of Ant 1.6] 1.5)
ant.project.name
Holds the name of the project that is executing (set with the name attribute of project)
ant.version
Contains the version of Ant running
basedir
Holds the absolute path of the project's base directory (set with the basedir attribute of project)
l Ant的运行:ant [options] [target [target2 [target3] ...]],在options中可以指定要执行的构建文件,默认为build.xml,如果构建文件为project.xml,则相应用ant命令为: ant –f project.xml,target可以指定多个,之间用空格分隔,如果未指定则使用构建文件中的默认目标。
第二章:Using Properties and Types
l Condition任务用于控制其他任务的执行:在Condition任务中设置属性值,而在其他任务中根据这些属性值的内容决定是否执行,如:
<condition property="all.set">
<and>
<available file="file1.java"/>
<available file="file2.java"/>
</and>
</condition>
这个任务用于判断file1.java和file2.java是否存在,如果都存在,则设置all.set属性为true,否则为false;
除了示例中出现的condition和and条件任务外还有available、or、equals等其他条件任务。
l 在任务中添加if或unless可以决定任务是否执行,继上例:
<target name="buildModule" if="all.set"/>
. . .
</target>
这个任务当all.set为true时执行,否则不执行。
l fail任务用于中断构建,如:
<fail message="Could not find all files." unless="all.set" />
当all.set为false时中断构建,并输出” Could not find all files.”
l 从文件装入属性:<property file="build.properties" />
l 将文件内容作为单个属性装入:
<loadfile property="message" srcFile="message.txt"/>
l 属性可以设置多次,后页的属性会覆盖前页的属性值。
l 通过命令行设置属性值:使用-D选项
ant -Dmessage="Compiling and compressing"
l 使用环境变量作为属性值,如:
<property environment="env" />
加上这句以后可以使用如下方式获取环境变量JAVA_HOME的值:
${env.JAVA_HOME},其他环境变量也通过类似方式获得。
l fileset用于指定文件集,并设置到属性中用于其他任务的构建,如文件复制、编译等,fileset的示例如下:
<fileset dir="${source}">
<include name="**/*.java"/>
<exclude name="**/*test*"/>
</fileset>
include用于包含文件,exclude用于排除文件,通配符**表示当前目录或当前目录下的所有子目录。除了使用include和exclude之外还可以使用filename来指定加入文件集的特定文件,如:
<fileset dir="${source}">
<filename name="**/*.java"/>
<filename name="test.cpp"/>
</fileset>
l 使用fileset的示例:
<copy todir="../dest">
<fileset dir="src">
<exclude name="**/*.java"/>
</fileset>
</copy>
这个任务将fileset中的文件复制到../dest目录下
l 相对于fileset还可以使用dirset表示目录集,使用与fileset类同。
第三章:Building Java Code
l javac任务用于编译java源代码,如:
<javac srcdir="${src}"
debug="on"
destdir="${bin}"
classpath="common.jar"
/>
l input任务可接收用户输入,如:
<target name="init">
<input
message="Deleting bin directory OK?"
validargs="y,n"
addproperty="do.delete"
/>
<condition property="do.abort">
<equals arg1="n" arg2="${do.delete}"/>
</condition>
<fail if="do.abort">Build aborted.</fail>
<delete dir="${output}" />
<mkdir dir="${output}" />
</target>
l 在同一构建文件中可以使用antcall任务执行另一个构建任务,并可指定构建参数作为构建属性,如:
<target name="main" depends="init, compile, compress">
<antcall target="displayMessage">
<param name="msg" value="${message}"/>
</antcall>
</target>
<target name="displayMessage">
<echo message="msg=${msg}"/>
</target>
在本例中main任务调用了displayMessage任务,并设置msg参数作为调用属性,在displayMessage任务中可以通过${msg}获取该属性值。
l 使用ant任务执行另一Ant构建文件,如:
<ant antfile="subproject/subbuild.xml">
<property name="parameter" value="4096"/>
<property file="config/subproject/build.properties"/>
</ant>
本例中执行了另一以subproject/subbuild.xml 为构建文件的Ant构建,将指定了构建的属性值,除此之外还可指定构建目标等其他选项。
l 使用import导入其他构建文件的内容,如:
<import file="shared.xml"/>
l 使用javadoc任务创建java文档,如:
<javadoc
sourcefiles="${src}/Project.java"
destdir="${docs}"
author="true"
version="true"
use="true"
windowtitle="Project API">
<doctitle><![CDATA[<h1>Project API</h1>]]></doctitle>
<bottom><![CDATA[<i>Copyright © 2005</i>]]></bottom>
</javadoc>
l 使用jar任务创建jar包,如:
<jar destfile="${output}/Project.jar" basedir="${output}"
includes="*.class" >
<manifest>
<attribute name="Author" value="${user.name}"/>
<section name="Shared">
<attribute name="Title" value="Example"/>
<attribute name="Vendor" value="MegaAntCo"/>
</section>
<section name="Copyright">
<attribute name="Copy" value="(C) MegaAntCo 2005"/>
</section>
</manifest>
</jar>
l 使用buildnumber任务读取并创建构建序号,buildnumber从文件 (默认为build.number) 中读取原构建序号并存到build.number属性中,在成功构建后加1写回到文件中。Buildnumber的file属性用于指定存放构建序号的文件。
l 使用tstamp任务设置时间属性,有3个属性被设置,分别为DSTAMP,格式为” yyyyMMdd”; TSTAMP,格式为”hhmm”; TODAY,格式为”MM dd yyyy”。Tstamp的子任务format可以设置时间的格式,如:
<tstamp>
<format property="timestamp" pattern="MM/dd/yyyy hh:mm:ss"/>
</tstamp>
第四章:Deploying Builds
l 使用tar任务创建tar文件,如:
<tar
destfile="${output}/Project.tar.gz"
basedir="${output}"
includes="*.class"
compression="gzip"/>
l 删除已存在的文件:<delete file="/lib/Project.jar"/>
l 删除已存在的目录:<delete dir="${dist}"/>
l 创建目录:<mkdir dir="${dist}"/>
l copy任务用于复制文件或目录。
l move任务用于移动文件或目录。
l 使用ftp发送或接收文件,如:
<ftp server="xxx.xxx.xxx.xxx" binary="true" verbose="true"
userid="${name}" password="${password}"
remotedir="/cgi-bin" action=”send” >
<fileset dir="${output}">
<exclude name="*.java"/>
<exclude name="*.class"/>
<exclude name="*.txt"/>
</fileset>
</ftp>
ftp的action包括:put, get,
del, list, chmod, mkdir and rmdir
l 使用telnet,如:
<telnet userid="steven" password="let_me_in"
server="xxx.xxx.xxx.xxx">
<read>/home/steven</read>
<write>ls</write>
</telnet>
l 使用SSH,如:
<sshexec host="xxx.xxx.xxx.xxx"
username="${name}"
password="${password}"
command="touch index.html"/>
l 使用email,如:
<mail mailhost="smtp.isp.com" mailport="1025" subject="New Build">
<from address="developer@isp.com"/>
<replyto address="developer@isp.com"/>
<to address="list@xyz.com"/>
<message>Here is the new build.</message>
<fileset dir="dist">
<includes name="**/*.tar.gz"/>
</fileset>
</mail>
l 自动构建:可以使用Windows的计划任务,或Anthill工具进行自动构建。
第六章:Getting Source Code from CVS Repositories
l 登入(login):
<cvspass
cvsroot=":pserver:steven@STEVE:/home/steven/repository"
password="opensesame" />
l 检出(check out):
<cvs package="GreetingApp" dest="${cvs.dir}" />
l 更新(update):
<cvs dest="${cvs.dir}" command="update"/>
l 提交(commit):
<cvs dest="${cvs.dir}/GreetingApp"
command="commit -m 'New Version'"/>
l 创建更新日志(change log):
<cvschangelog dir="${cvs.dir}/GreetingApp"
destfile="changelog.xml" />
第七章:Executing External Programs
l 执行Java代码,如:
<java jar="${bin}/connect.jar"
fork="true"
failonerror="true"
maxmemory="512m"
>
<arg value="-q"/>
<classpath>
<pathelement location="${bin}/connect.jar"/>
<pathelement path="${java.class.path}"/>
</classpath>
</java>
l exec任务用于执行系统命令或外部程序,如:
<exec dir="." executable="/bin/cpp.exe"
failonerror="true">
<arg line="-c ${src}/*.cpp ${output}"/>
</exec>
l 用apply任务执行批处理,apply与exec的差别是apply接收fileset,这样可以对多个文件或输入执行相同中的命令或程序。
l 用parallel可执行多线程任务。