javashellkotlinkaptkotlinc

How to use kapt from command line (with kotlinc)?


Official documentation instructs how to use kapt from Gradle and Maven. But how can I use kapt from command line, with kotlinc?


Solution

  • Add tools.jar to Kotlin compilers' classpath

    As of Kotlin version 1.1.3-2, kotlinc does not add tools.jar to compiler's classpath. tools.jar is required by kapt.

    As a workaround, you can patch kotlinc.

    vim $KOTLIN_HOME/bin/kotlinc
    

    Edit line 79.

    From:

    kotlin_app=("${KOTLIN_HOME}/lib/kotlin-preloader.jar" "org.jetbrains.kotlin.preloading.Preloader" "-cp" "${KOTLIN_HOME}/lib/kotlin-compiler.jar" $KOTLIN_COMPILER)
    

    To:

    kotlin_app=("${KOTLIN_HOME}/lib/kotlin-preloader.jar" "org.jetbrains.kotlin.preloading.Preloader" "-cp" "${KOTLIN_HOME}/lib/kotlin-compiler.jar:$JAVA_HOME/lib/tools.jar" $KOTLIN_COMPILER)
    

    Note: $JAVA_HOME must point to JDK, not JRE.

    Note: This is a hack.

    Invoke kotlinc with right arguments

    kotlinc -cp $MY_CLASSPATH \
    -Xplugin=$KOTLIN_HOME/lib/kotlin-annotation-processing.jar -P \
    plugin:org.jetbrains.kotlin.kapt3:aptMode=aptAndStubs,\
    plugin:org.jetbrains.kotlin.kapt3:apclasspath=/path/to/SomeAnnotationProcessor.jar,\
    plugin:org.jetbrains.kotlin.kapt3:sources=./sources,\
    plugin:org.jetbrains.kotlin.kapt3:classes=./classes,\
    plugin:org.jetbrains.kotlin.kapt3:stubs=./stubs \
    /path/to/MyKotlinFile.kt
    

    Replace:

    Note: -X arguments (advanced options) are non-standard and may be changed or removed without any notice

    Note: kapt's interface is undocumented. You can check the source code: https://github.com/JetBrains/kotlin/blob/master/plugins/kapt3/src/org/jetbrains/kotlin/kapt3/Kapt3Plugin.kt#L295


    This stuff was reverse-engineered from running gradle build --debug in kotlin-examples/gradle/kotlin-dagger (https://github.com/JetBrains/kotlin-examples/tree/master/gradle/kotlin-dagger).

    This is just a starting point. I'm still not sure of a few things. Feel free to edit this answer.

    Thanks to runningcode: https://github.com/facebook/buck/issues/956#issuecomment-309080611

    If it wasn't obvious: this stuff sucks. JetBrains just assumed that CLI doesn't matter and they made the crucial interfaces undocumented / reserved for internal use.