3.4 Providing Help

3.4.1 Problem

You want to provide help messages in your buildfiles.

3.4.2 Solution

Include a description attribute on the <project> and <target> tags. Also consider writing a help target, and use XML comments throughout the buildfile.

3.4.3 Discussion

Example 3-2 shows several techniques for providing additional help in Ant buildfiles. In this example, the help target is listed as the default target and is executed when the user types ant at the command line.

Example 3-2. Various ways to provide help
<?xml version="1.0"?>

<!-- You can document the buildfile using XML comments -->
<project name="My Big Project" default="help" basedir=".">
  <description>Shows how to provide help in an Ant buildfile.</description>

  <property name="dir.src" value="src"/>

  <target name="help">
    <echo message="This buildfile shows how to get help."/>
    <echo>(Type 'ant -projecthelp' for more info)</echo>
       Here is a block of text
       that you want to format
       in a very specific way!]]></echo>

  <!-- Here is an example of a subtarget -->
  <target name="prepare">
    <mkdir dir="${dir.build}"/>
    <mkdir dir="${dir.dist}"/>

  <!-- Here is an example of a main target -->
  <target name="clean"
          description="Remove all generated files.">
    <delete dir="${dir.build}"/>
    <delete dir="${dir.dist}"/>

  <target name="compile" depends="prepare"
          description="Compile all source code.">
    <javac srcdir="${dir.src}" destdir="${dir.build}"/>

The help target uses the echo task to print some usage information for Ant beginners. It reminds the user of the -projecthelp option, and uses an XML CDATA section to format a paragraph of text. CDATA sections are useful whenever you want to preserve linefeeds, spaces, and other characters precisely. CDATA is also useful because it allows you to print special XML characters like "<" without using entities like "&lt;".

Providing target descriptions is very useful:

<target name="clean"
        description="Remove all generated files.">

These descriptions are displayed when the user types ant -projecthelp. Targets with descriptions are displayed as main targets, while those without descriptions are called subtargets, and are only displayed if you also include the -verbose command-line flag. Because of the distinction between main targets and subtargets, you should only define description attributes for targets you want the user to actually use.

3.4.4 See Also

Recipe 3.7 shows how to use the fail task to abort the build if a property is not set.