# Using Ant

## Writing a Simple Buildfile

Ant's buildfiles are written in XML. Each buildfile contains one project and at least one (default) target. Targets contain task elements. Each task element of the buildfile can have an `id` attribute and can later be referred to by the value supplied to this. The value has to be unique. (For additional information, see the Tasks section below.)

### Projects

A project has three attributes:

Attribute | Description | Required
name | the name of the project. | No
default | the default target to use when no target is supplied. | Yes.
basedir | the base directory from which all path calculations are done. This attribute might be overridden by setting the "basedir" property beforehand. When this is done, it must be omitted in the project tag. If neither the attribute nor the property have been set, the parent directory of the buildfile will be used. | No

Optionally, a description for the project can be provided as a top-level `<description>` element (see the description type).

Each project defines one or more targets. A target is a set of tasks you want to be executed. When starting Ant, you can select which target(s) you want to have executed. When no target is given, the project's default is used.

### Targets

A target can depend on other targets. You might have a target for compiling, for example, and a target for creating a distributable. You can only build a distributable when you have compiled first, so the distribute target depends on the compile target. Ant resolves these dependencies.

It should be noted, however, that Ant's `depends` attribute only specifies the order in which targets should be executed - it does not affect whether the target that specifies the dependency(s) gets executed if the dependent target(s) did not (need to) run.

Ant tries to execute the targets in the `depends` attribute in the order they appear (from left to right). Keep in mind that it is possible that a target can get executed earlier when an earlier target depends on it:

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

Suppose we want to execute target D. From its `depends` attribute, you might think that first target C, then B and then A is executed. Wrong! C depends on B, and B depends on A, so first A is executed, then B, then C, and finally D.

A target gets executed only once, even when more than one target depends on it (see the previous example).

A target also has the ability to perform its execution if (or unless) a property has been set. This allows, for example, better control on the building process depending on the state of the system (java version, OS, command-line property defines, etc.). To make a target sense this property, you should add the `if` (or `unless`) attribute with the name of the property that the target should react to. Note: Ant will only check whether the property has been set, the value doesn't matter. A property set to the empty string is still an existing property. For example:

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

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

In the first example, if the `module-A-present` property is set (to any value), the target will be run. In the second example, if the `module-A-present` property is set (again, to any value), the target will not be run.

If no `if` and no `unless` attribute is present, the target will always be executed.

The optional `description` attribute can be used to provide a one-line description of this target, which is printed by the `-projecthelp` command-line option. Targets without such a description are deemed internal and will not be listed, unless either the `-verbose` or `-debug` option is used.

It is a good practice to place your tstamp tasks in a so-called initialization target, on which all other targets depend. Make sure that target is always the first one in the depends list of the other targets. In this manual, most initialization targets have the name `"init"`.

If the depends attribute and the if/unless attribute are set, the depends attribute is executed first.

A target has the following attributes:

Attribute | Description | Required
name | the name of the target. | Yes
depends | a comma-separated list of names of targets on which this target depends. | No
if | the name of the property that must be set in order for this target to execute. | No
unless | the name of the property that must not be set in order for this target to execute. | No
description | a short description of this target's function. | 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`.

### 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.1", "1.2", "1.3" and "1.4".

### Example Buildfile

    <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.

### Token Filters

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, DirSets, FileSets, and FileLists can be specified via nested `<dirset>`, `<fileset>`, and `<filelist>` elements, respectively. Note: The order in which the files building up a FileSet are added to the path-like structure is not defined.

        <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 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.

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

represents two separate command-line arguments.

>       <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

The `id` attribute of the buildfile's elements can be used to refer to them. 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 well.

Copyright © 2000-2004 The Apache Software Foundation. All rights Reserved.