Skip to content

Commit

Permalink
Remove wildcard imports (#472)
Browse files Browse the repository at this point in the history
  • Loading branch information
Foso authored Oct 29, 2023
1 parent c4b0a57 commit cc1bfb1
Show file tree
Hide file tree
Showing 15 changed files with 45 additions and 46 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.TypeVariableName
import com.squareup.kotlinpoet.ksp.toKModifier
import com.squareup.kotlinpoet.ksp.toTypeName
import de.jensklingenberg.ktorfit.model.KtorfitError.Companion.PROPERTIES_NOT_SUPPORTED
Expand All @@ -43,8 +42,6 @@ data class ClassData(
val ksFile: KSFile
)

const val WILDCARDIMPORT = "WILDCARDIMPORT"

/**
* Transform a [ClassData] to a [FileSpec] for KotlinPoet
*/
Expand Down Expand Up @@ -100,9 +97,10 @@ fun ClassData.getImplClassFileSource(resolver: Resolver): String {
.addModifiers(KModifier.PRIVATE)
.build()

val converterProperty = PropertySpec.builder("_converter", internalKtorfitClientType)
.initializer("%T(${ktorfitClass.objectName})", internalKtorfitClientType)
.build()
val converterProperty =
PropertySpec.builder(converterHelper.objectName, converterHelper.toClassName())
.initializer("%T(${ktorfitClass.objectName})", converterHelper.toClassName())
.build()

val implClassSpec = TypeSpec.classBuilder(implClassName)
.primaryConstructor(
Expand All @@ -116,10 +114,8 @@ fun ClassData.getImplClassFileSource(resolver: Resolver): String {
.addModifiers(classData.modifiers)
.addSuperinterface(ClassName(classData.packageName, classData.name))
.addKtorfitSuperInterface(classData.superClasses)
.addProperties(listOf(converterProperty, ktorfitProperty) + properties)
.addFunctions(classData.functions.map { it.toFunSpec(resolver) })
.addProperty(converterProperty)
.addProperty(ktorfitProperty)
.addProperties(properties)
.build()

return FileSpec.builder(classData.packageName, implClassName)
Expand All @@ -130,7 +126,6 @@ fun ClassData.getImplClassFileSource(resolver: Resolver): String {
.addFunction(createExtensionFunctionSpec)
.build()
.toString()
.replace(WILDCARDIMPORT, "*")
}

/**
Expand All @@ -143,7 +138,7 @@ private fun getCreateExtensionFunctionSpec(
.addModifiers(classData.modifiers)
.addStatement("return this.create(_${classData.name}Impl(this))")
.receiver(ktorfitClass.toClassName())
.returns(TypeVariableName(classData.name))
.returns(ClassName(classData.packageName, classData.name))
.build()
}

Expand All @@ -156,11 +151,17 @@ private fun getCreateExtensionFunctionSpec(
fun KSClassDeclaration.toClassData(logger: KSPLogger): ClassData {
val ksClassDeclaration = this
val imports = mutableListOf(
"io.ktor.util.reflect.*",
"io.ktor.client.request.*",
"io.ktor.http.*",
ktorfitClass.packageName + "." + ktorfitClass.name,
"de.jensklingenberg.ktorfit.internal.*"
"io.ktor.util.reflect.typeInfo",
"io.ktor.client.request.HttpRequestBuilder",
"io.ktor.client.request.setBody",
"io.ktor.client.request.headers",
"io.ktor.client.request.parameter",
"io.ktor.http.URLBuilder",
"io.ktor.http.HttpMethod",
"io.ktor.http.takeFrom",
"io.ktor.http.decodeURLQueryComponent",
"io.ktor.http.encodeURLPath",
typeDataClass.packageName + "." + typeDataClass.name,
)

val packageName = ksClassDeclaration.packageName.asString()
Expand Down Expand Up @@ -241,7 +242,7 @@ private fun KSClassDeclaration.getKsFile(): KSFile {
* Support for extending multiple interfaces, is done with Kotlin delegation. Ktorfit interfaces can only extend other Ktorfit interfaces, so there will
* be a generated implementation for each interface that we can use.
*/
fun TypeSpec.Builder.addKtorfitSuperInterface(superClasses: List<KSTypeReference>): TypeSpec.Builder {
private fun TypeSpec.Builder.addKtorfitSuperInterface(superClasses: List<KSTypeReference>): TypeSpec.Builder {
(superClasses).forEach { superClassReference ->
val superClassDeclaration = superClassReference.resolve().declaration
val superTypeClassName = superClassDeclaration.simpleName.asString()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import com.google.devtools.ksp.symbol.KSFunctionDeclaration
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterSpec
import com.squareup.kotlinpoet.TypeVariableName
import com.squareup.kotlinpoet.ksp.toTypeName
import de.jensklingenberg.ktorfit.model.annotations.*
import de.jensklingenberg.ktorfit.model.annotations.ParameterAnnotation.*
Expand Down Expand Up @@ -47,17 +46,18 @@ data class FunctionData(
)
.addStatement(
getTypeDataArgumentText(
this,
this.returnType,
)
)
.addStatement(
"return %L.%L<${returnTypeName}, ${innerReturnType}>(${typeDataClass.objectName},${extDataClass.objectName})%L",
"_converter",
"return %L.%L<${returnTypeName}, ${innerReturnType}>(%L,${extDataClass.objectName})%L",
converterHelper.objectName,
if (this.isSuspend) {
"suspendRequest"
} else {
"request"
},
typeDataClass.objectName,
if (this.returnType.isNullable) {
""
} else {
Expand Down Expand Up @@ -98,7 +98,7 @@ fun KSFunctionDeclaration.toFunctionData(
val returnType = ReturnTypeData(
name = resolvedReturnType.resolveTypeName(),
qualifiedName = resolvedReturnType?.toTypeName().toString(),
parameterType = funcDeclaration.returnType
parameterType = funcDeclaration.returnType?.resolve()
)

val functionAnnotationList = mutableListOf<FunctionAnnotation>()
Expand Down Expand Up @@ -217,7 +217,7 @@ fun KSFunctionDeclaration.toFunctionData(
val pathAnnotation = it.findAnnotationOrNull<Path>()
if (!firstHttpMethodAnnotation.path.contains("{${pathAnnotation?.value ?: ""}}")) {
logger.error(
KtorfitError.MISSING_X_IN_RELATIVE_URL_PATH(pathAnnotation?.value ?: ""),
KtorfitError.MISSING_X_IN_RELATIVE_URL_PATH(pathAnnotation?.value.orEmpty()),
funcDeclaration
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ val ktorfitClass = KtorfitClass("Ktorfit", "de.jensklingenberg.ktorfit", "_ktorf
val typeDataClass = KtorfitClass("TypeData", "de.jensklingenberg.ktorfit.internal", "_typeData")
val extDataClass = KtorfitClass("HttpRequestBuilder.() -> Unit", "", "_ext")
val formParameters = KtorfitClass("", "", "__formParameters")
val converterHelper = KtorfitClass("KtorfitConverterHelper","de.jensklingenberg.ktorfit.internal", "_converter")
val internalApi = ClassName("de.jensklingenberg.ktorfit.internal", "InternalKtorfitApi")
val internalKtorfitClientType = ClassName("de.jensklingenberg.ktorfit.internal", "KtorfitConverterHelper")

fun KtorfitClass.toClassName() = ClassName(packageName, name)
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,13 @@ fun KSValueParameter.createParameterData(logger: KSPLogger): ParameterData {
ReturnTypeData(
"HttpRequestBuilder.()->Unit",
"HttpRequestBuilder.()->Unit",
ksValueParameter.type,
parameterType,
)
} else {
ReturnTypeData(
parameterType.resolveTypeName(),
parameterType.declaration.qualifiedName?.asString().orEmpty(),
ksValueParameter.type,
parameterType,
)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package de.jensklingenberg.ktorfit.model

import com.google.devtools.ksp.symbol.KSTypeReference
import com.google.devtools.ksp.symbol.KSType


data class ReturnTypeData(
val name: String,
val qualifiedName: String,
val parameterType: KSTypeReference?
val parameterType: KSType?
) {
val isNullable: Boolean = name.endsWith("?")
val innerTypeName = name.substringAfter("<").substringBeforeLast(">")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ fun getFieldArgumentsText(params: List<ParameterData>, listType: KSType, arrayTy
val encoded = field.encoded
val paramName = parameterData.name
val fieldValue = field.value
val starProj = parameterData.type.parameterType?.resolve()?.starProjection()
val starProj = parameterData.type.parameterType?.starProjection()

val isList = starProj?.isAssignableFrom(listType) ?: false
val isArray = starProj?.isAssignableFrom(arrayType) ?: false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ fun getHeadersCode(
.joinToString("") { parameterData ->
val paramName = parameterData.name

val starProj = parameterData.type.parameterType?.resolve()?.starProjection()
val starProj = parameterData.type.parameterType?.starProjection()
val isList = starProj?.isAssignableFrom(listType) ?: false
val isArray = starProj?.isAssignableFrom(arrayType) ?: false

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ fun getPartsCode(params: List<ParameterData>, listType: KSType, arrayType: KSTyp
val name = parameterData.name
val partValue = part.value

val starProj = parameterData.type.parameterType?.resolve()?.starProjection()
val starProj = parameterData.type.parameterType?.starProjection()
val isList = starProj?.isAssignableFrom(listType) ?: false
val isArray = starProj?.isAssignableFrom(arrayType) ?: false

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ private fun getQueryNameText(
val encoded = queryName.encoded
val name = parameterData.name

val starProj = parameterData.type.parameterType?.resolve()?.starProjection()
val starProj = parameterData.type.parameterType?.starProjection()
val isList = starProj?.isAssignableFrom(listType) ?: false
val isArray = starProj?.isAssignableFrom(arrayType) ?: false

Expand Down Expand Up @@ -73,7 +73,7 @@ private fun getQueryText(
) = params.filter { it.hasAnnotation<Query>() }.joinToString(separator = "") { parameterData ->
val query = parameterData.annotations.filterIsInstance<Query>().first()
val encoded = query.encoded
val starProj = parameterData.type.parameterType?.resolve()?.starProjection()
val starProj = parameterData.type.parameterType?.starProjection()
val isList = starProj?.isAssignableFrom(listType) ?: false
val isArray = starProj?.isAssignableFrom(arrayType) ?: false

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,6 @@ fun getReqBuilderExtensionText(functionData: FunctionData, resolver: Resolver):
).filter { it.isNotEmpty() }
.joinToString("\n") { it }

return "val ${extDataClass.objectName}: HttpRequestBuilder.() -> Unit = {\n$args \n}"
return "val ${extDataClass.objectName}: ${extDataClass.name} = {\n$args \n}"
}

Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.ksp.toClassName
import de.jensklingenberg.ktorfit.model.ParameterData
import de.jensklingenberg.ktorfit.model.annotations.ParameterAnnotation.RequestType
import de.jensklingenberg.ktorfit.model.converterHelper

fun FunSpec.Builder.addRequestConverterText(parameterDataList: List<ParameterData>) = apply {
if (parameterDataList.any { it.hasAnnotation<RequestType>() }) {
Expand All @@ -15,7 +16,7 @@ fun FunSpec.Builder.addRequestConverterText(parameterDataList: List<ParameterDat
"val %L: %T = %L.convertParameterType(%L,%L::class,%T::class)",
parameter.name,
requestTypeClassName,
"_converter",
converterHelper.objectName,
parameter.name,
parameter.name,
requestTypeClassName
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package de.jensklingenberg.ktorfit.typeData


import de.jensklingenberg.ktorfit.model.FunctionData
import de.jensklingenberg.ktorfit.model.ReturnTypeData
import de.jensklingenberg.ktorfit.model.typeDataClass
import de.jensklingenberg.ktorfit.utils.removeWhiteSpaces

fun getTypeDataArgumentText(functionData: FunctionData): String {
fun getTypeDataArgumentText(returnTypeData: ReturnTypeData): String {

val returnTypeName = "qualifiedTypename = \"${functionData.returnType.qualifiedName.removeWhiteSpaces()}\""
val returnTypeInfo = getReturnTypeInfoText(functionData.returnType.name)
val returnTypeName = "qualifiedTypename = \"${returnTypeData.qualifiedName.removeWhiteSpaces()}\""
val returnTypeInfo = getReturnTypeInfoText(returnTypeData.name)
val args = listOf(
returnTypeName,
returnTypeInfo
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
package de.jensklingenberg.ktorfit.utils

import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSName
import com.google.devtools.ksp.symbol.KSType
import com.squareup.kotlinpoet.FileSpec
import de.jensklingenberg.ktorfit.model.FunctionData
import de.jensklingenberg.ktorfit.model.WILDCARDIMPORT
import java.io.File

fun KSType?.resolveTypeName(): String {
//TODO: Find better way to handle type alias Types
Expand Down Expand Up @@ -42,7 +39,7 @@ fun FileSpec.Builder.addImports(imports: List<String>): FileSpec.Builder {
* after Kotlin Poet generated the source code
*/
val packageName = it.substringBeforeLast(".")
val className = it.substringAfterLast(".").replace("*", WILDCARDIMPORT)
val className = it.substringAfterLast(".")

this.addImport(packageName, className)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ interface TestService {
)


val notExpectedBodyDataArgumentText = "setBody"
val notExpectedBodyDataArgumentText = "setBody("

val compilation = getCompilation(listOf(source))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ class HeaderCodeGeneratorKtTest {

val parameterData = ParameterData(
"test1",
ReturnTypeData("List<String>", "kotlin.collections.List", typeRef),
ReturnTypeData("List<String>", "kotlin.collections.List", typeRef.resolve()),
annotations = listOf(Header("foo"))
)
val params = listOf(parameterData)
Expand All @@ -73,7 +73,7 @@ class HeaderCodeGeneratorKtTest {

val parameterData = ParameterData(
"test1",
ReturnTypeData("Array<String>", "kotlin.Array", typeRef),
ReturnTypeData("Array<String>", "kotlin.Array", typeRef.resolve()),
annotations = listOf(Header("foo"))
)
val params = listOf(parameterData)
Expand Down

0 comments on commit cc1bfb1

Please sign in to comment.