Skip to content

Commit

Permalink
Add a better error message when Hilt Gradle Plugin class loader confl…
Browse files Browse the repository at this point in the history
…icts with KSP's Gradle plugin.

See #3965

RELNOTES=Add a better error message when Hilt Gradle Plugin class loader conflicts with KSP's Gradle plugin.
PiperOrigin-RevId: 553467242
  • Loading branch information
danysantiago authored and Dagger Team committed Aug 3, 2023
1 parent 354d744 commit 3f7b9b5
Showing 1 changed file with 30 additions and 0 deletions.
Expand Up @@ -38,6 +38,16 @@ internal fun addKaptTaskProcessorOptions(
component: ComponentCompat,
produceArgProvider: (Task) -> CommandLineArgumentProvider
) = project.plugins.withId("kotlin-kapt") {
checkClass("org.jetbrains.kotlin.gradle.internal.KaptTask") {
"""
The KAPT plugin was detected to be applied but its task class could not be found.
This is an indicator that the Hilt Gradle Plugin is using a different class loader because
it was declared at the root while KAPT was declared in a sub-project. To fix this, declare
both plugins in the same scope, i.e. either at the root (without applying them) or at the
sub-projects.
""".trimIndent()
}
project.tasks.withType(KaptTask::class.java) { task ->
if (task.name == "kapt${component.name.capitalize()}Kotlin") {
val argProvider = produceArgProvider.invoke(task)
Expand All @@ -60,13 +70,33 @@ internal fun addKspTaskProcessorOptions(
component: ComponentCompat,
produceArgProvider: (Task) -> CommandLineArgumentProvider
) = project.plugins.withId("com.google.devtools.ksp") {
checkClass("com.google.devtools.ksp.gradle.KspTaskJvm") {
"""
The KSP plugin was detected to be applied but its task class could not be found.
This is an indicator that the Hilt Gradle Plugin is using a different class loader because
it was declared at the root while KSP was declared in a sub-project. To fix this, declare
both plugins in the same scope, i.e. either at the root (without applying them) or at the
sub-projects.
See https://github.com/google/dagger/issues/3965 for more details.
""".trimIndent()
}
project.tasks.withType(KspTaskJvm::class.java) { task ->
if (task.name == "ksp${component.name.capitalize()}Kotlin") {
task.commandLineArgumentProviders.add(produceArgProvider.invoke(task))
}
}
}

private inline fun checkClass(fqn: String, msg: () -> String) {
try {
Class.forName(fqn)
} catch (ex: ClassNotFoundException) {
throw IllegalStateException(msg.invoke(), ex)
}
}

internal fun Task.isKspTask(): Boolean = try {
val kspTaskClass = Class.forName("com.google.devtools.ksp.gradle.KspTask")
kspTaskClass.isAssignableFrom(this::class.java)
Expand Down

0 comments on commit 3f7b9b5

Please sign in to comment.