Add apoptions support in KotlinCompilerCall (#499)

* Add apoptions support to KotlinCompilerCall

* Add bad annotated annotation test
This commit is contained in:
Zac Sweers
2018-04-11 19:30:21 -07:00
committed by Jesse Wilson
parent f9b758b5bf
commit 941229b6c9
2 changed files with 46 additions and 2 deletions

View File

@@ -188,4 +188,22 @@ class CompilerTest {
assertThat(result.systemErr).contains(
"error: No property for required constructor parameter a")
}
}
@Test fun badGeneratedAnnotation() {
val call = KotlinCompilerCall(temporaryFolder.root)
call.inheritClasspath = true
call.addService(Processor::class, JsonClassCodeGenProcessor::class)
call.kaptArgs[JsonClassCodeGenProcessor.OPTION_GENERATED] = "javax.annotation.GeneratedBlerg"
call.addKt("source.kt", """
|import com.squareup.moshi.JsonClass
|
|@JsonClass(generateAdapter = true)
|data class Foo(val a: Int)
|""".trimMargin())
val result = call.execute()
assertThat(result.exitCode).isEqualTo(ExitCode.COMPILATION_ERROR)
assertThat(result.systemErr).contains(
"Invalid option value for ${JsonClassCodeGenProcessor.OPTION_GENERATED}")
}
}

View File

@@ -20,11 +20,14 @@ import okio.Buffer
import okio.Okio
import org.jetbrains.kotlin.cli.common.CLITool
import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.ObjectOutputStream
import java.io.PrintStream
import java.net.URLClassLoader
import java.net.URLDecoder
import java.util.Base64
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import kotlin.reflect.KClass
@@ -38,6 +41,7 @@ class KotlinCompilerCall(var scratchDir: File) {
var inheritClasspath = false
val args = mutableListOf<String>()
val kaptArgs = mutableMapOf<String, String>()
val classpath = mutableListOf<String>()
val services = LinkedHashMultimap.create<KClass<*>, KClass<*>>()
@@ -73,6 +77,12 @@ class KotlinCompilerCall(var scratchDir: File) {
}
fullArgs.addAll(annotationProcessorArgs())
if (kaptArgs.isNotEmpty()) {
fullArgs.apply {
add("-P")
add("plugin:org.jetbrains.kotlin.kapt3:apoptions=${encodeOptions(kaptArgs)}")
}
}
val systemErrBuffer = Buffer()
val oldSystemErr = System.err
@@ -166,4 +176,20 @@ class KotlinCompilerCall(var scratchDir: File) {
throw IllegalStateException("no kotlin-annotation-processing-embeddable jar on classpath:\n " +
"${classpathFiles().joinToString(separator = "\n ")}}")
}
}
/**
* Base64 encodes a mapping of annotation processor args for kapt, borrowed from
* https://kotlinlang.org/docs/reference/kapt.html#apjavac-options-encoding
*/
private fun encodeOptions(options: Map<String, String>): String {
val os = ByteArrayOutputStream()
ObjectOutputStream(os).use { oos ->
oos.writeInt(options.size)
for ((key, value) in options.entries) {
oos.writeUTF(key)
oos.writeUTF(value)
}
}
return Base64.getEncoder().encodeToString(os.toByteArray())
}
}