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

Honour same-package import aliases #1794

Merged
merged 1 commit into from
Jan 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
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