Hopefully this is the right place to ask. I was wo...
# ksp
p
Hopefully this is the right place to ask. I was wondering if it's possible to generate source code for a kts script. I wanna try to use custom script runners, but I was wondering if there's something available for plain kts. It would be interesting to have something like plugins if nothing like that exists.
g
KSP doesn't generate code, it's "scanning" the code structure for you so that you can generate code during the compilation phase. As kts isn't compiled, using ksp really depends of what you want to generate (need more context to help). If you only need to generate kotlin code you can use something like kotlin-poet, since it's kotlin code eventually, I presume kts is supported.
p
Sorry, I meant ksp with kotlin poet for the code generation. I guess I'm wondering if there's an option to run code before running the script and include the code generated by kotlin-poet as a dependency of the script 🤔
The closest I found is using a custom script host, but was wondering if there's a way to do something like this or if it could be added. Is there a better channel to ask this? 🙏
r
I assume you want to have to have KSP read code -> send it to Kotlin Poet -> return the Poet-generated files as source code? You’d have to make a gradle task that runs the code generation. Then you can use dependsOn() to ensure the code generation finishes before Kotlin starts compiling. Something like this (Kotlin dsl):
Copy code
tasks.withType<KotlinCompilationTask<*>>()
     .configureEach {
         dependsOn("runCodegen")
     }
I’m currently working on such a project that I hope to open source relatively soonish. I began backwards, with the Kotlin Poet first and the KSP later. Not sure if it’s the ideal way to do it, but during the KSP phase I just create Kotlin objects which I stored as a list. The list is then serialized into a JSON file which is read by Kotlin Poet, which can just deserialize it back into regular Kotlin objects.