Groovy File Traverse behavior when parsing file

886 views Asked by At

I have a closure working properly on traverse, but another of the same kind is failing. I'm suspecting scope or timing is causing this to fail. The working code sums the size of files in the file system. The code not working is inspecting the content of the file and only prints one match. Running these with Grails 2.3.7

working code:

def groovySrcDir = new File('.', 'plugins/')
def countSmallFiles = 0
def postDirVisitor = {
   if (countSmallFiles > 0) {
      println "Found $countSmallFiles files with small filenames in ${it.name}"
   }
   countSmallFiles = 0
}
groovySrcDir.traverse(type: FILES, postDir: postDirVisitor, nameFilter: ~/.*\.groovy$/) {
   if (it.name.size() < 15) {
      countSmallFiles++
   }
}

problem code:

def datamap = [:]
def printDomainFound = {
   //File currentFile = new File(it.canonicalPath)
   def fileText = it.text
   if(fileText.indexOf("@Table ") > 0){
      //println "Found a Table annotation in ${it.name} "
      datamap.put(it.name, it.name)
   }
}
groovySrcDir.traverse type: FILES, visit: printDomainFound, nameFilter: filterGroovyFiles
datamap.each {
   println it.key
}
1

There are 1 answers

3
fonkap On BEST ANSWER

I tested your code and worked fine.

Which behaviour are you expecting?

I find a couple of suspicious things:

  • If fileText begins with "@Table " then indexOf will return 0 and the condition if(fileText.indexOf("@Table ") > 0) will not be satisfied.

  • "@Table " has a trailing space, then a file containing, for example: "@Table(", will not be printed.

You can also check that filterGroovyFiles has the appropiate value.

I hope it'll help.

-- EDIT --

Running the code with def filterGroovyFiles = ~/.*\.groovy$/ and this file tree:

plugins
|--sub1
|  |-dum.groovy
|  |-dum2.groovy
dum3.groovy

And all three groovy files containing the (but not starting with!!) "@Table " (with trailing space!!). I get the expected output:

dum3.groovy
dum.groovy
dum2.groovy

(Note both dum.groovy and dum2.groovy from the same folder sub1 are appearing).

I'm using groovy 2.0.5.

Please recheck your files :

  • Have the correct extension
  • Contain but not at the begining (index==0) the String "@Table "