Ubuntu insights, Programming in groovy, java, et als!

Tuesday, November 15, 2011

Count the Lines of Code in Your Project

I was searching through eclipse if there was an option somewhere within the IDE that could count the total lines of code in my project. After 5 min of Google struggle, I got to know that I need to install a metrics plugin to be able to do so. Reluctant to install any additional plugin, I resorted to groovy, spending an equivalent 5 min of time for this piece of code that counts the total number of lines in all the files within a directory at any depth.

Run the below script with dirPath variable pointing to your project base and addup comma seperated extensions in the filterFileExtensions variable list to specify the filetypes you wish to index , as in java, groovy or any text rendering file extensions like txt, html, etc. 

//------------------- Start Groovy Script --------------->


def filterFileExtensions = ["groovy", "java"] 
def dirPath = 'C:\\VKWorks\\Sampleproject'


def base = new File(dirPath)
def obj = new FileUtil(list:filterFileExtensions)
obj.recurseCountCodeLines(base)
obj.printResult()
//------------------- End Groovy Script --------------->


class FileUtil{
def lineCount = 0
def filesProcessed = 0
def list 


def recurseCountCodeLines(file){
    if(file.isDirectory()){
        file.listFiles().each{recurseCountCodeLines(it)}
    }


    else{
    def fileExtn = file.getName().tokenize(".").last()
    if(list.contains(fileExtn)){
        println "processing file $file"
            file.getText().eachLine{ line ->
            def isCommentedCode = line.startsWith("/") ||
                                  line.startsWith("*")                      
                if(line.size()>0 && !isCommentedCode)
                    lineCount++
            }
            filesProcessed ++
        }
    }
}
    
def printResult(){
    println "---------------------------------"
    println "files processed : $filesProcessed "
    println "Code line count : $lineCount"
    println "---------------------------------"
}
}



PS on performance: 12,000 lines of code in 150 odd files within various depths of the specified directory were retrieved in less than a second. 



0 comments:

Post a Comment