provides software and services that enable enterprises
Live Chat 1-888-673-6564

Open Source Software Technical Articles

  • Home
  • Search
  • Contact Us
  • Products and Support
  • Services
  • Enterprise OSS Blog
  • Wazi Technical Blog
  • About Wazi
  • Attributions and Licensing
  • Supply Chain Compliance
  • How to Contribute
  • Contributors
  • Resources Library
  • Cloud Services
  • Partners
  • Customers
  • Community
  • Company
  • Careers
  • News and Events

Subscribe to Wazi by Email

Your email:


Enterprise Developer Support 24 x 7, Get a Support Quote Now!


click-here-to-chat-with-an-online-representative

download-oss-discovery

Latest Posts

  • The secret to great reporting with Drupal 7
  • A more colorful LibreOffice unveiled
  • Toward a more colorful LibreOffice
  • Flexible administration with Puppet's Facter and templates
  • Knock for OpenSSH
  • Get more out of phpMyAdmin
  • Image annotation in GIMP, Dia, and OpenOffice Draw
  • Solr, Drupal 7, and faceted search
  • Using FreeNAS' new full disk encryption for ZFS
  • Create distributed storage with Gluster

Connect with Us!

Current Articles | RSS Feed RSS Feed

Ant buildfiles: A look under the carapace

Posted by Juliet Kemp on Thu, Feb 28, 2013
  
Email This Email Article  
Tweet  
  

You may already use the Apache Ant Java-based build tool to build projects with a presupplied build.xml file. But what if you want to do something more complicated? Knowing how Ant works under the hood will let you make the most of its capabilities. Let's dissect an Ant buildfile and examine its components.

Ant operates in a different way than other command-line build tools. Instead of using shell commands to extend your tool, you extend Ant by writing Java classes to run particular tasks – although Ant comes with a huge list of available tasks. Instead of constructing a shell command to run a particular task configuration, you configure Ant in XML files. The XML creates a tree of tasks to be executed to build particular defined targets, and each task is run by its own object. The crucial implication of this is that Ant is entirely cross-platform, unlike make and its ilk.

I'll assume that you already have Ant installed for this tutorial; if not, get it from its website or your package manager.

Basic Ant building

If you just type ant on the command line in an empty directory, you'll get an error message telling you that there's no build.xml file. build.xml is the file Ant needs in order to know what it's supposed to do. Let's look at the structure of a basic buildfile:

<?xml version="1.0" encoding="UTF-8"?>
<project name="HelloAnt" default="compile" basedir=".">
  <property name="src.dir" value="."/>
  <property name="build.dir" value="build/"/>

  <target name="clean">
     <echo>Cleaning up ${build.dir}</echo>
     <delete dir="${build.dir}"/>
  </target>

  <target name="init" depends="clean">
     <echo>Creating build directory ${build.dir}</echo>
     <mkdir dir="${build.dir}"/>
  </target>

  <target name="compile" depends="init">
     <echo>Compiling source from ${src.dir} to ${build.dir}</echo>
     <javac srcdir="${src.dir}" destdir="${build.dir}"/>
  </target>
</project>

The root element for an Ant buildfile is project: the rest of the file forms part of this element. The project element itself has a name, default target, and base directory, none of which are required. The buildfile then defines source and build directory properties, which it refers to later in the file. This means that if you change your directory structure, you only need to alter one place in the file. The actual work is done by three targets: clean (which deletes the build directory), init (which recreates the build directory), and compile.

Each target comprises a number of tasks. Ant has a huge list of built-in tasks available, and you can define more of your own by writing a Java file, though here we're just using built-in ones. echo, delete, mkdir, and javac all do what you'd expect; you can check out the documentation for more information. Note that the javac task will fail if the destination directory doesn't already exist, hence the need to create it in the init target.

You'll also notice the depends attribute on two of the tasks. This sets up a chain of tasks; if you tell Ant to execute Task 1 which is dependent on Task 2, Ant will run Task 2 for you first. You can also chain multiple dependencies, as here, where compile depends on init which depends on clean. They'll all be executed in the correct order. Tasks can also have multiple dependencies, and Ant will sort out everything for you.

To test this buildfile, create a basic HelloWorld.java file in your base directory, then type ant. Since our default target is compile, it should clean, init, and compile your program.

Properties

Instead of having all the properties at the start of build.xml, you can instead keep them in a properties file. This is usually called build.properties, and ours would look like this:

 
src.dir=. 
build.dir=build
test.dir=${build.dir}/test

As you can see, you can refer to earlier properties within the file itself. You then include this build.properties file in build.xml:

<project name="HelloAndroid" default="help">
  <property file="build.properties"/>
  ...
</project>

This modular structure is more maintainable when you have a significant number of properties, so it's good to get into the habit of using it.

You can also override properties on the command line. Try this command (note the lack of a space between the flag and the value):

ant -Dbuild.dir=test

Your project will be rebuilt into test/. Note that in this case, the old classfiles in build/ will not be deleted, because the clean target will be run on test/ instead.

More on targets

Ant lets you create "hidden" targets. For example, let's add a couple of targets:

<project name="HelloAnt" basedir="." default="compile">
  ...
  <property name="jar.dir" value="jar/"/>
  <property name="jar.jarfile" value="HelloAnt.jar"/>

  ...

  <target name="-jarinit">   
    <tstamp>   
      <format property="TODAY_UK" pattern="yyyy-MM-dd_HH.mm" locale="en_GB" />
    </tstamp>   
  </target>   

  <target name="jar" depends="-jarinit"   
          description="Creates the binary distribution.">   
    <mkdir dir="${jar.dir}/${TODAY_UK}" />   
    <jar basedir="${build.dir}"   
         destfile="${jar.dir}/${TODAY_UK}/${jar.jarfile}" />   
  </target>   
</project>

The target -jarinit can't be called from the command line, which makes sense, as all it does is to set up a property, TODAY_UK, which is a timestamp with a particular format. However, the target jar, which can be called from the command line, depends on -jarinit, which sets up the directory the jar file will be saved in. If you remove that depends="-jarinit" attribute, the task will still run, but it'll use the directory ${TODAY_UK} rather than substituting in the property. (This is one property that has to stay in build.xml rather than build.properties.)

In fact, jar really should depend on compile as well as jarinit, since you can't create a jarfile from a nonexistent build directory and don't want to create one from an old build directory! Change the depends property to read depends="-jarinit,compile" and run ant jar again. You'll see Ant run -jarinit, then traverse the tree of tasks to run clean, init, compile, and then jar.

Help!

Now try typing ant -projecthelp. You should get output like this:

 
Buildfile: /home/juliet/coding/ant/build.xml

Main targets:

 jar  Creates the binary distribution. 
Default target: compile

Only one of our tasks shows up! This is because the jar task is the only one with a description property. Add descriptions to the other tasks, and try ant -projecthelp again:

 
Buildfile: /Users/juliet/coding/ant/build.xml

Main targets:

 -jarinit  Creates a timestamp.
 clean     Cleans up old build directory.
 compile   Compiles source.
 init      Creates build directory.
 jar       Creates the binary distribution. 
Default target: compile

Note that even the hidden task will show up if you give it a description.

It's also good practice to create a help target – something like this:

<target name="help" depends="usage" />   

<target name="usage" description="Display usage information.">   
  <echo message="  Execute 'ant -projecthelp' for build file help." />   
  <echo message="  Execute 'ant -help' for Ant help." />   
</target>

This shows another feature of Ant targets: You can have a "target alias," meaning a target that only invokes another target. Here, all help does is invoke usage. This means that the user will get help from either ant help or ant usage. You could also alias build to compile, for example. This also shows another way of using the echo task.

It's good practice to change your default to help or to something else that doesn't do much; if you make the default be compile, a user may be unhappy when Ant blows away old build files, or takes ages to run for a large project.

This tutorial should give you enough information to get started editing an Ant build.xml file if you want to tweak your builds a little. Once you feel comfortable, you can also try setting up an Ant file for other tasks you do regularly; there's no need to limit yourself to Java compilation!

Follow @openlogic
Follow @OSCloudServices

This work is licensed under a Creative Commons Attribution 3.0 Unported License
Creative Commons License.
Tags: Ant, Technical, Tutorial, make

Comments

Currently, there are no comments. Be the first to post one!
Post Comment
Name
 *
Email
 *
Website (optional)
Comment
 *

Allowed tags: <a> link, <b> bold, <i> italics

Loading...
Error sending email
Email sent successfully

Email article
Email To : 
Your name : 
Message : (maximum 200 characters)
Home | Search | Contact Us | Products and Support | Services | Enterprise OSS Blog | Wazi Technical Blog | Resources Library | Cloud Services | Partners | Customers | Community | Company | Careers | News and Events
Products
OpenLogic Exchange (OLEX)
License Compliance Module
OSS Discovery
OSS Deep Discovery
OpenUpdate
Services
Open Source Support
CentOS Support
Scanning & Compliance
Open Source Training
Professional Services
Solutions
Support & Indemnification
Open Source Governance
Open Source Scanning
Open Source Provisioning
Consulting & Training
Contact Us
1-888-673-6564


© 2013 OpenLogic, Inc. All rights reserved.
Site Map  |  Privacy Policy