views:

977

answers:

2

Does anyone know how to recursively delete "empty" directories with ANT (empty includes directories that only contain ".svn" etc).

I know ant allows you to "includeEmptyDirs=true" but I want it to ONLY delete a directory if it is empty (and actually I'd probably need to walk up the recursive chain and delete the directory it was contained in if it is now empty).

Basically as part of our build process we copy over a set of directories that contain a bunch of other nested directories containing various XML and data, and when we move the location for that data our "copy" and checkin build process doesn't really work, and because we are checking into another source control (SVN), wiping out the directories and copying over isn't really an option either (we'd be blowing away the ".svn" folders).

Before we copy over the new builds I can "clear" out the directories by doing the following:

<delete>
  <fileset dir="${webplatformBin}" includes="**/*"/>
</delete>

This leaves every directory (with the ".svn") as an empty directory and then I copy over the new files. After they're copied I'm not sure how I can clear out the empty directories that are left (if we've completely moved where the top-level data directory is etc.).

For example if I had a /projectA/data/localization/text.xml file and I moved it to /projectB/data/localization/text.xml, I would end up with an empty folder /projectA/data/localization/ (that would only contain a .svn folder).

A: 

If it is not sufficient to completely clear the target location (use defaultExcludes="false" to ensure the .svn folders are deleted), you could try writing a custom ant task to traverse the file system below the target, deleting empty directories as you move back up from each leaf.

Rich Seller
I tried to expand on the question, but I want something that will after I clear out the contents of all the directories and then copy over the new build it will then delete any remaining directories that are empty (and by empty that means they could contain an excluded file/folder (e.g. .svn)). If I run a delete */** includeEmptyDirs="true" this will delete EVERYTHING, I ONLY want to delete empty dirs.
Dougnukem
I would definitely go with the custom ant task. They are easy to write, cross platform, and are a tidy way to get exactly the behavior you want in a declarative style.
Jeffrey Fredrick
A: 

This is probably easier to do with a batch file that gets called from ant.

You can use Raymond Chen's script, but it doesn't work if there are spaces in the names.

Jeremy Stein