Generate include list in settings.gradle

Instead of manually defining the set of project to ‘include’ in settings.gradle, I would like to simply include everything beneath the root which contains a build.gradle. Here is my attempt:

def buildableProjects() {
    def result = []
    settingsDir.eachDirRecurse { dir ->
        if (new File(dir, 'build.gradle').exists()) {
            result << ':' + settingsDir.toPath().relativize(dir.toPath())
                .toString().replaceAll(~/[\\\\/]/, ':')
        }
    }
    result
}

include buildableProjects()

Unfortunately, this doesn’t quite work:

> [Ljava.lang.String; cannot be cast to java.util.List

I’ve tried adding toList(), but this doesn’t make a difference (which is quite confusing to me). Any clues?

The problem is the other way around, the include() method accepts an array, not a List. You’ll want to do something like

result as String[]

Awesome! This works. But I’m confused. I thought I was declaring an array to begin with. And why does it say it is trying to cast anything to List?

Also, I tried recursing down the children of rootProject, but there weren’t any. I presume this is because within settings.gradle, the only projects are those that have already been added via ‘include’. Is this correct?

Finally, while my code works, I would be happy to make any improvements in style which are more idiomatic groovy/gradle. Thanks for your help!

The Groovy [] literal syntax creates a Java List not an array.

Correct.

Not really, this is a pretty common pattern and your implementation seems sound. There’s no “standard” way of doing this since every project is structured differently and has its own conventions.