pcimcioch.gitlabci.dsl.DslBase.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of gitlab-ci-kotlin-dsl Show documentation
Show all versions of gitlab-ci-kotlin-dsl Show documentation
Library providing Kotlin DSL to configure GitlabCI file
package pcimcioch.gitlabci.dsl
import kotlinx.serialization.Decoder
import kotlinx.serialization.Encoder
import kotlinx.serialization.KSerializer
import kotlinx.serialization.PrimitiveDescriptor
import kotlinx.serialization.PrimitiveKind
import kotlinx.serialization.Serializable
import kotlin.reflect.KClass
@GitlabCiDslMarker
@Serializable(with = DslBase.DslBaseSerializer::class)
abstract class DslBase {
open fun validate(errors: MutableList) {}
companion object {
private val serializers: MutableMap, KSerializer> = mutableMapOf()
internal fun addError(errors: MutableList, condition: Boolean?, message: String) {
if (condition == true) {
errors.add(message)
}
}
internal fun addErrors(errors: MutableList, messagePrefix: String, objs: Collection) {
objs.forEach { addErrors(errors, messagePrefix, it) }
}
internal fun addErrors(errors: MutableList, messagePrefix: String, vararg obj: DslBase?) {
val objErrors = mutableListOf()
obj.forEach { it?.validate(objErrors) }
objErrors.forEach { errors.add("$messagePrefix$it") }
}
internal fun addAndReturn(list: MutableList, element: T): T {
list.add(element)
return element
}
internal fun isEmpty(tested: String?) = (tested == null || "" == tested)
internal fun addSerializer(clazz: KClass, serializer: KSerializer) {
serializers[clazz] = serializer
}
}
object DslBaseSerializer: KSerializer {
override val descriptor = PrimitiveDescriptor("DslBase", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): DslBase {
throw IllegalStateException(descriptor.serialName)
}
override fun serialize(encoder: Encoder, value: DslBase) {
getSerializer(value).serialize(encoder, value)
}
@Suppress("UNCHECKED_CAST")
private fun getSerializer(value: T): KSerializer {
for (serializer in serializers) {
if (serializer.key.isInstance(value)) {
return serializer.value as KSerializer
}
}
throw IllegalStateException("No serializer found for value of type '${value.javaClass.kotlin.qualifiedName}'")
}
}
}