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

Propagate OptIn annotations to generated class #666 #670

Merged
merged 5 commits into from
Sep 7, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 4 additions & 1 deletion docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@ But there is no intent to bump the Ktorfit major version for every KSP update.

## Fixed
- Inheritance problem [#663](https://github.com/Foso/Ktorfit/issues/663)
Please be aware that Ktorfit only generates code for the functions that annotated inside a interface.
Please be aware that Ktorfit only generates code for the functions that are annotated inside a interface.
When you extend a interface that contains no annotated functions, you have to make sure that every function from extended interfaces are
overridden in the interface that you want to use with Ktorfit.
Otherwise you will get compile error because the function missing.

- Generated classes do not propagate opt-in ExperimentalUuidApi [666](https://github.com/Foso/Ktorfit/issues/666)
OptIn annotations on interfaces and functions will now be propagated to the generated classes.

# [2.1.0]()

* Supported Kotlin version: 2.0.0; 2.0.10; 2.0.20
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ fun generateImplClass(
val moduleName =
try {
resolver.getModuleName().getShortName()
} catch (e: AbstractMethodError) {
} catch (e: Throwable) {
""
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package de.jensklingenberg.ktorfit.model
import com.google.devtools.ksp.getDeclaredFunctions
import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.symbol.ClassKind
import com.google.devtools.ksp.symbol.KSAnnotation
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSFile
import com.google.devtools.ksp.symbol.KSPropertyDeclaration
Expand Down Expand Up @@ -30,6 +31,7 @@ data class ClassData(
val properties: List<KSPropertyDeclaration> = emptyList(),
val modifiers: List<KModifier> = emptyList(),
val ksFile: KSFile,
val annotations: List<KSAnnotation>,
) {
val implName = "_${name}Impl"
val providerName = "_${name}Provider"
Expand Down Expand Up @@ -98,6 +100,7 @@ fun KSClassDeclaration.toClassData(logger: KSPLogger): ClassData {
properties = properties,
modifiers = ksClassDeclaration.modifiers.mapNotNull { it.toKModifier() },
ksFile = ksClassDeclaration.getKsFile(),
annotations = ksClassDeclaration.annotations.toList()
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package de.jensklingenberg.ktorfit.model

import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.symbol.KSFunctionDeclaration
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ksp.toAnnotationSpec
import de.jensklingenberg.ktorfit.model.annotations.FunctionAnnotation
import de.jensklingenberg.ktorfit.model.annotations.HttpMethod
import de.jensklingenberg.ktorfit.model.annotations.HttpMethodAnnotation
Expand Down Expand Up @@ -30,7 +32,8 @@ data class FunctionData(
val parameterDataList: List<ParameterData>,
val annotations: List<FunctionAnnotation> = emptyList(),
val httpMethodAnnotation: HttpMethodAnnotation,
val modifiers: List<KModifier> = emptyList()
val modifiers: List<KModifier> = emptyList(),
val optInAnnotations: List<AnnotationSpec>
)

/**
Expand Down Expand Up @@ -226,13 +229,20 @@ fun KSFunctionDeclaration.toFunctionData(logger: KSPLogger): FunctionData {
}
}

val optInAnnotations =
funcDeclaration.annotations
.filter { it.shortName.getShortName() == "OptIn" }
.map { it.toAnnotationSpec() }
.toList()

return FunctionData(
functionName,
returnType,
funcDeclaration.isSuspend,
functionParameters,
functionAnnotationList,
firstHttpMethodAnnotation,
modifiers
modifiers,
optInAnnotations
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.ksp.toAnnotationSpec
import com.squareup.kotlinpoet.ksp.toTypeName
import de.jensklingenberg.ktorfit.KtorfitOptions
import de.jensklingenberg.ktorfit.model.ClassData
Expand Down Expand Up @@ -63,6 +64,8 @@ fun ClassData.getImplClassSpec(
classData.properties.map { property ->
propertySpec(property)
}
val optInAnnotations =
classData.annotations.filter { it.shortName.getShortName() == "OptIn" }.map { it.toAnnotationSpec() }

val implClassSpec =
createImplClassTypeSpec(
Expand All @@ -77,7 +80,8 @@ fun ClassData.getImplClassSpec(
ktorfitOptions.setQualifiedType
)
},
classDataList
classDataList,
optInAnnotations
)

return FileSpec
Expand Down Expand Up @@ -113,10 +117,11 @@ private fun createImplClassTypeSpec(
helperProperty: PropertySpec,
implClassProperties: List<PropertySpec>,
funSpecs: List<FunSpec>,
classDataList: List<ClassData>
classDataList: List<ClassData>,
optInAnnotations: List<AnnotationSpec>
) = TypeSpec
.classBuilder(implClassName)
.addAnnotation(internalApiAnnotation)
.addAnnotations(optInAnnotations + internalApiAnnotation)
.addModifiers(classData.modifiers)
.primaryConstructor(
FunSpec
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ fun FunctionData.toFunSpec(
return FunSpec
.builder(name)
.addModifiers(modifiers)
.addAnnotations(optInAnnotations)
.addParameters(
parameterDataList.map {
it.parameterSpec()
Expand Down Expand Up @@ -71,10 +72,6 @@ private fun FunSpec.Builder.addBody(
"request"
},
typeDataClass.objectName,
if (functionData.returnType.parameterType.isMarkedNullable) {
""
} else {
"!!"
},
"!!".takeIf { !functionData.returnType.parameterType.isMarkedNullable }.orEmpty(),
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package de.jensklingenberg.ktorfit

import com.tschuchort.compiletesting.KotlinCompilation
import com.tschuchort.compiletesting.SourceFile
import com.tschuchort.compiletesting.kspSourcesDir
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.File

class OptInTest {
@Test
fun `when OptIn annotation is used add it to the implementation class`() {
val source =
SourceFile.kotlin(
"Source.kt",
"""package com.example.api
import de.jensklingenberg.ktorfit.http.GET
import de.jensklingenberg.ktorfit.http.Headers
import de.jensklingenberg.ktorfit.http.Header
import de.jensklingenberg.ktorfit.http.HeaderMap
import org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi

@OptIn(ExperimentalCompilerApi::class)
interface TestService {
@Headers(value = ["x:y","a:b"])
@GET("posts")
@OptIn(ExperimentalCompilerApi::class)
suspend fun test(@Header("testHeader") testParameterNonNullable: String?, @Header("testHeader") testParameterNullable: String?, @HeaderMap("testHeaderMap") testParameter2: Map<String,String>): String
}
""",
)

val expectedHeadersArgumentText =
"""@OptIn(ExperimentalCompilerApi::class)
@OptIn(InternalKtorfitApi::class)
public class _TestServiceImpl(
private val _ktorfit: Ktorfit,
) : TestService {
private val _helper: KtorfitConverterHelper = KtorfitConverterHelper(_ktorfit)

@OptIn(ExperimentalCompilerApi::class)
override suspend fun test("""

val compilation = getCompilation(listOf(source))
val result = compilation.compile()
assertEquals(KotlinCompilation.ExitCode.OK, result.exitCode)
val generatedSourcesDir = compilation.kspSourcesDir
val generatedFile =
File(
generatedSourcesDir,
"/kotlin/com/example/api/_TestServiceImpl.kt",
)

val actualSource = generatedFile.readText()
assertTrue(actualSource.contains(expectedHeadersArgumentText))
}
}