Extend optional rather than adding it to existing classpath

This allows the attributes configured on compileClasspath and
runtimeClasspath to independently influence the variant selection when
resolving the optional configuration, allowing it to contribute compile
dependencies (JAVA_API) to the former and runtime dependencies
(JAVA_RUNTIME) to the latter.

Fixes gh-27365
This commit is contained in:
Andy Wilkinson
2021-09-06 17:19:29 +01:00
committed by Brian Clozel
parent 0ec4be37d5
commit d23afea168

View File

@@ -44,18 +44,14 @@ public class OptionalDependenciesPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
Configuration optional = project.getConfigurations().create("optional");
optional.attributes((attributes) -> attributes.attribute(Usage.USAGE_ATTRIBUTE,
project.getObjects().named(Usage.class, Usage.JAVA_API)));
optional.setCanBeConsumed(false);
optional.setCanBeResolved(true);
optional.setCanBeResolved(false);
project.getPlugins().withType(JavaPlugin.class, (javaPlugin) -> {
SourceSetContainer sourceSets = project.getConvention()
.getPlugin(JavaPluginConvention.class).getSourceSets();
SourceSetContainer sourceSets = project.getConvention().getPlugin(JavaPluginConvention.class)
.getSourceSets();
sourceSets.all((sourceSet) -> {
sourceSet.setCompileClasspath(
sourceSet.getCompileClasspath().plus(optional));
sourceSet.setRuntimeClasspath(
sourceSet.getRuntimeClasspath().plus(optional));
project.getConfigurations().getByName(sourceSet.getCompileClasspathConfigurationName()).extendsFrom(optional);
project.getConfigurations().getByName(sourceSet.getRuntimeClasspathConfigurationName()).extendsFrom(optional);
});
});
project.getPlugins().withType(EclipsePlugin.class, (eclipePlugin) -> {