From 4593621556298205a01785c7dd26109b77702675 Mon Sep 17 00:00:00 2001 From: Egor Andreevich Date: Fri, 5 Jan 2024 17:09:12 +0100 Subject: [PATCH] Honour same-package import aliases --- .../com/squareup/kotlinpoet/CodeWriter.kt | 14 ++++----- .../com/squareup/kotlinpoet/FileSpecTest.kt | 31 +++++++++++++++++++ 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/kotlinpoet/src/commonMain/kotlin/com/squareup/kotlinpoet/CodeWriter.kt b/kotlinpoet/src/commonMain/kotlin/com/squareup/kotlinpoet/CodeWriter.kt index ff1de0157e..d4489f249a 100644 --- a/kotlinpoet/src/commonMain/kotlin/com/squareup/kotlinpoet/CodeWriter.kt +++ b/kotlinpoet/src/commonMain/kotlin/com/squareup/kotlinpoet/CodeWriter.kt @@ -445,8 +445,8 @@ internal class CodeWriter constructor( return className.canonicalName } - // If the class is in the same package, we're done. - if (packageName == className.packageName) { + // If the class is in the same package and there's no import alias for that class, we're done. + if (packageName == className.packageName && imports[className.canonicalName]?.alias == null) { referencedNames.add(className.topLevelClassName().simpleName) return className.simpleNames.joinToString(".") } @@ -722,11 +722,11 @@ internal class CodeWriter constructor( importsCollector.close() return CodeWriter( - out, - indent, - memberImports + generatedImports.filterKeys { it !in memberImports }, - suggestedTypeImports, - suggestedMemberImports, + out = out, + indent = indent, + imports = memberImports + generatedImports.filterKeys { it !in memberImports }, + importedTypes = suggestedTypeImports, + importedMembers = suggestedMemberImports, ) } diff --git a/kotlinpoet/src/commonTest/kotlin/com/squareup/kotlinpoet/FileSpecTest.kt b/kotlinpoet/src/commonTest/kotlin/com/squareup/kotlinpoet/FileSpecTest.kt index c363f592d0..a855cddc6a 100644 --- a/kotlinpoet/src/commonTest/kotlin/com/squareup/kotlinpoet/FileSpecTest.kt +++ b/kotlinpoet/src/commonTest/kotlin/com/squareup/kotlinpoet/FileSpecTest.kt @@ -500,6 +500,37 @@ class FileSpecTest { ) } + // https://github.com/square/kotlinpoet/issues/1696 + @Test fun aliasedImportInSamePackage() { + val packageName = "com.mypackage" + val className = ClassName(packageName, "StringKey") + val source = FileSpec.builder(packageName, "K") + .addAliasedImport(className, "S") + .addType( + TypeSpec + .objectBuilder("K") + .addProperty( + PropertySpec.builder("test", className) + .initializer("%T(%L)", className, 0) + .build(), + ) + .build(), + ) + .build() + assertThat(source.toString()).isEqualTo( + """ + |package com.mypackage + | + |import com.mypackage.StringKey as S + | + |public object K { + | public val test: S = S(0) + |} + | + """.trimMargin(), + ) + } + @Test fun conflictingParentName() { val source = FileSpec.builder("com.squareup.tacos", "A") .addType(