Skip to content

Instantly share code, notes, and snippets.

@mehdiyari
Created April 23, 2022 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mehdiyari/d1e87eb1201a8e74370e33c9e30b629e to your computer and use it in GitHub Desktop.
Save mehdiyari/d1e87eb1201a8e74370e33c9e30b629e to your computer and use it in GitHub Desktop.
/**
* 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