Configure optional configuration to consume its dependencies' API

Previously, the optional configuration had no usage attribute. This
resulted in it using the default, JAVA_RUNTIME, which caused it to
only consume the runtime produced by its dependencies and not the
API. Given that the optional configuration is added to the compile
classpath, this was incorrect.

This commit updates the optional configuration to be configured to
consume the Java API of its dependencies. The configuration has
also been marked as not being for consumption. This prevents other
projects attempting to consume the optional variant of a project
that has the optional dependencies plugin applied and further
aligns it with Gradle's built-in configurations of a similar nature.

See gh-27365
This commit is contained in:
Andy Wilkinson 2021-09-06 16:21:24 +01:00 committed by Brian Clozel
parent 532b4b636d
commit 0ec4be37d5
1 changed files with 5 additions and 0 deletions

View File

@ -19,6 +19,7 @@ package org.springframework.build.optional;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.attributes.Usage;
import org.gradle.api.plugins.JavaPlugin;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.tasks.SourceSetContainer;
@ -43,6 +44,10 @@ 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);
project.getPlugins().withType(JavaPlugin.class, (javaPlugin) -> {
SourceSetContainer sourceSets = project.getConvention()
.getPlugin(JavaPluginConvention.class).getSourceSets();