Wednesday, September 15, 2010

Apache Ant - How to find empty directories

To find out empty directories just using standard Ant tasks is not a trivial job. Here I'll show you how this can be accomplished applying a technique that involves an accurate use of <copy> task and <present> selector.

Let's take a look at the following script excerpt:
<property name="dirToCheck" value="c:/temp"/>

<copy todir="${java.io.tmpdir}/_copy_" includeEmptyDirs="false">
<fileset dir="${dirToCheck}"/>
</copy>

<dirset dir="${dirToCheck}" id="emptyDirs">
<present present="srconly" targetdir="${java.io.tmpdir}/_copy_"/>
</dirset>
In the previous code we want to check for empty directories starting from a base directory identified by property named "dirToCheck".

The idea is to use the <copy> task to clone the directory structure into a temp dir (${java.io.tmpdir}/_copy_) without including empty directories (includeEmptyDirs="false"). This way we get a clone of the original directory structure without its empty directories.

Empty directories can now appear from the comparison between the original directory structure and the cloned one: they simply emerge as those directories that are present only in the original structure, as the <present> selector shows.

No comments: