Skip to content

Commit 143b175

Browse files
committed
Fix KSP not working with only Java files
1 parent db45793 commit 143b175

File tree

2 files changed

+34
-5
lines changed

2 files changed

+34
-5
lines changed

core/src/main/kotlin/com/tschuchort/compiletesting/AbstractKotlinCompilation.kt

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -162,13 +162,17 @@ abstract class AbstractKotlinCompilation<A : CommonCompilerArguments> internal c
162162
)
163163
)
164164

165-
// if no Kotlin sources are available, skip the compileKotlin step
166-
if (sources.none(File::hasKotlinFileExtension))
167-
return KotlinCompilation.ExitCode.OK
168-
169165
// in this step also include source files generated by kapt in the previous step
170166
val args = arguments.also { args ->
171-
args.freeArgs = sources.map(File::getAbsolutePath).distinct()
167+
args.freeArgs =
168+
sources.map(File::getAbsolutePath).distinct() + if (sources.none(File::hasKotlinFileExtension)) {
169+
/* __HACK__: The Kotlin compiler expects at least one Kotlin source file or it will crash,
170+
so we trick the compiler by just including an empty .kt-File. We need the compiler to run
171+
even if there are no Kotlin files because some compiler plugins may also process Java files. */
172+
listOf(SourceFile.new("emptyKotlinFile.kt", "").writeIfNeeded(sourcesDir).absolutePath)
173+
} else {
174+
emptyList()
175+
}
172176
args.pluginClasspaths = (args.pluginClasspaths ?: emptyArray()) + arrayOf(getResourcesPath())
173177
}
174178

ksp/src/test/kotlin/com/tschuchort/compiletesting/KspTest.kt

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,25 @@ class KspTest {
5151
}
5252
}
5353

54+
@Test
55+
fun allProcessorMethodsAreCalledWhenOnlyJavaFilesArePresent() {
56+
val instance = mock<SymbolProcessor>()
57+
val providerInstance = mock<SymbolProcessorProvider>()
58+
`when`(providerInstance.create(any(), any(), any(), any())).thenReturn(instance)
59+
val result = KotlinCompilation().apply {
60+
sources = listOf(DUMMY_JAVA_SRC)
61+
symbolProcessorProviders = listOf(providerInstance)
62+
}.compile()
63+
assertThat(result.exitCode).isEqualTo(ExitCode.OK)
64+
providerInstance.inOrder {
65+
verify().create(any(), any(), any(), any())
66+
}
67+
instance.inOrder {
68+
verify().process(any())
69+
verify().finish()
70+
}
71+
}
72+
5473
@Test
5574
fun processorGeneratedCodeIsVisible() {
5675
val annotation = SourceFile.kotlin(
@@ -308,5 +327,11 @@ class KspTest {
308327
class Dummy {}
309328
""".trimIndent()
310329
)
330+
331+
private val DUMMY_JAVA_SRC = SourceFile.java(
332+
"foo.bar.DummyJava.java", """
333+
class DummyJava {}
334+
""".trimIndent()
335+
)
311336
}
312337
}

0 commit comments

Comments
 (0)