Monday, May 10, 2010

Classpath Builder

In Java world, we all are very familiar with classpath. If let's say we have a lot of JAR files scattered around in many different sub-directories, listing down all of them by hand can be very tedious.

Below is the script that can help you to automate that. You can do something like this.

java -cp `groovy ClassPathBuilder.groovy absolute auto jars` myproject.Main

def validateArgs() {
    if (this.args.size() != 3) {
        printUsage()
        System.exit(0)
    }

    if (this.args[0] != 'absolute' && this.args[0] != 'relative' &&
           this.args[1] != 'unix' && this.args[1] != 'windows' && this.args[1] != 'auto') {
        printUsage()
        System.exit(0)
    }

    if (!(new File(this.args[2]).isDirectory())) {
        println "${this.args[2]} is not a directory"
        System.exit(0)
    }
}

def printUsage() {
    println "Usage: groovy ClassPathBuilder.groovy [absolute|relative] [unix|windows|auto] [dir]"
}

def getJars(def file) {
    def jars = []
    file.eachFileRecurse { 
        if (it.name.toLowerCase().endsWith(".jar")) { 
            jars += it 
        }
    }
    return jars
}

validateArgs()
def dir = new File(this.args[2])
def jars = getJars(dir)
def option1 = this.args[0]
def option2 = this.args[1]
def pathSeparator = (option2 == 'unix') ? ":" : (option2 == 'windows') ? ";" : File.pathSeparator
def result = ''
if (option1 == 'absolute') {
    result = jars.collect { file -> file.getPath() }.join(pathSeparator)
} else {
    result = jars.collect { file -> file.getPath().substring(dir.getPath().size()+1) }.join(pathSeparator)
}

if (option2 == 'unix') {
    println result.replaceAll('\\\\', '/')
} else if (option2 == 'windows') {
    println result.replaceAll('/', '\\\\')
} else {
    println result
}

No comments:

Post a Comment