Skip to content



Removing duplication from ant build files

Once I started getting my ant build script to work for both my development and production environment, I started getting some (evil) duplication in it.

build.xml

<?xml version="1.0"?>
<project name="some-project" basedir=".">
<property name="dev-deploy.path"
value="./lib/apache-tomcat-6.0.18/webapps">
<property name="prod-deploy.path"
value="/usr/share/apache-tomcat-6.0.16/webapps">

<target name="copy-dev-war"
 depends="build" description="copy WAR to webapps directory">
<copy todir="${dev-deploy.path}" preservelastmodified="true">
<fileset dir=".">
<include name="*.war"/>
</fileset>
</copy>
</target>

<target name="copy-prod-war"
depends="build" description=" copy WAR to webapps directory ">
<copy todir="${prod-deploy.path}" preservelastmodified="true">
<fileset dir=".">
<include name="*.war"/>
</fileset>
</copy>
</target>

</project>

As you can see the copy-dev-war and copy-prod-war targets are the same, except for the ${xxx-deploy-path} which is different for each. I couldn’t live with this. How do you get rid of the duplication and have just one target?

Create a build for each environment, which declares (or includes) specific environment properties, and then include a common file that holds the generic ant targets.

build-prod.xml

<?xml version="1.0"?>
<project name="some-project-prod" basedir=".">
<property name="deploy.path" value="/usr/share/apache-tomcat-6.0.16/webapps"/>
<import file="build-general.xml"/>
</project>


build-dev.xml

<?xml version="1.0"?>
<project name="smn-stock-prices-dev" basedir=".">
<property name="deploy.path" value="./lib/apache-tomcat-6.0.18/webapps"/>
<import file="build-general.xml"/>
</project>

build-general.xml

<?xml version="1.0"?>
<project name="some-project" basedir=".">
<target name="copy-war" depends="build" description="copy WAR to webapps directory">
<copy todir="${deploy.path}" preservelastmodified="true">
<fileset dir=".">
<include name="*.war"/>
</fileset>
</copy>
</target>
</project>

Now I can breathe ok. In this way I was able to remove several duplicate ant targets and significantly slim it down. Besides, adding a new deployment environment would just involve creating a build file which declares its environment specific properties, and then includes the generic build.xml

I also found some very useful tips in the ThoughtWorks Anthology book. See the chapter on “Refactoring ant build files” by Julian Simpson

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*