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

Fix a bug caused by too long return expressions #1256

Merged
merged 12 commits into from Jun 1, 2022
15 changes: 14 additions & 1 deletion kotlinpoet/src/main/java/com/squareup/kotlinpoet/FunSpec.kt
Expand Up @@ -114,7 +114,7 @@ public class FunSpec private constructor(
} else if (!isEmptySetter) {
codeWriter.emitCode("·{\n")
codeWriter.indent()
codeWriter.emitCode(body, ensureTrailingNewline = true)
codeWriter.emitCode(body.returnsWithoutLinebreak(), ensureTrailingNewline = true)
codeWriter.unindent()
codeWriter.emit("}\n")
} else {
Expand Down Expand Up @@ -245,6 +245,19 @@ public class FunSpec private constructor(
return null
}

private fun CodeBlock.returnsWithoutLinebreak(): CodeBlock {
val originCodeBlockBuilder = toBuilder()
Egorand marked this conversation as resolved.
Show resolved Hide resolved
val returnWithSpace = "return "
val returnWithNbsp = "return·"
zsqw123 marked this conversation as resolved.
Show resolved Hide resolved
originCodeBlockBuilder.formatParts.clear()
formatParts.mapTo(originCodeBlockBuilder.formatParts) { formatPart ->
Egorand marked this conversation as resolved.
Show resolved Hide resolved
if (formatPart.startsWith(returnWithSpace)) {
formatPart.replaceFirst(returnWithSpace, returnWithNbsp)
} else formatPart
zsqw123 marked this conversation as resolved.
Show resolved Hide resolved
}
return originCodeBlockBuilder.build()
}

override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null) return false
Expand Down
25 changes: 25 additions & 0 deletions kotlinpoet/src/test/java/com/squareup/kotlinpoet/FunSpecTest.kt
Expand Up @@ -206,6 +206,31 @@ class FunSpecTest {
)
}

@Test fun returnsLongExpression() {
val funSpec = FunSpec.builder("foo")
.returns(String::class)
.addStatement("val placeholder = 1")
.addStatement("return \"Loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong\"")
zsqw123 marked this conversation as resolved.
Show resolved Hide resolved
.build()
val sb = StringBuilder()
CodeWriter(sb).use {
funSpec.emit(
codeWriter = it,
enclosingName = null,
implicitModifiers = setOf(KModifier.PUBLIC),
includeKdocTags = false
)
}
assertThat(sb.toString()).isEqualTo(
"""
|public fun foo(): kotlin.String {
| val placeholder = 1
| return "Loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"
|}
|""".trimMargin()
)
}

@Test fun functionParamWithKdoc() {
val funSpec = FunSpec.builder("foo")
.addParameter(
Expand Down