# Properties

Properties are key-value-pairs where Apache Ant tries to expand `${key}` to `value` at runtime.

There are many tasks that can set properties, the most common one is the property task. In addition properties can be defined via command line arguments or similar mechanisms from outside of Ant.

Normally property values can not be changed, once a property is set, most tasks will not allow its value to be modified. In general properties are of global scope, i.e. once they have been defined they are available for any task or target invoked subsequently - it is not possible to set a property in a child build process created via the ant, antcall or subant tasks and make it available to the calling build process, though.

Starting with Ant 1.8.0 the local task can be used to create properties that are locally scoped to a target or a sequential element like the one of the macrodef task.

## 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.project.default-target
                        the name of the currently executing project's
                        default target;  it is set via the default
                        attribute of <project>.
    ant.project.invoked-targets
                        a comma separated list of the targets that have
                        been specified on the command line (the IDE,
                        an <ant> task ...) when invoking the current
                        project.
                        This property is set when the first target is executed.
                        So you can't use it in the implicit target (directly
                        under the <project> tag).
    ant.java.version    the JVM version Ant detected; currently it can hold
                        the values "1.7", "1.6", "1.5",
                        "1.4",  "1.3" and "1.2".
    ant.core.lib        the absolute path of the ant.jar file.

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

The following property is only set if Ant is started via the Launcher class (which means it may not be set inside IDEs either):

    ant.library.dir     the directory that has been used to load Ant's
                        jars from.  In most cases this is ANT_HOME/lib.

# PropertyHelpers

Ant's property handling is accomplished by an instance of `org.apache.tools.ant.PropertyHelper` associated with the current Project. You can learn more about this class by examining Ant's Java API. In Ant 1.8 the PropertyHelper class was much reworked and now itself employs a number of helper classes (actually instances of the `org.apache.tools.ant.PropertyHelper$Delegate` marker interface) to take care of discrete tasks such as property setting, retrieval, parsing, etc. This makes Ant's property handling highly extensible; also of interest is the new propertyhelper task used to manipulate the PropertyHelper and its delegates from the context of the Ant buildfile.

There are three sub-interfaces of `Delegate` that may be useful to implement.

- `org.apache.tools.ant.property.PropertyExpander` is responsible for finding the property name inside a string in the first place (the default extracts `foo` from `${foo}`).

  This is the interface you'd implement if you wanted to invent your own property syntax - or allow nested property expansions since the default implementation doesn't balance braces (see `NestedPropertyExpander` in the "props" Antlib for an example).

- `org.apache.tools.ant.PropertyHelper$PropertyEvaluator` is used to expand `${some-string}` into an `Object`.

  This is the interface you'd implement if you want to provide your own storage independent of Ant's project instance - the interface represents the reading end. An example for this would be `org.apache.tools.ant.property.LocalProperties` which implements storage for local properties.

  Another reason to implement this interface is if you wanted to provide your own "property protocol" like expanding `toString:foo` by looking up the project reference foo and invoking `toString()` on it (which is already implemented in Ant, see below).

- `org.apache.tools.ant.PropertyHelper$PropertySetter` is responsible for setting properties.

  This is the interface you'd implement if you want to provide your own storage independent of Ant's project instance - the interface represents the reading end. An example for this would be `org.apache.tools.ant.property.LocalProperties` which implements storage for local properties.

The default `PropertyExpander` looks similar to:

    public class DefaultExpander implements PropertyExpander {
        public String parsePropertyName(String s, ParsePosition pos,
                                        ParseNextProperty notUsed) {
            int index = pos.getIndex();
            if (s.indexOf("${", index) == index) {
                int end = s.indexOf('}', index);
                if (end < 0) {
                    throw new BuildException("Syntax error in property: " + s);
                }
                int start = index + 2;
                pos.setIndex(end + 1);
                return s.substring(start, end);
            }
            return null;
        }
    }

The logic that replaces `${toString:some-id}` with the stringified representation of the object with id `some-id` inside the current build is contained in a PropertyEvaluator similar to the following code:

    public class ToStringEvaluator implements PropertyHelper.PropertyEvaluator {
        private static final String prefix = "toString:";
        public Object evaluate(String property, PropertyHelper propertyHelper) {
            Object o = null;
            if (property.startsWith(prefix) && propertyHelper.getProject() != null) {
                o = propertyHelper.getProject().getReference(
                        property.substring(prefix.length()));
            }
            return o == null ? null : o.toString();
        }
    }

# Property Expansion

When Ant encounters a construct `${some-text}` the exact parsing semantics are subject to the configured property helper delegates.

## `$$` Expansion

In its default configuration Ant will expand the text `$$` to a single `$` and suppress the normal property expansion mechanism for the text immediately following it, i.e. `$${key}` expands to `${key}` and not `value` even though a property named `key` was defined and had the value `value`. This can be used to escape literal `$` characters and is useful in constructs that only look like property expansions or when you want to provide diagnostic output like in

      <echo>$${builddir}=${builddir}</echo>

which will echo this message:

      ${builddir}=build/classes

if the property `builddir` has the value `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 "$$".

## Nesting of Braces

In its default configuration Ant will not try to balance braces in property expansions, it will only consume the text up to the first closing brace when creating a property name. I.e. when expanding something like `${a${b}}` it will be translated into two parts:

1. the expansion of property `a${b` - likely nothing useful.
2. the literal text `}` resulting from the second closing brace

This means you can't use easily expand properties whose names are given by properties, but there are some workarounds for older versions of Ant. With Ant 1.8.0 and the the props Antlib you can configure Ant to use the `NestedPropertyExpander` defined there if you need such a feature.

## Expanding a "Property Name"

In its most simple form `${key}` is supposed to look up a property named `key` and expand to the value of the property. Additional `PropertyEvaluator`s may result in a different interpretation of `key`, though.

The props Antlib provides a few interesting evaluators but there are also a few built-in ones.

### Getting the value of a Reference with ${toString:}

Any Ant type which has been declared with a reference can also its string value extracted by using the `${toString:}` operation, with the name of the reference listed after the `toString:` text. The `toString()` method of the Java class instance that is referenced is invoked -all built in types strive to produce useful and relevant output in such an instance.

For example, here is how to get a listing of the files in a fileset,

    <fileset id="sourcefiles" dir="src" includes="**/*.java" />
    <echo> sourcefiles = ${toString:sourcefiles} </echo>

There is no guarantee that external types provide meaningful information in such a situation

### Getting the value of a Reference with ${ant.refid:}

Any Ant type which has been declared with a reference can also be used as a property by using the `${ant.refid:}` operation, with the name of the reference listed after the `ant.refid:` text. The difference between this operation and `${toString:}` is that `${ant.refid:}` will expand to the referenced object itself. In most circumstances the toString method will be invoked anyway, for example if the `${ant.refid:}` is surrounded by other text.

This syntax is most useful when using a task with attribute setters that accept objects other than String. For example if the setter accepts a Resource object as in

    public void setAttr(Resource r) { ... }

then the syntax can be used to pass in resource subclasses previously defined as references like

      <url url="http://ant.apache.org/" id="anturl"/>
      <my:task attr="${ant.refid:anturl}"/>

## If/Unless Attributes

The `<target>` element and various tasks (such as `<fail>`) and task elements (such as `<test>` in `<junit>`) support `if` and `unless` attributes which can be used to control whether the item is run or otherwise takes effect.

In Ant 1.7.1 and earlier, these attributes could only be property names. The item was enabled if a property with that name was defined - even to be the empty string or `false` - and disabled if the property was not defined. For example, the following works but there is no way to override the file existence check negatively (only positively):

    <target name="-check-use-file">
        <available property="file.exists" file="some-file"/>
    </target>
    <target name="use-file" depends="-check-use-file" if="file.exists">
        <!-- do something requiring that file... -->
    </target>
    <target name="lots-of-stuff" depends="use-file,other-unconditional-stuff"/>

As of Ant 1.8.0, you may instead use property expansion; a value of `true` (or `on` or `yes`) will enable the item, while `false` (or `off` or `no`) will disable it. Other values are still assumed to be property names and so the item is enabled only if the named property is defined.

Compared to the older style, this gives you additional flexibility, because you can override the condition from the command line or parent scripts:

    <target name="-check-use-file" unless="file.exists">
        <available property="file.exists" file="some-file"/>
    </target>
    <target name="use-file" depends="-check-use-file" if="${file.exists}">
        <!-- do something requiring that file... -->
    </target>
    <target name="lots-of-stuff" depends="use-file,other-unconditional-stuff"/>

Now `ant -Dfile.exists=false lots-of-stuff` will run `other-unconditional-stuff` but not `use-file`, as you might expect, and you can disable the condition from another script too:

    <antcall target="lots-of-stuff">
        <param name="file.exists" value="false"/>
    </antcall>

Similarly, an `unless` attribute disables the item if it is either the name of property which is defined, or if it evaluates to a `true`-like value. For example, the following allows you to define `skip.printing.message=true` in `my-prefs.properties` with the results you might expect:

    <property file="my-prefs.properties"/>
    <target name="print-message" unless="${skip.printing.message}">
        <echo>hello!</echo>
    </target>