Skip to content

Commit

Permalink
Honour same-package import aliases
Browse files Browse the repository at this point in the history
  • Loading branch information
Egorand committed Jan 7, 2024
1 parent d44d63b commit 4593621
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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(".")
}
Expand Down Expand Up @@ -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,
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down

0 comments on commit 4593621

Please sign in to comment.