Move or copy a set of directories using Ant
I’m often baffled by the way some tasks work in Ant. Today, I needed to move a set of directories to another directory based on a <fileset> wildcard expression. My first, seemingly intuitive attempt was to use the <move> task and specify a <fileset> with an includes expression. Let’s suppose I want to move a set of incremental backup directories that all have the keyword “incremental” in the name:
backup-incremental1 backup-incremental2 backup-incremental3
It seems intuitive to use the following Ant move task to move these directories into another directory called backups/
<target name="move.dirs"> <mkdir dir="backups"/> <move todir="backups"> <fileset dir="." includes="*incremental*"/> </move> </target>
For some reason this only copies the root directory without recursively copying its contents. Ant gives a message that looks like the following:
[move] Moved 3 empty directories to 3 empty directories under Sandbox/ant/backups
After going through several iterations (emphatically gesturing at the monitor along the way) I finally realized that the core <move> and <copy> Ant tasks cannot do this. At least, not that I could figure out. Instead, you have to use the ant-contrib library’s <foreach> element to iterate over each directory and call a separate target that will actually move the directory:
<target name="move.dirs"> <mkdir dir="backups"/> <foreach param="dir" target="move.inc.backups"> <path> <fileset dir="."> <include name="*incremental*"/> </fileset> </path> </foreach> </target> <target name="move.inc.backups"> <move todir="backups" file="$dir"/> </target>
Why is this so? I’m still trying to figure out if there are any vanilla Ant solutions to this problem. I will be sure to post what I find in the future. For now I will just accept this as another one of many quirks in Ant. I love Ant for its simplicity and the ability to cobble together scripts quickly to automate tasks. But on the other hand, sometimes Ant lacks the intuitive nature of scripting languages like python or ruby.
If you have any alternatives to the method I presented here, please feel free to post them in the comments.
Update: To move or copy directories recursively without ant-contrib see this more recent post Ant copy and move directories recursively without ant-contrib