Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/schema class generation #81

Merged
merged 18 commits into from
Apr 10, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.schwarz.crystalapi

@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS)
annotation class SchemaClass
jansigi marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.schwarz.crystalapi.schema

interface Schema

interface DatabaseRecord<out T>

class CMField<T : Any>(val name: String, val path: String) : DatabaseRecord<T>

class CMList<T : Any>(val name: String, val path: String) : DatabaseRecord<T>

class CMObject<out T : Schema>(val element: T, val path: String) : DatabaseRecord<T>

class CMObjectList<out T : Schema>(val element: T, val name: String, val path: String) : DatabaseRecord<T>
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package com.schwarz.crystalprocessor

import com.google.auto.service.AutoService
import com.schwarz.crystalapi.*
import com.schwarz.crystalapi.mapify.Mapper
import com.schwarz.crystalapi.query.Queries
import com.schwarz.crystalapi.query.Query
import com.schwarz.crystalprocessor.CoachBaseBinderProcessor.Companion.FRAMEWORK_DOCUMENTATION_FILENAME_OPTION_NAME
import com.schwarz.crystalprocessor.CoachBaseBinderProcessor.Companion.FRAMEWORK_DOCUMENTATION_PATH_OPTION_NAME
import com.schwarz.crystalprocessor.CoachBaseBinderProcessor.Companion.FRAMEWORK_SCHEMA_FILENAME_OPTION_NAME
Expand All @@ -11,17 +15,20 @@ import com.schwarz.crystalprocessor.generation.CodeGenerator
import com.schwarz.crystalprocessor.processing.Worker
import com.schwarz.crystalprocessor.processing.mapper.MapperWorker
import com.schwarz.crystalprocessor.processing.model.ModelWorker
import com.schwarz.crystalapi.*
import com.schwarz.crystalapi.mapify.Mapper
import com.schwarz.crystalapi.query.Queries
import com.schwarz.crystalapi.query.Query
import javax.annotation.processing.*
import javax.lang.model.SourceVersion
import javax.lang.model.element.TypeElement

@SupportedSourceVersion(SourceVersion.RELEASE_17)
@AutoService(Processor::class)
@SupportedOptions(KAPT_KOTLIN_GENERATED_OPTION_NAME, FRAMEWORK_USE_SUSPEND_OPTION_NAME, FRAMEWORK_DOCUMENTATION_PATH_OPTION_NAME, FRAMEWORK_DOCUMENTATION_FILENAME_OPTION_NAME, FRAMEWORK_SCHEMA_PATH_OPTION_NAME, FRAMEWORK_SCHEMA_FILENAME_OPTION_NAME)
@SupportedOptions(
KAPT_KOTLIN_GENERATED_OPTION_NAME,
FRAMEWORK_USE_SUSPEND_OPTION_NAME,
FRAMEWORK_DOCUMENTATION_PATH_OPTION_NAME,
FRAMEWORK_DOCUMENTATION_FILENAME_OPTION_NAME,
FRAMEWORK_SCHEMA_PATH_OPTION_NAME,
FRAMEWORK_SCHEMA_FILENAME_OPTION_NAME
)
class CoachBaseBinderProcessor : AbstractProcessor() {

private lateinit var mLogger: Logger
Expand Down Expand Up @@ -81,6 +88,17 @@ class CoachBaseBinderProcessor : AbstractProcessor() {
}

override fun getSupportedAnnotationTypes(): MutableSet<String> {
return setOf(Field::class.java.canonicalName, Entity::class.java.canonicalName, MapWrapper::class.java.canonicalName, Queries::class.java.canonicalName, Query::class.java.canonicalName, GenerateAccessor::class.java.canonicalName, Mapper::class.java.canonicalName, Reduces::class.java.canonicalName, Reduce::class.java.canonicalName).toMutableSet()
return setOf(
Field::class.java.canonicalName,
Entity::class.java.canonicalName,
MapWrapper::class.java.canonicalName,
SchemaClass::class.java.canonicalName,
Queries::class.java.canonicalName,
Query::class.java.canonicalName,
GenerateAccessor::class.java.canonicalName,
Mapper::class.java.canonicalName,
Reduces::class.java.canonicalName,
Reduce::class.java.canonicalName
).toMutableSet()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
package com.schwarz.crystalprocessor.generation.model

import com.schwarz.crystalapi.schema.*
import com.schwarz.crystalprocessor.model.entity.SchemaClassHolder
import com.schwarz.crystalprocessor.model.field.CblBaseFieldHolder
import com.schwarz.crystalprocessor.model.field.CblFieldHolder
import com.schwarz.crystalprocessor.util.ConversionUtil
import com.schwarz.crystalprocessor.util.TypeUtil
import com.squareup.kotlinpoet.*
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy

/**
* This class is responsible for generating the Schema classes.
*
* To generate a SchemaClass, add the following annotation to your Class:
* ```
* @SchemaClass
* ```
* All the fields will then be generated into a new file.
*/
class SchemaGeneration {
private val pathAttributeName = "path"
fun generateModel(holder: SchemaClassHolder, schemaClassPaths: List<String>): FileSpec {
val packageName = holder.sourcePackage
val schemaClassName = holder.entitySimpleName

val schemaClass: TypeSpec.Builder = buildSchemaClass(schemaClassName)

buildAndAddFieldProperties(holder, schemaClass, schemaClassPaths)

return FileSpec.builder(packageName, schemaClassName).addType(schemaClass.build()).build()
}

private fun buildSchemaClass(className: String): TypeSpec.Builder {
val pathParameter = ParameterSpec.builder(pathAttributeName, String::class).defaultValue("%S", "").build()

return TypeSpec.classBuilder(className)
.addModifiers(KModifier.OPEN)
jansigi marked this conversation as resolved.
Show resolved Hide resolved
.addSuperinterface(Schema::class)
.primaryConstructor(
FunSpec.constructorBuilder()
.addParameter(pathParameter)
.build()
)
}

private fun buildAndAddFieldProperties(
holder: SchemaClassHolder,
schemaClass: TypeSpec.Builder,
schemaClassPaths: List<String>,
) {
buildAndAddConstantFieldProperties(holder, schemaClass, schemaClassPaths)
buildAndAddNormalFieldProperties(holder, schemaClass, schemaClassPaths)
}

private fun buildAndAddConstantFieldProperties(
holder: SchemaClassHolder,
schemaClass: TypeSpec.Builder,
schemaClassPaths: List<String>
) {
holder.fieldConstants.forEach { (fieldName, fieldObject) ->
val defaultVariableName = "DEFAULT_${fieldObject.constantName}"
jansigi marked this conversation as resolved.
Show resolved Hide resolved

val constantProperty = PropertySpec.builder(
defaultVariableName,
fieldObject.fieldType
).initializer(
ConversionUtil.convertStringToDesiredFormat(
fieldObject.typeMirror,
fieldObject.constantValue
)
)

schemaClass.addProperty(constantProperty.build())

buildAndAddFieldProperty(
schemaClass,
fieldName,
fieldObject,
schemaClassPaths
)
}
}

private fun buildAndAddNormalFieldProperties(
holder: SchemaClassHolder,
schemaClass: TypeSpec.Builder,
schemaClassPaths: List<String>
) {
holder.fields.forEach { (fieldName, fieldObject) ->
buildAndAddFieldProperty(
schemaClass,
fieldName,
fieldObject,
schemaClassPaths,
)
}
}

private fun buildAndAddFieldProperty(
schemaClass: TypeSpec.Builder,
fieldName: String,
fieldObject: CblBaseFieldHolder,
schemaClassPaths: List<String>,
): TypeSpec.Builder = schemaClass.addProperty(
buildFieldProperty(fieldObject, fieldName, schemaClassPaths)
)

private fun buildFieldProperty(
fieldObject: CblBaseFieldHolder,
fieldName: String,
schemaClassPaths: List<String>,
): PropertySpec {
val isObject = schemaClassPaths.contains(fieldObject.typeMirror.toString())

val outerType = getOuterPropertyType(fieldObject.isIterable, isObject)

val innerType: TypeName = getInnerPropertyType(fieldObject)

return PropertySpec.builder(
fieldName,
outerType.parameterizedBy(innerType)
).initializer(
createPropertyFormat(fieldName, innerType, fieldObject.isIterable, isObject),
outerType,
).build()
}

private fun createPropertyFormat(
fieldName: String,
propertyType: TypeName,
isIterable: Boolean,
isObject: Boolean
): String {
val propertyAccessPath =
"if ($pathAttributeName.isBlank()) \"$fieldName\" else \"\$$pathAttributeName.$fieldName\""

return when {
isIterable && isObject -> buildObjectListFormat(propertyType, fieldName, propertyAccessPath)
isObject -> buildObjectFormat(propertyType, propertyAccessPath)
else -> buildSimpleFormat(fieldName)
}
}

private fun buildObjectListFormat(propertyType: TypeName, fieldName: String, propertyAccessPath: String): String =
"""%T(
$propertyType($propertyAccessPath),
"$fieldName",
$pathAttributeName,
)"""

private fun buildSimpleFormat(fieldName: String): String =
"""%T("$fieldName", $pathAttributeName)"""

private fun buildObjectFormat(propertyType: TypeName, propertyAccessPath: String): String =
"""%T(
$propertyType($propertyAccessPath),
$pathAttributeName,
)"""

private fun getOuterPropertyType(
isIterable: Boolean,
isObject: Boolean
) = when {
isIterable && isObject -> CMObjectList::class.asTypeName()
isIterable -> CMList::class.asTypeName()
isObject -> CMObject::class.asTypeName()
else -> CMField::class.asTypeName()
}

private fun getInnerPropertyType(field: CblBaseFieldHolder): TypeName {
val subEntity = (field as? CblFieldHolder)?.subEntitySimpleName

return TypeUtil.parseMetaType(field.typeMirror, false, subEntity)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import com.schwarz.crystalprocessor.model.entity.BaseModelHolder
import com.schwarz.crystalprocessor.model.entity.EntityHolder
import com.schwarz.crystalprocessor.model.entity.ReducedModelHolder
import com.schwarz.crystalprocessor.model.entity.WrapperEntityHolder
import com.schwarz.crystalprocessor.model.entity.SchemaClassHolder
import com.schwarz.crystalprocessor.model.field.CblConstantHolder
import com.schwarz.crystalprocessor.model.field.CblFieldHolder
import com.schwarz.crystalprocessor.model.id.DocIdHolder
Expand All @@ -16,10 +17,12 @@ import com.schwarz.crystalprocessor.model.source.ISourceModel
import com.schwarz.crystalprocessor.util.FieldExtractionUtil

object EntityFactory {
private const val WRAPPER_SUB_ENTITY_SUFFIX = "Wrapper"
private const val SCHEMA_SUB_ENTITY_SUFFIX = "Schema"

fun createEntityHolder(
sourceModel: ISourceModel,
allWrappers: List<String>,
allWrapperPaths: List<String>,
allBaseModels: Map<String, BaseModelHolder>
): EntityHolder {
val annotation = sourceModel.entityAnnotation!!
Expand All @@ -29,54 +32,70 @@ object EntityFactory {
annotation.database,
annotation.modifierOpen,
annotation.type,
sourceModel
sourceModel,
),
allWrappers,
allBaseModels
allWrapperPaths,
allBaseModels,
WRAPPER_SUB_ENTITY_SUFFIX,
) as EntityHolder
}

fun createBaseModelHolder(
sourceModel: ISourceModel,
allWrappers: List<String>
allWrapperPaths: List<String>
): BaseModelHolder {
return create(
sourceModel,
BaseModelHolder(sourceModel),
allWrappers,
emptyMap()
allWrapperPaths,
emptyMap(),
WRAPPER_SUB_ENTITY_SUFFIX,
) as BaseModelHolder
}

fun createChildEntityHolder(
sourceModel: ISourceModel,
allWrappers: List<String>,
allWrapperPaths: List<String>,
allBaseModels: Map<String, BaseModelHolder>
): WrapperEntityHolder {
val annotation = sourceModel.mapWrapperAnnotation!!
return create(
sourceModel,
WrapperEntityHolder(annotation.modifierOpen, sourceModel),
allWrappers,
allBaseModels
allWrapperPaths,
allBaseModels,
WRAPPER_SUB_ENTITY_SUFFIX,
) as WrapperEntityHolder
}

fun createSchemaEntityHolder(
sourceModel: ISourceModel,
allSchemaClassPaths: List<String>,
allBaseModels: Map<String, BaseModelHolder>
): SchemaClassHolder = create(
sourceModel,
SchemaClassHolder(sourceModel),
allSchemaClassPaths,
allBaseModels,
SCHEMA_SUB_ENTITY_SUFFIX,
) as SchemaClassHolder

private fun create(
sourceModel: ISourceModel,
content: BaseEntityHolder,
allWrappers: List<String>,
allBaseModels: Map<String, BaseModelHolder>
classPaths: List<String>,
allBaseModels: Map<String, BaseModelHolder>,
subEntityNameSuffix: String,
): BaseEntityHolder {
content.reducesModels = createReduceModels(sourceModel, content, allWrappers, allBaseModels)
content.reducesModels = createReduceModels(sourceModel, content)
content.abstractParts = sourceModel.abstractParts
content.comment = sourceModel.commentAnnotation?.comment ?: arrayOf()
content.deprecated = sourceModel.deprecatedAnnotation?.let { DeprecatedModel(it) }

addBasedOn(sourceModel, allBaseModels, content)

parseQueries(sourceModel, content)
parseFields(sourceModel, content, allWrappers, allBaseModels)
parseFields(sourceModel, content, classPaths, subEntityNameSuffix)

val docId = sourceModel.docIdAnnotation
val docIdSegments: MutableList<DocIdSegmentHolder> = mutableListOf()
Expand Down Expand Up @@ -116,9 +135,7 @@ object EntityFactory {

private fun createReduceModels(
sourceModel: ISourceModel,
content: BaseEntityHolder,
allWrappers: List<String>,
allBaseModels: Map<String, BaseModelHolder>
content: BaseEntityHolder
): List<ReducedModelHolder> {
sourceModel.reduceAnnotations.let { reduce ->
return reduce.map {
Expand Down Expand Up @@ -169,14 +186,14 @@ object EntityFactory {
private fun parseFields(
sourceModel: ISourceModel,
content: BaseEntityHolder,
allWrappers: List<String>,
allBaseModels: Map<String, BaseModelHolder>
classPaths: List<String>,
subEntityNameSuffix: String
) {
for (cblField in sourceModel.fieldAnnotations) {
if (cblField.readonly) {
content.fieldConstants[cblField.name] = CblConstantHolder(cblField)
} else {
val cblFieldHolder = CblFieldHolder(cblField, allWrappers)
val cblFieldHolder = CblFieldHolder(cblField, classPaths, subEntityNameSuffix)
content.fields[cblField.name] = cblFieldHolder
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.schwarz.crystalprocessor.model.entity

import com.schwarz.crystalprocessor.model.source.ISourceModel

class SchemaClassHolder(sourceModel: ISourceModel) : BaseEntityHolder(sourceModel) {
jansigi marked this conversation as resolved.
Show resolved Hide resolved

override val entitySimpleName: String
get() = sourceClazzSimpleName + "Schema"
}
Loading