Skip to content

Instantly share code, notes, and snippets.

@PaulWoitaschek
Last active November 18, 2021 20:54
Show Gist options
  • Save PaulWoitaschek/29fe68c7987a409355be38e2f7c9c485 to your computer and use it in GitHub Desktop.
Save PaulWoitaschek/29fe68c7987a409355be38e2f7c9c485 to your computer and use it in GitHub Desktop.
internal class EnumGenerator(
private val codeGenerator: CodeGenerator
) {
fun generate(classDeclaration: KSClassDeclaration) {
require(classDeclaration.classKind == ClassKind.ENUM_CLASS) {
"${classDeclaration.containingFile?.filePath} is no enum."
}
val enum = buildEnum(classDeclaration)
val fileSpec = FileSpec.builder(enum.name)
.addType(enum)
.build()
createFile(classDeclaration, fileSpec)
}
private fun buildEnum(classDeclaration: KSClassDeclaration): TypeSpec {
val fileName = classDeclaration.qualifiedName!!.asString()
.removePrefix(classDeclaration.packageName.asString() + ".")
.replace(".", "")
val enumBuilder = TypeSpec.enumBuilder(fileName)
.addModifiers(Modifier.PUBLIC)
classDeclaration.declarations
.forEach {
if (it is KSClassDeclaration && it.classKind == ClassKind.ENUM_ENTRY) {
val enumName = it.simpleName.asString().replaceFirstChar { char ->
char.lowercase()
}
enumBuilder.addEnumCase(enumName)
}
}
return enumBuilder.build()
}
private fun createFile(
classDeclaration: KSClassDeclaration,
fileSpec: FileSpec
) {
codeGenerator.createNewFile(
dependencies = Dependencies(
aggregating = false,
sources = listOfNotNull(classDeclaration.containingFile).toTypedArray()
),
packageName = classDeclaration.packageName.asString(),
extensionName = "swift",
fileName = fileSpec.name
).use { output ->
OutputStreamWriter(output, Charsets.UTF_8).use {
fileSpec.writeTo(it)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment