Ant Best Practices: Use ZipFileSet

Ant Best Practices: Use ZipFileSet

(image taken from the superbly named MasochismTango's photostream)


Welcome to the lucky thirteenth edition of Ant Best Practices. You probably guessed this one: Use the ZipFileSet type when you make a zip file in Ant.

This one slipped past me recently. We were working on a web project and the developers added a cache-busting feature to stop CSS stylesheets being cached by the reader's browser. So they wrote build targets to:

  • fetch the static content
  • lay it out in a directory, nested under an arbitrary kind of key
  • zip it all up for deployment later

It looked something like this:

<project name="web" default="zipfile">
  <property name="build.dir" value="build" />
  <property name="tmp" value="${build.dir}/tmp" />
  <target name="zipfile">
    <copy todir="${tmp}/static/random_token">
      <fileset dir="code" />
    </copy>
<!-- more static files, you getthe idea -->
    <zip file="${build.dir}/static.zip">
      <fileset dir="${tmp}" />
    </zip>
  </target>
</project>


Sounds fine, right?

Hmm. Actually, no. The approach gets top marks for actually working, but where I should have intervened was the copying of the files about to make the paths that were desired. In this case, the <zipfileset> lets you pluck files from wherever they might be, and put them into the right place:

<project name="web" default="zipfile">
  <property name="build.dir" value="build" />
  <target name="zipfile">
  <zip file="${build.dir}/static.zip">
    <zipfileset prefix="random_token" dir="code"/>
  </zip>
  </target>
</project>


Really, that's it. I was originally quite surprised that it made Eric's original list of practices: It's quite a simple change to make. But on writing about it I'm thinking this should be a refactoring. It'd be great to invoke an automated refactoring and introduce a zipfileset whenever you saw tedious copying and zipping operations. Anyway. Do this, and it will make your build faster and easy to read. Result.

DevOps New Zealand