Check if source set exists and is not empty

Hello there.

I’m currently working on a small “plug’n’play” script that automatically adds some stuff to some of my projects.
Now depending on whether a certain source set (like test) exists and has some source file I need to add some more task. I know that I can use conditionals and stuff like that and that really is not what I’m struggling here. What I’m struggling with is to detect whether a certain source set exists and has source (like for example test exists by default but can be empty. In which case I don’t want to add the tasks).

I tried sourceSets.contains, but that expects a SourceSet as a parameter, so I can’t pass it a string.
Also I have no idea on how to check whether the source set has source in it or not.

I principle my code looks like that:

def sourceSetExistsAndNotEmpty(sourceSet) {
    // Here be dragons
    return ...;
}

task doStuffMain {
    // ...
}

if (sourceSetExistsAndNotEmpty("test")) {
    task doStuffTest {
        // ...
    }
}

if (sourceSetExistsAndNotEmpty("api")) {
    task doStuffApi {
        // ...
    }
}

if (sourceSetExistsAndNotEmpty("extra")) {
    task doStuffExtra {
        // ...
    }
}

While continuing to look for a solution, I still haven’t found a solution to this problem.

  1. You can find a specific source set by it’s name, by using filter() instead of contains().
  2. You can check whether there are files in a SourceSet by checking it’s classpath file collections. There are FileCollections for compileClassPath, runtimeClasspath and annotationProcessorPath.
def sourceSetIsNotEmpty(String sourceSetName) {
    final SourceSet sourceSet = sourceSets.find {
        it.name.equals(sourceSetName)
    }

    return null != sourceSet && 
            (0 < sourceSet.compileClasspath.size()
            || 0 < sourceSet.runtimeClasspath.size())
}

task thatShouldRunOnlyIfThereAreFileInTestSourceSet {
    enabled = sourceSetIsNotEmpty("test")
    
    if(!enabled) {
        return
    }
    
    println 'Task configuration continues'

    doLast {
        println 'Executing thatShouldRunOnlyIfThereAreFileInTestSourceSet'
    }
}
1 Like