groovy utility script

While trying to get a java project to compile, I noticed it needed some classes that weren’t included in the src folder. I found them pretty quick, but , to my surprise, the classes were just thrown there. What I mean by that is:

  • there was a pretty large number of classes in one directory
  • classes belonged to a package, but they weren’t placed in the right directory structure ( actually they weren’t in any directory structure )

I could have just add them to my src folder and then click my way through them while Eclipse would fix the packages, but I didn’t like that solution, so I wrote the following groovy script :

if(args.size() != 2) {
    println "groovy classplacer.groovy sourcedir destdir"
else {
    def sourceDir = new File(args[0])
    def destDir = new File(args[1])
    if(!destDir.exists()) {
        println "creating $destDir"
    sourceDir.eachFileRecurse { file ->
        if(file.name.endsWith(".java")) {
            file.eachLine { line ->
                def matcher = line =~ /^(?i)\s*package\s+(.*?)\s*;\s*$/
                if(matcher.count > 0) {
                    def packageName = matcher[0][1]
                    def dirName = packageName.replaceAll("\\.",File.separator)
                    def fDestDir = new File(destDir,dirName) // destination dir, with package
                    def fDestFile = new File(fDestDir,file.name) // full path, including java ext
                    println "moving $file to $fDestFile"
                    fDestDir.mkdirs() // create dirs so that the path will exist
                    fDestFile.write file.text // "copy" the file

The script takes 2 parameters, a source dir and a destination dir. It will look in the source dir for all java files and move them to the destination dir. It will also create the directories needed so that the class will be located in the right package.

An example of it’s run would be :

groovy classplacer.groovy classes/ ~/workspace/project/src


0 Responses to “groovy utility script”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Blog Stats

  • 239,004 hits

%d bloggers like this: