Marty Andrews

artful code

Thursday, July 8, 2004

Maintainability in Ant build scripts

I've worked on dozens of projects that used Ant build scripts, with team sizes ranging from just me to tens of developers. Big projects tend to have big Ant scripts, and they can be a maintenance nightmare. I've developed a structural style for scripts that I find easier to maintain and explain on larger projects.

Take the following Ant script as a typical example.

<project name="foo" basedir="." default="test"><target name="init" description="Prepare directories for build">...</target><target name="compile" depends="init" description="Compiles code">...</target><target name="test" depends="compile" description="Tests code">...</target></project>

The script has only three targets in it. All targets have a description, and two of them have a dependancy on another target. Those descriptions and dependancies are scattered throughout the file. It is possible to discover the descriptions of targets publicly available by running ant -projecthelp, and the dependancies will be seen when the script runs, but neither are easily viewable at a glance. This is especially true when your Ant script has grown to hundreds of lines and tens of targets.

Here's the same script modified to follow my different convention

<project name="foo" basedir="." default="test"><target name="-init">...</target><target name="-compile">...</target><target name="-test">...</target><!-- Private targets used only for dependancies --><target name="--init"    depends="-init"/><target name="--compile" depends="-init,-compile"/><target name="--test"    depends="--compile,-test"><!-- Public targets with description --><target name="init"    depends="--init"    description="Prepare directories for build"><target name="compile" depends="--compile" description="Compiles code"><target name="test"    depends="--test"    description="Tests code"></project>

Most of the targets in this script are now "private" targets. Basically - anything that starts with a hyphen can't be run on the command line by Ant, as it thinks you are passing a parameter to the Ant script rather than specifying a target. None of these private targets have any dependancies or descriptions.

All dependancies between targets can be seen at a glance in one section. They are again all listed on private targets, but these ones do no work other than describing dependancies.

All descriptions can be seen at a glance in one section. They are listed on public targets, and delegate to a single other private target which handles the dependancies for it.

Thats all there is to it really. The purist in me doesn't like it, because the test target really does depend on the compile target, so thats where it should be listed. My pragmatic side almost always wins though, and I've seen enough confusion in Ant scripts to adopt this pattern for all my new builds.

No comments:

Post a Comment