From 7f2df80bef9fcae423f0a90e6444e4846298c26e Mon Sep 17 00:00:00 2001 From: Kevin Wooten Date: Wed, 20 Dec 2023 01:46:28 -0700 Subject: [PATCH] Fix incorrect importing of local types --- .../java/io/outfoxx/swiftpoet/CodeWriter.kt | 3 ++ .../java/io/outfoxx/swiftpoet/ImportSpec.kt | 4 +++ .../outfoxx/swiftpoet/test/FileSpecTests.kt | 33 +++++++++++++++++++ 3 files changed, 40 insertions(+) diff --git a/src/main/java/io/outfoxx/swiftpoet/CodeWriter.kt b/src/main/java/io/outfoxx/swiftpoet/CodeWriter.kt index 38a91dcd7..befd0290f 100644 --- a/src/main/java/io/outfoxx/swiftpoet/CodeWriter.kt +++ b/src/main/java/io/outfoxx/swiftpoet/CodeWriter.kt @@ -271,6 +271,9 @@ internal class CodeWriter( } private fun referenceTypeName(typeName: DeclaredTypeName) { + if (typeName.moduleName.isEmpty()) { + return + } referencedTypes[typeName.canonicalName] = typeName } diff --git a/src/main/java/io/outfoxx/swiftpoet/ImportSpec.kt b/src/main/java/io/outfoxx/swiftpoet/ImportSpec.kt index c4e6876a1..ef65e9756 100644 --- a/src/main/java/io/outfoxx/swiftpoet/ImportSpec.kt +++ b/src/main/java/io/outfoxx/swiftpoet/ImportSpec.kt @@ -59,6 +59,10 @@ class ImportSpec internal constructor( internal val doc = CodeBlock.builder() internal val guardTest = CodeBlock.builder() + init { + require(name.isNotBlank()) { "name is empty" } + } + fun addDoc(format: String, vararg args: Any) = apply { doc.add(format, *args) } diff --git a/src/test/java/io/outfoxx/swiftpoet/test/FileSpecTests.kt b/src/test/java/io/outfoxx/swiftpoet/test/FileSpecTests.kt index 403dc70cc..deb84355b 100644 --- a/src/test/java/io/outfoxx/swiftpoet/test/FileSpecTests.kt +++ b/src/test/java/io/outfoxx/swiftpoet/test/FileSpecTests.kt @@ -366,7 +366,40 @@ class FileSpecTests { ) ) } + @Test + @DisplayName("Emits local module types without import") + fun testLocalTypesAreNotImported() { + val type = + TypeSpec.structBuilder("SomeType") + .addProperty( + PropertySpec.varBuilder( + "myStuff", + typeName(".MyStuff") + ).build() + ) + .build() + + val testFile = FileSpec.builder("Test", "Test") + .addType(type) + .build() + + val out = StringWriter() + testFile.writeTo(out) + + assertThat( + out.toString(), + equalTo( + """ + struct SomeType { + var myStuff: MyStuff + + } + + """.trimIndent() + ) + ) + } @Test @DisplayName("Generates guarded imports") fun testGenGuardedImports() {