Created
April 23, 2022 10:35
-
-
Save mehdiyari/d1e87eb1201a8e74370e33c9e30b629e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This is simple processor that use KSP API to generate | |
* extension function for annotated classes with [HelloWorldAnnotation] | |
*/ | |
class HelloWorldProcessor( | |
private val logger: KSPLogger, | |
private val codeGenerator: CodeGenerator | |
) : SymbolProcessor { | |
override fun process(resolver: Resolver): List<KSAnnotated> { | |
val symbols = resolver.getSymbolsWithAnnotation(HelloWorldAnnotation::class.qualifiedName!!) | |
val returnList = symbols.filter { !it.validate() }.toList() | |
symbols.filter { it is KSClassDeclaration && it.validate() } | |
.forEach { it.accept(HelloWorldAnnotatedClassVisitor(), Unit) } | |
return returnList | |
} | |
inner class HelloWorldAnnotatedClassVisitor : KSVisitorVoid() { | |
override fun visitClassDeclaration(classDeclaration: KSClassDeclaration, data: Unit) { | |
super.visitClassDeclaration(classDeclaration, data) | |
val packageName = classDeclaration.qualifiedName?.getQualifier() ?: kotlin.run { | |
logger.error("packageName is empty") | |
return | |
} | |
val className = classDeclaration.simpleName.getShortName() | |
codeGenerator.createNewFile( | |
Dependencies( | |
true, | |
classDeclaration.containingFile!! | |
), | |
packageName, | |
"${className}_Generated" | |
).use { file -> | |
file.write(""" | |
package $packageName\n | |
fun ${packageName}.${className}.printHelloWorld() { | |
println("Hello world!") | |
} | |
""".trimIndent().toByteArray()) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment