Anyway, I'm working on some simple scripting for work (to automate setting up a development environment on Linux), and I think "hey, why don't I use Groovy for this?" I've been reading some very good Groovy books (and doing a little hacking with it), so it seemed like a perfect opportunity.
My first task is simple enough - grab some gzipped tar files from a source directory and expand them into some destination directory. It starts of in a simple minded way:
"tar zxf $/sourcedir/file_a.tgz -C /destdir".execute()
"tar zxf $/sourcedir/file_b.tgz -C /destdir".execute()
"tar zxf $/sourcedir/file_b.tgz -C /destdir".execute()
OK, not very "Groovy" (or terribly useful or cleaver, for that matter). So I say "well, I can at least abstract out the source and destination directories, along with the filenames." Now I have:
SRCDIR = "/sourcedir"
DSTDIR = "/destdir"
FILE_A="file_a.tgz"
FILE_B="file_b.tgz"
FILE_C="file_c.tgz"
"tar zxf ${SRCDIR}/${FILE_A} -C ${DSTDIR}".execute()
"tar zxf ${SRCDIR}/${FILE_B} -C ${DSTDIR}".execute()
"tar zxf ${SRCDIR}/${FILE_C} -C ${DSTDIR}".execute()
Not much of an improvement.
OK, then I wise up a bit an realize I can use AntBuilder instead of executing tar directly. The "tar..." lines become:
def ant = new AntBuilder()
ant.untar(src:"${SRCDIR}/${FILE_A}",
dest:"${DSTDIR}",
compression:"gzip")
ant.untar(src:"${SRCDIR}/${FILE_B}",
dest:"${DSTDIR}",
compression:"gzip")
ant.untar(src:"${SRCDIR}/${FILE_C}",
dest:"${DSTDIR}",
compression:"gzip")
A little better. Finally, on about midnight, I begin to think of how to do this in a much more idiomatic "Groovy" way: put the files in an array, and iterate over them with a closure! (Those used to Groovy, Ruby or any other decent dynamic language may feel free to say "duh" at this point. Give me a break - I've been using Java since 1.0 :-). Now I have something like this:
SRCDIR = "/sourcedir"
DSTDIR = "/destdir"
files = ["file_a.tgz", "file_b.tgz", "file_c.tgz"]
files.each {file ->
ant.untar(src:"${SRCDIR}/${file}",
dest:"${DSTDIR}",
compression:"gzip")
}
Much Groovier. Now I can go and get some sleep ;-)
Wicked groovy! Keep it up!!
ReplyDelete