How do I use groovy/Gradle DSL to get a list of directories matching a pattern?

Viewed 449

The Gradle sonar plugin has a sonar.junit.reportPaths property that needs to be a comma-separated list of directories containing the JUnit test results files.

In our case, the directories match the pattern "^.*/build/test-results/(test|(component|integration)Test)/.*$".

We wanted to generate that list using fileTree includes/matching.

But it appears that fileTree:

  1. Returns only files, not directories.
  2. Is limited to ant-style file globbing, not full regular expressions.

After flailing around for way longer than we should have spent on it, we finally gave up and wrote it in Java:

def junitResults() {
    Set<String> testDirs = new LinkedHashSet<>()
    for (File file : files(fileTree(dir: rootDir, include: "**/build/test-results/**"))) {
        testDirs.add(file.getAbsolutePath().replaceAll("/build/test-results/(test|(component|integration)Test)/.*", "/build/test-results/\$1"))
    }
    return testDirs.toArray(new String[testDirs.size()]);
}

That has the advantage of actually working, but it looks idiosyncratic.

Does someone know how to replace that with normal-looking groovy/Gradle DSL?

2 Answers

Maybe something with eachDirMatch() like this

file('path/build/test-results/.').eachDirMatch(/(test|(component|integration)Test)/) { dir ->
    println dir.getPath()
}

wp78de, your answer pointed me in the right direction (use file, not fileTree):

def junitResultsDirs() {
def dirs = []
rootDir.eachDirRecurse { dir ->
    if (dir.absolutePath.matches("^.*/build/test-results/(test|(component|integration)Test)\$")) {
        dirs << dir
    }
}
return dirs;

}

Related