How to make an Ant script fail gracefully if a property file doesn't exist

Wow, I just realized that until this morning I hadn't done anything new with Ant in several months. It sure is nice when things just work. :)

This morning I made several modifications to the build process for a system I'm working on, and one of the nice changes I made is that the build process now fails early if it can't find a property file that is required for the rest of the build. I decided to add this safety check after showing other people how to create a build, and then realizing that the first thing they would probably do is forget to create a properties file that is specific to their machine/environment.

So, here's a source code example from the beginning portion of an Ant build script where I'm looking for a specific property file, and then I make the build intentionally fail right away if the file can't be found:

<property environment="env" />
<property name="build.dir" value="build" />
<property file="${build.dir}/build.${env.BUILD_TARGET}" />

<available file="${build.dir}/build.${env.BUILD_TARGET}" property="isFileAvail" />
<fail unless="isFileAvail" message="The build properties file does not exist, can't build. Is BUILD_TARGET set?" />

The way this works is that you have to specify the environment variable BUILD_TARGET before you run the ant command. In my world, this variable will either be DEV, TEST, or PROD, and after today's change, if you want this script to run at all, you better have a corresponding file in your build directory named build.DEV, build.TEST, or build.PROD.

Specifically, on a Windows system, when running my build process from a cmd window, you first specify the build environment like this:


Then when you want to run your unit tests you run

ant test

and when you're ready to deploy your project you run

ant target