Wednesday, November 7, 2007

Ant <echoproperties /> Task

I have always found it useful when writing Ant build.xml files to have a task that prints out the properties that I use in that script. This helps me to determine if any of the properties are undefined or defined incorrectly. I have typically used the <echo> tag with the message attribute for each property. However, I realized recently when reading The Elements of Ant Style that this can be much easier using the echoproperties tag.

When used directly without any attributes or nested tags, all properties (general Java and Ant properties as well as locally defined project-specific properties) are listed. Because this can sometimes be a little too much information, it is useful that the echoproperties tag has the prefix attribute to narrow down the returned properties to those starting with the specified prefix. One limitation to using the prefix tag is that only one such prefix can be declared in an XML attribute. To declare multiple prefixes for which properties should be displayed, you can use the propertyset nested tag.

The following code listing shows an example of a build.xml file that uses the echoproperties tag and shows off a few of its features.

<?xml version="1.0" encoding="UTF-8"?>

<project name="EchoPropertiesExample" default="echoAll" basedir=".">
  <property environment="env" />

  <target name="echoAll"
          description="Echo all properties I access.">
    <echoproperties />
  <target name="echoJava"
          description="Echo my properties that begin with java.">
    <echoproperties prefix="java" />
  <target name="echoAnt"
          description="Echo my properties that begin with ant.">
    <echoproperties prefix="ant" />

  <target name="echoAntAndJava"
          description="Echo Ant and Java properties">
        <propertyref prefix="java" />
        <propertyref prefix="ant" />

  <target name="echoAllXml"
          description="Echo all properties in XML format">
    <echoproperties format="xml" />


The last target example in the above build.xml file demonstrates how to use the format attribute set to xml to have the properties output to XML rather than the default text format. This is usually most useful when used in conjunction with the destfile attribute to specify a file to which the XML output is written.

Displaying the properties available to a particular Ant build.xml file is useful in ensuring that build are configured and working properly and the <echoproperties /> task makes this trivial.

In a previous blog entry, I discussed using Ant to reveal Java and Ant properties that are available in a given environment, but using <echoproperties /> is a more convenient method for doing this than explicitly creating individual <echo .../> tasks for each property.

No comments: