David R. Heffelfinger

  Ensode Technology, LLC

 

Groovy Script to zip a directory excluding certain files and subdirectories


Like I mentioned in my last post, I've been reading about Groovy lately. I'm finding Groovy very useful to automate small tedious tasks that I have to do in a regular basis.

For example, many times I have to zip up a directory, but there are some files or subdirectories I want to leave out. What I usually did was I would zip up the whole directory, then manually delete whatever I didn't want in the zip file. Alternatively, I would try to do it from the Linux command line, but I invariably would forget the syntax to do it, this would happen so often that I wrote a blog post explaining how to do it primarily so that I could refer to it myself.

ANT has a zip core task that can easily exclude files or directories from the resulting zip file, through Groovy's AntBuilder class, it is trivial to write Groovy scripts to invoke ANT tasks. It didn't take long to put two and two together, and write a simple Groovy script that would invoke the ANT zip task, specifying any unwanted files or directories.

Without further ado, here's the script:



#!/usr/bin/env groovy
def excludes="**/*.swp, somefile.txt, somedir/**"
def ant = new AntBuilder()

println "args = ${args}"
if (args.length > 0) {
if (args[0].endsWith("/") || args[0].endsWith("\\")) {
args[0] = args[0].substring(0, args[0].length() -1)
}
ant.zip(baseDir:args[0], destFile:args[0] + ".zip", excludes:excludes,
update:true)
}
else {
println "usage: ZipDir.groovy [dirName]"
}

Simply edit the value of the excludes variable to contain any valid comma-separated ANT patterns matching the files or directories you want to exclude from the zip file. Enjoy.

 
 
 
 
 

« August 2009 »
SunMonTueWedThuFriSat
      
2
3
4
5
6
8
9
10
11
12
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
     
Today

 
© David R. Heffelfinger