Brad Mace
Brad Mace

Reputation: 27886

Gradle add dependency on another source set via plugin

I've got a Gradle plugin that adds a scratch source set. I want classes defined in src/main/java/ to be usable in src/scratch/java. I've figured out how to do this in the build file, but I'd like to have my plugin do this instead:

dependencies {
    scratchImplementation sourceSets.main.output
    //...
}

How can my plugin do this using the Gradle API?

Upvotes: 1

Views: 762

Answers (1)

Brad Mace
Brad Mace

Reputation: 27886

I pieced this together from Jeff's example: project.dependencies.add(project.getConvention().getPlugin(JavaPluginConvention).sourceSets.getByName("main").output);

but aside from being deprecated in Gradle 7.2, Gradle doesn't seem to like the add call:

Could not find method add() for arguments [main classes] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler

Tim's suggestion using the extension instead of the convention avoids the deprecation. Initially I got an error when I tried it, but it seems to have cleared up now.

What I had found in the interim that also worked is:

        project.dependencies {
            // add dependency on main java code from scratch java code
            scratchImplementation project.extensions.getByType(JavaPluginExtension).sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME).output
        }

(though I'm not totally sure why)

Upvotes: 1

Related Questions