Changes
This commit is contained in:
1 parent
e23373f73b
commit
6ab2e4082e
9 files changed
+229
-88
No files matched your search
@@ -17,7 +17,10 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
fetch-tags: true
|
||||||
- name: Set up JDK 21
|
- name: Set up JDK 21
|
||||||
uses: actions/setup-java@v3
|
uses: actions/setup-java@v3
|
||||||
with:
|
with:
|
||||||
|
|||||||
+31
-9
@@ -1,32 +1,46 @@
|
|||||||
plugins {
|
plugins {
|
||||||
kotlin("jvm") version "2.3.21"
|
kotlin("jvm") version "2.2.21"
|
||||||
id("maven-publish")
|
id("maven-publish")
|
||||||
`java-gradle-plugin`
|
`java-gradle-plugin`
|
||||||
`kotlin-dsl`
|
`kotlin-dsl`
|
||||||
}
|
}
|
||||||
|
|
||||||
val dynamicVersion = providers.provider {
|
val dynamicVersion: String by lazy {
|
||||||
val ref = System.getenv("GITHUB_REF") ?: ""
|
val githubRef = System.getenv("GITHUB_REF") ?: ""
|
||||||
val isSnapshot = ref.endsWith("/master") || ref.endsWith("/main")
|
val releaseTag = System.getenv("GITHUB_REF_NAME") ?: ""
|
||||||
|
val eventName = System.getenv("GITHUB_EVENT_NAME") ?: ""
|
||||||
|
|
||||||
|
// Hvis det er en release eller tag-push i GitHub Actions, bruk taggen direkte
|
||||||
|
if ((eventName == "release" || githubRef.startsWith("refs/tags/")) && releaseTag.isNotBlank()) {
|
||||||
|
releaseTag.removePrefix("v")
|
||||||
|
} else {
|
||||||
|
// Lokalt eller ved vanlig push til main/master: Beregn dynamisk SNAPSHOT via git
|
||||||
|
try {
|
||||||
|
val isSnapshot = githubRef.endsWith("/master") || githubRef.endsWith("/main") || githubRef.isEmpty()
|
||||||
val latestTag = providers.exec {
|
val latestTag = providers.exec {
|
||||||
commandLine("git", "describe", "--tags", "--abbrev=0")
|
commandLine("git", "describe", "--tags", "--abbrev=0")
|
||||||
}.standardOutput.asText.getOrElse("0.0.0").trim().removePrefix("v")
|
}.standardOutput.asText.get().trim().removePrefix("v")
|
||||||
|
|
||||||
if (isSnapshot) {
|
if (isSnapshot) {
|
||||||
val parts = latestTag.split(".")
|
val parts = latestTag.split(".")
|
||||||
val patch = parts.lastOrNull()?.toIntOrNull()?.plus(1) ?: 1
|
val patch = parts.lastOrNull()?.toIntOrNull()?.plus(1) ?: 1
|
||||||
val base = if (parts.size >= 2) "${parts[0]}.${parts[1]}" else latestTag
|
val base = if (parts.size >= 2) "${parts.first()}.${parts[1]}" else latestTag
|
||||||
val buildNumber = providers.exec {
|
val buildNumber = providers.exec {
|
||||||
commandLine("git", "rev-list", "v$latestTag..HEAD", "--count")
|
commandLine("git", "rev-list", "v$latestTag..HEAD", "--count")
|
||||||
}.standardOutput.asText.getOrElse("0").trim().toIntOrNull() ?: 0
|
}.standardOutput.asText.get().trim().toIntOrNull() ?: 0
|
||||||
|
|
||||||
"$base.$patch-SNAPSHOT-$buildNumber"
|
"$base.$patch-SNAPSHOT-$buildNumber"
|
||||||
} else {
|
} else {
|
||||||
latestTag
|
latestTag
|
||||||
}
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
"0.0.1-SNAPSHOT"
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
group = "no.iktdev"
|
group = "no.iktdev"
|
||||||
version = dynamicVersion.get()
|
version = dynamicVersion
|
||||||
val named = "ts-gen"
|
val named = "ts-gen"
|
||||||
|
|
||||||
|
|
||||||
@@ -63,6 +77,14 @@ dependencies {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tasks.jar {
|
||||||
|
manifest {
|
||||||
|
attributes(
|
||||||
|
"Implementation-Title" to project.name,
|
||||||
|
"Implementation-Version" to project.version
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
tasks.test {
|
tasks.test {
|
||||||
useJUnitPlatform()
|
useJUnitPlatform()
|
||||||
@@ -85,7 +107,7 @@ publishing {
|
|||||||
if (name == "pluginMaven") {
|
if (name == "pluginMaven") {
|
||||||
groupId = "no.iktdev"
|
groupId = "no.iktdev"
|
||||||
artifactId = "ts-gen"
|
artifactId = "ts-gen"
|
||||||
version = dynamicVersion.get()
|
version = dynamicVersion
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package no.iktdev.ts
|
||||||
|
|
||||||
|
enum class SealedStrategy {
|
||||||
|
AS_INTERFACE, // Lager kun interfacet (og eventuelt union) uten automatisk type-felt
|
||||||
|
AS_INTERFACE_WITH_TYPE,// Lager interface + union + automatisk type-felt på subtypene
|
||||||
|
ONLY_TYPED // Lager kun unionen/typene uten base-interface
|
||||||
|
}
|
||||||
@@ -5,18 +5,16 @@ import java.io.File
|
|||||||
object TsGenerator {
|
object TsGenerator {
|
||||||
var versionInfo: String = System.getProperty("tsgenerator.version")
|
var versionInfo: String = System.getProperty("tsgenerator.version")
|
||||||
?: TsGenerator::class.java.getPackage()?.implementationVersion
|
?: TsGenerator::class.java.getPackage()?.implementationVersion
|
||||||
?: "dev"
|
?: "any"
|
||||||
var buildTime: String = java.time.Instant.now().toString()
|
var buildTime: String = java.time.Instant.now().toString()
|
||||||
|
|
||||||
val ttm = TsTypeMapper()
|
|
||||||
val tmr = TsModelRenderer()
|
val tmr = TsModelRenderer()
|
||||||
|
|
||||||
fun generate(
|
fun generate(
|
||||||
packageName: String,
|
packageName: String,
|
||||||
output: File,
|
output: File,
|
||||||
classLoader: ClassLoader = Thread.currentThread().contextClassLoader,
|
classLoader: ClassLoader = Thread.currentThread().contextClassLoader,
|
||||||
includeTypedSealed: Boolean = true,
|
writeSealedStrategy: SealedStrategy,
|
||||||
includeTypedInterface: Boolean = true
|
|
||||||
) {
|
) {
|
||||||
println("TsGenerator: scanning package: $packageName")
|
println("TsGenerator: scanning package: $packageName")
|
||||||
|
|
||||||
@@ -35,28 +33,37 @@ object TsGenerator {
|
|||||||
classes.forEach { cls ->
|
classes.forEach { cls ->
|
||||||
when {
|
when {
|
||||||
// ----------------------------------------------------
|
// ----------------------------------------------------
|
||||||
// 1) Sealed interface → union type alias
|
// 1) Sealed interface → union type alias + evt. base interface
|
||||||
// ----------------------------------------------------
|
// ----------------------------------------------------
|
||||||
cls.isSealed && cls.java.isInterface -> {
|
cls.isSealed && cls.java.isInterface -> {
|
||||||
println("Generating union type for sealed interface: ${cls.simpleName}")
|
println("Generating sealed interface: ${cls.simpleName}")
|
||||||
append(tmr.sealedUnionToTs(cls))
|
append(tmr.sealedUnionToTs(cls, writeSealedStrategy))
|
||||||
}
|
}
|
||||||
|
|
||||||
// ----------------------------------------------------
|
// ----------------------------------------------------
|
||||||
// 1a) Sealed class → union type alias
|
// 1a) Sealed class → union type alias + evt. base interface
|
||||||
// ----------------------------------------------------
|
// ----------------------------------------------------
|
||||||
cls.isSealed && !cls.java.isInterface -> {
|
cls.isSealed && !cls.java.isInterface -> {
|
||||||
println("Generating union type for sealed class: ${cls.simpleName}")
|
println("Generating sealed class: ${cls.simpleName}")
|
||||||
append(tmr.sealedUnionToTs(cls))
|
append(tmr.sealedUnionToTs(cls, writeSealedStrategy))
|
||||||
}
|
}
|
||||||
|
|
||||||
// ----------------------------------------------------
|
// ----------------------------------------------------
|
||||||
// 1b) Sealed subtype (data object / data class)
|
// 1b) Sealed subtype (data object / data class)
|
||||||
// → Bruker includeTypedSealed for type-lappen
|
// Sjekker strategien for type-felt og extends-base
|
||||||
// ----------------------------------------------------
|
// ----------------------------------------------------
|
||||||
cls.isSealedSubtype() -> {
|
cls.isSealedSubtype() -> {
|
||||||
println("Generating sealed subtype interface: ${cls.simpleName}")
|
println("Generating sealed subtype interface: ${cls.simpleName}")
|
||||||
append(tmr.dataClassToTs(cls, ttm, includeTypedSealed))
|
|
||||||
|
// Finn baseklassen/interfacet hvis strategien tillater det
|
||||||
|
val baseName = if (writeSealedStrategy != SealedStrategy.ONLY_TYPED) {
|
||||||
|
cls.java.superclass?.kotlin?.takeIf { it.isSealed }?.simpleName
|
||||||
|
?: cls.java.interfaces.map { it.kotlin }.firstOrNull { it.isSealed }?.simpleName
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
append(tmr.sealedSubtypeToTs(cls, writeSealedStrategy, baseName))
|
||||||
}
|
}
|
||||||
|
|
||||||
// ----------------------------------------------------
|
// ----------------------------------------------------
|
||||||
@@ -68,12 +75,11 @@ object TsGenerator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ----------------------------------------------------
|
// ----------------------------------------------------
|
||||||
// 3) Data class → interface
|
// 3) Data class → interface (vanlige klasser)
|
||||||
// → Bruker includeTypedInterface for type-lappen
|
|
||||||
// ----------------------------------------------------
|
// ----------------------------------------------------
|
||||||
cls.hasProperties() && !cls.isSealed -> {
|
cls.hasProperties() && !cls.isSealed -> {
|
||||||
println("Generating interface: ${cls.simpleName}")
|
println("Generating interface: ${cls.simpleName}")
|
||||||
append(tmr.dataClassToTs(cls, ttm, includeTypedInterface))
|
append(tmr.dataClassToTs(cls))
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> {
|
else -> {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package no.iktdev.ts
|
|||||||
|
|
||||||
import kotlin.reflect.KClass
|
import kotlin.reflect.KClass
|
||||||
import kotlin.reflect.full.memberProperties
|
import kotlin.reflect.full.memberProperties
|
||||||
|
import kotlin.reflect.full.primaryConstructor
|
||||||
|
|
||||||
class TsModelRenderer {
|
class TsModelRenderer {
|
||||||
|
|
||||||
@@ -12,24 +13,66 @@ class TsModelRenderer {
|
|||||||
return "export type ${cls.simpleName} = $values\n"
|
return "export type ${cls.simpleName} = $values\n"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Genererer union-typen for sealed klasser (f.eks. export type Progress = A | B | C)
|
// Genererer base-interface (hvis ikke ONLY_TYPED) og union-typen
|
||||||
fun sealedUnionToTs(cls: KClass<*>): String {
|
fun sealedUnionToTs(
|
||||||
|
cls: KClass<*>,
|
||||||
|
strategy: SealedStrategy
|
||||||
|
): String {
|
||||||
val subTypes = cls.sealedSubclasses
|
val subTypes = cls.sealedSubclasses
|
||||||
.mapNotNull { it.simpleName }
|
.mapNotNull { it.simpleName }
|
||||||
.joinToString(" | ")
|
.joinToString(" | ")
|
||||||
|
|
||||||
|
if (strategy == SealedStrategy.ONLY_TYPED) {
|
||||||
return "export type ${cls.simpleName} = $subTypes\n"
|
return "export type ${cls.simpleName} = $subTypes\n"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Genererer standard interface for klasser/subtyper
|
// AS_INTERFACE og AS_INTERFACE_WITH_TYPE lager base-interfacet for sealed-klassen
|
||||||
fun dataClassToTs(
|
val superClasses = getSuperClasses(cls)
|
||||||
cls: KClass<*>,
|
val extendsClause = getExtendsClause(superClasses, null)
|
||||||
ttm: TsTypeMapper,
|
val inheritedPropNames = superClasses.flatMap { it.memberProperties }.map { it.name }.toSet()
|
||||||
includeTypedInterface: Boolean
|
|
||||||
): String {
|
|
||||||
val typeParams = cls.typeParameters.map { it.name }
|
|
||||||
val generic = if (typeParams.isNotEmpty()) "<" + typeParams.joinToString(", ") + ">" else ""
|
|
||||||
|
|
||||||
|
val baseInterface = buildInterfaceString(cls, inheritedPropNames, extendsClause, null)
|
||||||
|
val unionType = "export type ${cls.simpleName}Type = $subTypes\n"
|
||||||
|
|
||||||
|
return listOf(baseInterface, unionType).filter { it.isNotBlank() }.joinToString("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sealed subtype renderer som respekterer om vi skal ha type-felt eller ikke
|
||||||
|
fun sealedSubtypeToTs(
|
||||||
|
cls: KClass<*>,
|
||||||
|
strategy: SealedStrategy,
|
||||||
|
extendsBaseName: String?
|
||||||
|
): String {
|
||||||
|
// Hvis ONLY_TYPED, skal den ikke arve fra eller filtrere ut felter fra baseklassen
|
||||||
|
val superClasses = if (strategy == SealedStrategy.ONLY_TYPED) emptyList() else getSuperClasses(cls)
|
||||||
|
|
||||||
|
// Kun AS_INTERFACE_WITH_TYPE og AS_INTERFACE skal arve fra baseklassen
|
||||||
|
val extraExtends = if (strategy != SealedStrategy.ONLY_TYPED) extendsBaseName else null
|
||||||
|
val extendsClause = getExtendsClause(superClasses, extraExtends)
|
||||||
|
val inheritedPropNames = if (strategy == SealedStrategy.ONLY_TYPED) emptySet() else superClasses.flatMap { it.memberProperties }.map { it.name }.toSet()
|
||||||
|
|
||||||
|
// Type-literalen tvinges KUN på hvis strategien er AS_INTERFACE_WITH_TYPE
|
||||||
|
val typeLiteral = if (strategy == SealedStrategy.AS_INTERFACE_WITH_TYPE) {
|
||||||
|
getDefaultTypeLiteral(cls) ?: cls.simpleName
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
return buildInterfaceString(cls, inheritedPropNames, extendsClause, typeLiteral)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ordinær data-klasse / interface renderer
|
||||||
|
fun dataClassToTs(cls: KClass<*>): String {
|
||||||
|
val superClasses = getSuperClasses(cls)
|
||||||
|
val extendsClause = getExtendsClause(superClasses, null)
|
||||||
|
val inheritedPropNames = superClasses.flatMap { it.memberProperties }.map { it.name }.toSet()
|
||||||
|
|
||||||
|
return buildInterfaceString(cls, inheritedPropNames, extendsClause, null)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Felles hjelpemetoder ---
|
||||||
|
|
||||||
|
private fun getSuperClasses(cls: KClass<*>): List<KClass<*>> {
|
||||||
val superClasses = mutableListOf<KClass<*>>()
|
val superClasses = mutableListOf<KClass<*>>()
|
||||||
val superClass = cls.java.superclass?.kotlin
|
val superClass = cls.java.superclass?.kotlin
|
||||||
if (superClass != null && superClass != Any::class) {
|
if (superClass != null && superClass != Any::class) {
|
||||||
@@ -41,37 +84,64 @@ class TsModelRenderer {
|
|||||||
.filter { it.simpleName != "Any" && it.simpleName != "Serializable" }
|
.filter { it.simpleName != "Any" && it.simpleName != "Serializable" }
|
||||||
|
|
||||||
superClasses.addAll(superInterfaces)
|
superClasses.addAll(superInterfaces)
|
||||||
|
return superClasses
|
||||||
|
}
|
||||||
|
|
||||||
val extendsClause = if (superClasses.isNotEmpty()) {
|
private fun getExtendsClause(superClasses: List<KClass<*>>, extraExtends: String?): String {
|
||||||
" extends " + superClasses.joinToString(", ") { it.simpleName!! }
|
val names = superClasses.map { it.simpleName!! }.toMutableList()
|
||||||
|
if (extraExtends != null && extraExtends !in names) {
|
||||||
|
names.add(extraExtends)
|
||||||
|
}
|
||||||
|
return if (names.isNotEmpty()) {
|
||||||
|
" extends ${names.distinct().joinToString(", ")}"
|
||||||
} else ""
|
} else ""
|
||||||
|
}
|
||||||
|
|
||||||
val inheritedPropNames = superClasses.flatMap { it.memberProperties }.map { it.name }.toSet()
|
private fun buildInterfaceString(
|
||||||
val hasTypeProp = cls.memberProperties.any { it.name == "type" }
|
cls: KClass<*>,
|
||||||
|
inheritedPropNames: Set<String>,
|
||||||
|
extendsClause: String?,
|
||||||
|
forcedTypeLiteral: String?
|
||||||
|
): String {
|
||||||
|
val typeParams = cls.typeParameters.map { it.name }
|
||||||
|
val generic = if (typeParams.isNotEmpty()) "<" + typeParams.joinToString(", ") + ">" else ""
|
||||||
|
val defaultTypeLiteral = getDefaultTypeLiteral(cls)
|
||||||
|
|
||||||
val props = cls.memberProperties
|
val props = cls.memberProperties
|
||||||
.filter { it.name !in inheritedPropNames }
|
.filter { it.name !in inheritedPropNames }
|
||||||
|
.filter { forcedTypeLiteral == null || it.name != "type" }
|
||||||
.joinToString("\n") { prop ->
|
.joinToString("\n") { prop ->
|
||||||
// HVIS feltet heter "type" og vi har slått på includeTypedInterface,
|
val tsType = if (prop.name == "type" && defaultTypeLiteral != null) {
|
||||||
// tvinger vi type-definisjonen til å bli klassens navn som en string-literal!
|
"\"$defaultTypeLiteral\""
|
||||||
val tsType = if (prop.name == "type" && includeTypedInterface) {
|
|
||||||
"\"${cls.simpleName}\""
|
|
||||||
} else {
|
} else {
|
||||||
ttm.kotlinToTsType(prop.returnType.toString(), typeParams)
|
TsTypeMapper.kotlinToTsType(prop.returnType.toString(), typeParams)
|
||||||
}
|
}
|
||||||
" ${prop.name}: $tsType;"
|
" ${prop.name}: $tsType;"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val propsBlock = if (props.isBlank()) "" else "\n$props"
|
||||||
|
|
||||||
return buildString {
|
return buildString {
|
||||||
appendLine("export interface ${cls.simpleName}$generic$extendsClause {")
|
appendLine("export interface ${cls.simpleName}$generic${extendsClause ?: ""} {")
|
||||||
|
if (forcedTypeLiteral != null) {
|
||||||
// Hvis klassen IKKE hadde "type"-felt fra før, men flagget er på, legger vi til lappen her
|
appendLine(" type: \"$forcedTypeLiteral\";$propsBlock")
|
||||||
if (includeTypedInterface && !hasTypeProp && "type" !in inheritedPropNames) {
|
} else if (props.isNotBlank()) {
|
||||||
appendLine(" type: \"${cls.simpleName}\";")
|
appendLine(props)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (props.isNotBlank()) appendLine(props)
|
|
||||||
appendLine("}")
|
appendLine("}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun getDefaultTypeLiteral(cls: KClass<*>): String? {
|
||||||
|
val ctor = cls.primaryConstructor ?: return null
|
||||||
|
ctor.parameters.find { it.name == "type" } ?: return null
|
||||||
|
|
||||||
|
return try {
|
||||||
|
val instance = ctor.callBy(emptyMap())
|
||||||
|
val prop = cls.memberProperties.find { it.name == "type" }
|
||||||
|
prop?.getter?.call(instance)?.toString()
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
package no.iktdev.ts
|
package no.iktdev.ts
|
||||||
|
|
||||||
class TsTypeMapper {
|
object TsTypeMapper {
|
||||||
fun kotlinToTsType(kotlinType: String, genericParams: List<String> = emptyList()): String {
|
fun kotlinToTsType(kotlinType: String, genericParams: List<String> = emptyList()): String {
|
||||||
val isNullable = kotlinType.endsWith("?")
|
val isNullable = kotlinType.endsWith("?")
|
||||||
// Fjerner eventuelle backticks som Kotlin legger rundt lokale/test-klasser, og trimmet
|
// Fjerner eventuelle backticks som Kotlin legger rundt lokale/test-klasser, og trimmet
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package no.iktdev.tsgen
|
package no.iktdev.tsgen
|
||||||
|
|
||||||
|
import no.iktdev.ts.SealedStrategy
|
||||||
import no.iktdev.ts.TsGenerator
|
import no.iktdev.ts.TsGenerator
|
||||||
import org.gradle.api.Plugin
|
import org.gradle.api.Plugin
|
||||||
import org.gradle.api.Project
|
import org.gradle.api.Project
|
||||||
@@ -12,15 +13,13 @@ interface TsGeneratorExtension {
|
|||||||
val packageName: Property<String>
|
val packageName: Property<String>
|
||||||
val outputFile: Property<File>
|
val outputFile: Property<File>
|
||||||
|
|
||||||
val includeTypedSealed: Property<Boolean>
|
val sealedStrategy: Property<SealedStrategy>
|
||||||
val includeTypedInterface: Property<Boolean>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class TsGeneratorPlugin : Plugin<Project> {
|
class TsGeneratorPlugin : Plugin<Project> {
|
||||||
override fun apply(project: Project) {
|
override fun apply(project: Project) {
|
||||||
val extension = project.extensions.create("tsGenerator", TsGeneratorExtension::class.java).apply {
|
val extension = project.extensions.create("tsGenerator", TsGeneratorExtension::class.java).apply {
|
||||||
includeTypedSealed.convention(false)
|
sealedStrategy.convention(SealedStrategy.AS_INTERFACE_WITH_TYPE)
|
||||||
includeTypedInterface.convention(false)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
project.tasks.register("generateTs") {
|
project.tasks.register("generateTs") {
|
||||||
@@ -32,8 +31,7 @@ class TsGeneratorPlugin : Plugin<Project> {
|
|||||||
|
|
||||||
val pkg = extension.packageName.get()
|
val pkg = extension.packageName.get()
|
||||||
val out = extension.outputFile.get()
|
val out = extension.outputFile.get()
|
||||||
val includeTypedSealed = extension.includeTypedSealed.get()
|
val writeSealedStrategy = extension.sealedStrategy.get()
|
||||||
val includeTypedInterface = extension.includeTypedInterface.get()
|
|
||||||
|
|
||||||
// Hent classpath for å lage ClassLoaderen
|
// Hent classpath for å lage ClassLoaderen
|
||||||
val mainSourceSet = project.extensions.getByType(JavaPluginExtension::class.java)
|
val mainSourceSet = project.extensions.getByType(JavaPluginExtension::class.java)
|
||||||
@@ -43,7 +41,7 @@ class TsGeneratorPlugin : Plugin<Project> {
|
|||||||
val cl = URLClassLoader(urls, TsGenerator::class.java.classLoader)
|
val cl = URLClassLoader(urls, TsGenerator::class.java.classLoader)
|
||||||
|
|
||||||
// Kall generatoren med det nye flagget
|
// Kall generatoren med det nye flagget
|
||||||
TsGenerator.generate(pkg, out, cl, includeTypedSealed, includeTypedInterface)
|
TsGenerator.generate(pkg, out, cl, writeSealedStrategy)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,11 +11,10 @@ import org.junit.jupiter.api.Test
|
|||||||
class TsModelRendererTest {
|
class TsModelRendererTest {
|
||||||
|
|
||||||
private val renderer = TsModelRenderer()
|
private val renderer = TsModelRenderer()
|
||||||
private val ttm = TsTypeMapper()
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `should maintain exact property names without renaming`() {
|
fun `should maintain exact property names without renaming`() {
|
||||||
val result = renderer.dataClassToTs(Fancy::class, ttm, true)
|
val result = renderer.dataClassToTs(Fancy::class)
|
||||||
|
|
||||||
// Sjekk at "isFancy" ikke ble endret til "fancy"
|
// Sjekk at "isFancy" ikke ble endret til "fancy"
|
||||||
assertThat(result).contains("isFancy: boolean;")
|
assertThat(result).contains("isFancy: boolean;")
|
||||||
@@ -28,7 +27,7 @@ class TsModelRendererTest {
|
|||||||
@Test
|
@Test
|
||||||
fun `full test - verifiser arv, typer og union`() {
|
fun `full test - verifiser arv, typer og union`() {
|
||||||
// 1. Test Interface Arv
|
// 1. Test Interface Arv
|
||||||
val cameraTs = renderer.dataClassToTs(Camera::class, ttm, true)
|
val cameraTs = renderer.dataClassToTs(Camera::class)
|
||||||
|
|
||||||
assertThat(cameraTs).contains("interface Camera extends BaseDevice")
|
assertThat(cameraTs).contains("interface Camera extends BaseDevice")
|
||||||
assertThat(cameraTs).contains("resolution: number;")
|
assertThat(cameraTs).contains("resolution: number;")
|
||||||
@@ -43,24 +42,62 @@ class TsModelRendererTest {
|
|||||||
fun `should handle generic classes correctly`() {
|
fun `should handle generic classes correctly`() {
|
||||||
data class Wrapper<T>(val data: T, val message: String?)
|
data class Wrapper<T>(val data: T, val message: String?)
|
||||||
|
|
||||||
val result = renderer.dataClassToTs(Wrapper::class, ttm, true)
|
val result = renderer.dataClassToTs(Wrapper::class)
|
||||||
|
|
||||||
assertThat(result).contains("export interface Wrapper<T>")
|
assertThat(result).contains("export interface Wrapper<T>")
|
||||||
assertThat(result).contains("data: T;")
|
assertThat(result).contains("data: T;")
|
||||||
assertThat(result).contains("message: string | null;")
|
assertThat(result).contains("message: string | null;")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class TsModelRendererTest {
|
||||||
|
private val renderer = TsModelRenderer()
|
||||||
|
|
||||||
|
sealed class ASealedDevice
|
||||||
|
data class Sensor(val value: Double) : ASealedDevice()
|
||||||
|
data class Actuator(val active: Boolean) : ASealedDevice()
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `sealed subtype test - verifiser type discriminator`() {
|
fun `sealed union and subtypes - AS_INTERFACE_WITH_TYPE`() {
|
||||||
data class Sensor(val type: String = "TEMP_SENSOR", val value: Double)
|
// 1. Verifiser at hovedklassen blir et interface + union-type
|
||||||
|
val unionTs = renderer.sealedUnionToTs(ASealedDevice::class, SealedStrategy.AS_INTERFACE_WITH_TYPE)
|
||||||
// Bruker dataClassToTs direkte ettersom sealed subtyper nå bruker denne metoden
|
assertThat(unionTs).contains("export interface ASealedDevice")
|
||||||
val sensorTs = renderer.dataClassToTs(Sensor::class, ttm, includeTypedInterface = true)
|
assertThat(unionTs).contains("export type ASealedDeviceType = Actuator | Sensor")
|
||||||
|
|
||||||
|
// 2. Verifiser at subtypen får type-discriminator og arver baseklassen
|
||||||
|
val sensorTs = renderer.sealedSubtypeToTs(Sensor::class, SealedStrategy.AS_INTERFACE_WITH_TYPE, "ASealedDevice")
|
||||||
|
assertThat(sensorTs).contains("export interface Sensor extends ASealedDevice")
|
||||||
assertThat(sensorTs).contains("type: \"Sensor\";")
|
assertThat(sensorTs).contains("type: \"Sensor\";")
|
||||||
assertThat(sensorTs).contains("value: number;")
|
assertThat(sensorTs).contains("value: number;")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `sealed union and subtypes - ONLY_TYPED`() {
|
||||||
|
// 1. Verifiser at ONLY_TYPED kun lager en ren union-type for hovedklassen
|
||||||
|
val unionTs = renderer.sealedUnionToTs(ASealedDevice::class, SealedStrategy.ONLY_TYPED)
|
||||||
|
assertThat(unionTs).isEqualTo("export type ASealedDevice = Actuator | Sensor\n")
|
||||||
|
|
||||||
|
// 2. Verifiser at subtypen IKKE får type-discriminator eller extends-klausul når baseName er null
|
||||||
|
val sensorTs = renderer.sealedSubtypeToTs(Sensor::class, SealedStrategy.ONLY_TYPED, null)
|
||||||
|
assertThat(sensorTs).doesNotContain("type:")
|
||||||
|
assertThat(sensorTs).doesNotContain("extends")
|
||||||
|
assertThat(sensorTs).contains("export interface Sensor {")
|
||||||
|
assertThat(sensorTs).contains("value: number;")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `sealed union and subtypes - AS_INTERFACE`() {
|
||||||
|
// 1. Verifiser at AS_INTERFACE lager base-interface og union-type
|
||||||
|
val unionTs = renderer.sealedUnionToTs(ASealedDevice::class, SealedStrategy.AS_INTERFACE)
|
||||||
|
assertThat(unionTs).contains("export interface ASealedDevice")
|
||||||
|
assertThat(unionTs).contains("export type ASealedDeviceType = Actuator | Sensor")
|
||||||
|
|
||||||
|
// 2. Verifiser at subtypen arver baseklassen, men IKKE har automatisk type-discriminator
|
||||||
|
val sensorTs = renderer.sealedSubtypeToTs(Sensor::class, SealedStrategy.AS_INTERFACE, "ASealedDevice")
|
||||||
|
assertThat(sensorTs).contains("export interface Sensor extends ASealedDevice")
|
||||||
|
assertThat(sensorTs).doesNotContain("type:")
|
||||||
|
assertThat(sensorTs).contains("value: number;")
|
||||||
|
}
|
||||||
|
}
|
||||||
@Test
|
@Test
|
||||||
fun `should generate string literal union for enums`() {
|
fun `should generate string literal union for enums`() {
|
||||||
val result = renderer.enumToTs(DeviceStatus::class)
|
val result = renderer.enumToTs(DeviceStatus::class)
|
||||||
@@ -73,7 +110,7 @@ class TsModelRendererTest {
|
|||||||
open class Base(val id: String)
|
open class Base(val id: String)
|
||||||
data class EmptySub(val type: String = "EmptySub") : Base("123")
|
data class EmptySub(val type: String = "EmptySub") : Base("123")
|
||||||
|
|
||||||
val result = renderer.dataClassToTs(EmptySub::class, ttm, true)
|
val result = renderer.dataClassToTs(EmptySub::class)
|
||||||
|
|
||||||
assertThat(result).contains("export interface EmptySub extends Base")
|
assertThat(result).contains("export interface EmptySub extends Base")
|
||||||
assertThat(result).contains("type: \"EmptySub\";")
|
assertThat(result).contains("type: \"EmptySub\";")
|
||||||
@@ -84,7 +121,7 @@ class TsModelRendererTest {
|
|||||||
data class SubItem(val code: String)
|
data class SubItem(val code: String)
|
||||||
data class Container(val items: List<SubItem>)
|
data class Container(val items: List<SubItem>)
|
||||||
|
|
||||||
val result = renderer.dataClassToTs(Container::class, ttm, false)
|
val result = renderer.dataClassToTs(Container::class)
|
||||||
|
|
||||||
assertThat(result).contains("items: SubItem[];")
|
assertThat(result).contains("items: SubItem[];")
|
||||||
}
|
}
|
||||||
@@ -94,7 +131,7 @@ class TsModelRendererTest {
|
|||||||
open class Parent(val id: String, val createdAt: String)
|
open class Parent(val id: String, val createdAt: String)
|
||||||
data class Child(val name: String, val age: Int) : Parent("default-id", "now")
|
data class Child(val name: String, val age: Int) : Parent("default-id", "now")
|
||||||
|
|
||||||
val result = renderer.dataClassToTs(Child::class, ttm, false)
|
val result = renderer.dataClassToTs(Child::class)
|
||||||
|
|
||||||
assertThat(result).contains("extends Parent")
|
assertThat(result).contains("extends Parent")
|
||||||
assertThat(result).contains("name: string;")
|
assertThat(result).contains("name: string;")
|
||||||
@@ -109,7 +146,7 @@ class TsModelRendererTest {
|
|||||||
data class Sensor(val type: String = "TEMP_SENSOR", val value: Double)
|
data class Sensor(val type: String = "TEMP_SENSOR", val value: Double)
|
||||||
|
|
||||||
// Tester med false for å verifisere at type-lappen utelates
|
// Tester med false for å verifisere at type-lappen utelates
|
||||||
val sensorTs = renderer.dataClassToTs(Sensor::class, ttm, includeTypedInterface = false)
|
val sensorTs = renderer.dataClassToTs(Sensor::class)
|
||||||
|
|
||||||
assertThat(sensorTs).doesNotContain("type: \"Sensor\";")
|
assertThat(sensorTs).doesNotContain("type: \"Sensor\";")
|
||||||
assertThat(sensorTs).contains("value: number;")
|
assertThat(sensorTs).contains("value: number;")
|
||||||
@@ -118,7 +155,7 @@ class TsModelRendererTest {
|
|||||||
@Test
|
@Test
|
||||||
fun `should correctly extend abstract class and avoid duplicated properties`() {
|
fun `should correctly extend abstract class and avoid duplicated properties`() {
|
||||||
// 1. Generer TypeScript fra dummy-klassen
|
// 1. Generer TypeScript fra dummy-klassen
|
||||||
val result = renderer.dataClassToTs(AChild::class, ttm, true)
|
val result = renderer.dataClassToTs(AChild::class)
|
||||||
|
|
||||||
// 2. Verifiser at den utvider den abstrakte klassen
|
// 2. Verifiser at den utvider den abstrakte klassen
|
||||||
assertThat(result).contains("extends AParent")
|
assertThat(result).contains("extends AParent")
|
||||||
|
|||||||
@@ -6,49 +6,47 @@ import org.junit.jupiter.api.Test
|
|||||||
|
|
||||||
class TsTypeMapperTest {
|
class TsTypeMapperTest {
|
||||||
|
|
||||||
private val mapper = TsTypeMapper()
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `should map primitives correctly`() {
|
fun `should map primitives correctly`() {
|
||||||
assertEquals("string", mapper.kotlinToTsType("kotlin.String"))
|
assertEquals("string", TsTypeMapper.kotlinToTsType("kotlin.String"))
|
||||||
assertEquals("number", mapper.kotlinToTsType("kotlin.Int"))
|
assertEquals("number", TsTypeMapper.kotlinToTsType("kotlin.Int"))
|
||||||
assertEquals("number", mapper.kotlinToTsType("kotlin.Double"))
|
assertEquals("number", TsTypeMapper.kotlinToTsType("kotlin.Double"))
|
||||||
assertEquals("boolean", mapper.kotlinToTsType("kotlin.Boolean"))
|
assertEquals("boolean", TsTypeMapper.kotlinToTsType("kotlin.Boolean"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `should map java types to string`() {
|
fun `should map java types to string`() {
|
||||||
assertEquals("string", mapper.kotlinToTsType("java.util.UUID"))
|
assertEquals("string", TsTypeMapper.kotlinToTsType("java.util.UUID"))
|
||||||
assertEquals("string", mapper.kotlinToTsType("java.time.Instant"))
|
assertEquals("string", TsTypeMapper.kotlinToTsType("java.time.Instant"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `should handle nullability`() {
|
fun `should handle nullability`() {
|
||||||
assertEquals("string | null", mapper.kotlinToTsType("kotlin.String?"))
|
assertEquals("string | null", TsTypeMapper.kotlinToTsType("kotlin.String?"))
|
||||||
assertEquals("number | null", mapper.kotlinToTsType("kotlin.Int?"))
|
assertEquals("number | null", TsTypeMapper.kotlinToTsType("kotlin.Int?"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `should map List and Set to arrays`() {
|
fun `should map List and Set to arrays`() {
|
||||||
assertEquals("string[]", mapper.kotlinToTsType("kotlin.collections.List<kotlin.String>"))
|
assertEquals("string[]", TsTypeMapper.kotlinToTsType("kotlin.collections.List<kotlin.String>"))
|
||||||
assertEquals("number[]", mapper.kotlinToTsType("kotlin.collections.MutableSet<kotlin.Int>"))
|
assertEquals("number[]", TsTypeMapper.kotlinToTsType("kotlin.collections.MutableSet<kotlin.Int>"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `should handle nested Map`() {
|
fun `should handle nested Map`() {
|
||||||
val input = "kotlin.collections.Map<kotlin.String, kotlin.Int>"
|
val input = "kotlin.collections.Map<kotlin.String, kotlin.Int>"
|
||||||
assertEquals("Record<string, number>", mapper.kotlinToTsType(input))
|
assertEquals("Record<string, number>", TsTypeMapper.kotlinToTsType(input))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `should handle generic parameters`() {
|
fun `should handle generic parameters`() {
|
||||||
// Antar at "T" er definert i genericParams
|
// Antar at "T" er definert i genericParams
|
||||||
val generics = listOf("T")
|
val generics = listOf("T")
|
||||||
assertEquals("T[]", mapper.kotlinToTsType("kotlin.collections.List<T>", generics))
|
assertEquals("T[]", TsTypeMapper.kotlinToTsType("kotlin.collections.List<T>", generics))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `should handle unknown types by taking simple name`() {
|
fun `should handle unknown types by taking simple name`() {
|
||||||
assertEquals("MyCustomClass", mapper.kotlinToTsType("no.iktdev.models.MyCustomClass"))
|
assertEquals("MyCustomClass", TsTypeMapper.kotlinToTsType("no.iktdev.models.MyCustomClass"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user