Monday, June 14, 2010

Using Groovy AntBuilder to zip / unzip files

I've been quiet for quite a while - partly because I am not working with Oracle just at the moment. I have been building some automated workflow systems using Groovy as the scripting language. I've known about Groovy since James Strachan first invented it back in around 2002/3 - but this is the first time I've really been using it in earnest. It's a great for portable scripts, and for integration with Java (it runs in the JVM). It's much friendlier than Java for someone like me who comes from a PL/SQL and C (not C++) background.

Anyhow, I found out about using Groovy Antbuilder tasks, and have been using them to manage zipping / unzipping file sets:

def ant = new AntBuilder(); // create an antbuilder
ant.unzip( src: planZipFile, dest:workingDirName, overwrite:"true")

Then I found I wanted to flatten the output (ie don't reproduce the directory structure). The Apache Ant documentation for the unzip task shows the Ant XML:

<unzip src="" dest="${tools.home}">
<include name="apache-ant/lib/ant.jar"/>
<mapper type="flatten"/>

How to add the mapper element?

Well, lots of googling later, I couldn't find an example but I did see the patternset being used. So thanks to that, I found that the Groovy way of expressing the mapper part of this is to add a closure after the call:
def ant = new AntBuilder();
ant.unzip( src: planZipFile, dest:workingDirName, overwrite:"true"){ mapper(type:"flatten")};

So I hope someone finds that useful.


nikhil said...

For pattern set please find the example

ant.unzip(src : jarFile, dest: privateClasspath) {
patternset() {
exclude(name: "**/org/eclipse/jetty/continuation/Jetty6Continuation.class")


Sean Flanigan said...

Thanks for the post!

If you need to use one of the mappers which doesn't have a <mapper type>, such as <cutdirsmapper dirs="1"/>, you can use something like this:

ant.untar(src: f, dest: target,
compression: 'gzip', failOnEmptyArchive: true, overwrite: true) {cutdirsmapper(dirs: 1)}