class BuildScriptSupportPlugin implements Plugin<Project> {
/**
* Spring {@link PathMatchingResourcePatternResolver} used to find all Gradle scripts
* on the classpath.
*/
private PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(getClass().getClassLoader());
@Override
public void apply(Project project) {
project.logger?.debug("Applying Build Script Support Plugin to ${project.name}...")
// Make sure the output directory for the extracted scripts exists.
File outputDirectory = new File(project.buildDir, 'scripts')
outputDirectory.mkdirs()
// Find all .gradle files in the "scripts" package on the class path.
Resource[] resources = resourceResolver.findPathMatchingResources('classpath*:/scripts/*.gradle')
// For each script, copy it from the class path to the output directory and then apply it to the project.
resources.each { Resource resource ->
try {
File output = new File(outputDirectory, resource.getFilename())
output.withWriter { writer ->
writer.write(new InputStreamReader(resource.getInputStream()).getText())
}
project.apply([from: "${outputDirectory}/${resource.getFilename()}"])
} catch (e) {
project.logger?.error("Unable to retrieve and apply bulid script '${resource.getFilename()}': ${e.getMessage()}")
}
}
}
}