13 October 2010

Counting lines of code using Groovy

The following Groovy scripts easily counts the lines of files. In this example comparing the lines of code between an multi module Maven 2 project and the Gradle oposite.

def root = new File('/home/username/dirOne')
def pomCount = 0
def gradleCount = 0

private int getLOC(File f) {
    int i = 0  
    f.eachLine { i++ }
    return i
}

root.eachFileRecurse {

    if (it.isFile()) {
        if (it.name == 'pom.xml') {
             println "Reading ${it.absolutePath}"
             pomCount += getLOC(it)
        }
        else if (it.name.matches('.*\\.gradle')) {
             println "Reading ${it.absolutePath}"
             gradleCount += getLOC(it)
        }
        else {
          //println "Ignoring ${it.name} (${it.absolutePath})"
        }
    }
}
println "LOC of all pom.xml ${pomCount}"
println "LOC of all gradle.build ${gradleCount}"

No comments: