2014-11-14 52 views
0

我有一个闭包在遍历中正常工作,但另一个同类失败。我怀疑范围或时间正在导致失败。工作代码将文件系统中文件的大小相加。代码不工作是检查文件的内容,只打印一个匹配。Groovy文件解析文件时的遍历行为

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++ 
    } 
} 

问题代码:

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 
} 

回答

0

我测试你的代码,并能正常工作使用Grails 2.3.7

工作的代码运行这些。

您期待哪种行为?

我找到了几个可疑的东西:

  • 如果fileText开始"@Table "然后indexOf将返回0,条件if(fileText.indexOf("@Table ") > 0)不会满意。

  • "@Table "具有尾随空格,那么包含一个文件,例如:"@Table(",将不被打印。

您还可以检查filterGroovyFiles是否具有相应的值。

我希望它能帮上忙。

- 编辑 -

运行与def filterGroovyFiles = ~/.*\.groovy$/代码和文件树:

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

和包含(但不是开始!!) “@Table” 三个常规文件(尾随空间!!)。我得到预期输出:

​​

(注意从SUB1都出现在同一个文件夹都dum.groovy和dum2.groovy)。

我使用的是groovy 2.0.5。

请重新检查您的文件:

  • 有正确的扩展
  • 遏制而不是在开始时(指数== 0),字符串“@表”
+0

行为我看到是在满足正则表达式匹配的目录中的第一个文件是打印的唯一行,然后处理停止(仅一行),即使为每个子目录都打印countSmallFiles。我使用的是Grails 2.3.7。我会尝试使用旧版本的grails运行,看看我是否得到相同的结果。 – Duane5000 2014-11-17 20:43:33

+0

有点不同的方法,但为我工作: 'def groovySrcDir = new File('。','plugins /') def result = new AntBuilder()。fileset(dir:'./ plugins /',包括: '**/*。groovy'){ containsregexp expression:'。* @ Table。*'' } *。文件 result.each(){f - > \t def fileText = f.text \t Pattern p = Pattern.compile(“(@ Table | @NamedQuery)。*?(name)。*?(=)。( \\ S +)(\\))“); \t Matcher m = p.matcher(fileText); /* @NamedQuery不起作用。 (m.find())打印“$ {f.name} \ treferences table:”+ m.group(4).replace()时,我怀疑string.string的命名是打破REGEX */ \t “\”“,”“); \t} }' – Duane5000 2014-11-17 20:47:57

+0

我不明白,如果我运行代码,我会得到一行所有带有”@Table“的文件。 。 – fonkap 2014-11-17 22:03:21