Skip to content

Instantly share code, notes, and snippets.

@adibfara
Created May 5, 2022 14:06
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 adibfara/d8ed207f9c6d904904a0743918a7ea11 to your computer and use it in GitHub Desktop.
Save adibfara/d8ed207f9c6d904904a0743918a7ea11 to your computer and use it in GitHub Desktop.
Completing the processor
internal class ListedProcessor(
private val environment: SymbolProcessorEnvironment,
) : SymbolProcessor {
private fun Resolver.findAnnotations(
kClass: KClass<*>,
) = getSymbolsWithAnnotation(
kClass.qualifiedName.toString())
.filterIsInstance<KSFunctionDeclaration>().filter {
it.parameters.isEmpty()
}
override fun process(resolver: Resolver): List<KSAnnotated> {
val listedFunctions: Sequence<KSFunctionDeclaration> =
resolver.findAnnotations(Listed::class)
if(!listedFunctions.iterator().hasNext()) return emptyList()
// gathering the required imports
val imports = listedFunctions.mapNotNull { it.qualifiedName?.asString() }.toSet()
// group functions based on their given list-name
val lists = listedFunctions.groupBy { it.annotations.first { it.shortName.asString() == "Listed" }.arguments.first().value.toString() }
val sourceFiles = listedFunctions.mapNotNull { it.containingFile }
val fileText = buildString {
append("package your.desired.packagename")
newLine()
newLine()
imports.forEach {
append("import $it")
newLine()
}
newLine()
lists.forEach { (listName, functions) ->
val functionNames = functions.map { it.simpleName.asString() + "()" }.joinToString(", ")
append("val $listName = listOf($functionNames)")
newLine()
}
}
createFileWithText(sourceFiles, fileText)
return (listedFunctions).filterNot { it.validate() }.toList()
}
private fun createFileWithText(
sourceFiles: Sequence<KSFile>,
fileText: String,
) {
val file = environment.codeGenerator.createNewFile(
Dependencies(
false,
*sourceFiles.toList().toTypedArray(),
),
"your.generated.file.package",
"GeneratedLists"
)
file.write(fileText.toByteArray())
}
private fun StringBuilder.newLine(count: Int = 1) {
repeat(count){
append("\n")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment