square / javapoet

A Java API for generating .java source files.
Apache License 2.0
10.81k stars 1.37k forks source link

Multiline Strings Forcefully Wrapping With Concatenation Causing Issues #604

Open cretz opened 6 years ago

cretz commented 6 years ago

What would be expected when the following is run?

MethodSpec.builder().addComment("Test: $S", "foo\nbar");

Unfortunately this outputs something like:

// Test: "foo\n"
    "bar"

A bit disappointed and surprising that string literals are always wrapped at newline chars no matter what. Can this change at all? I know that a backwards incompatible break probably won't happen, so another placeholder type?

JakeWharton commented 6 years ago

Changing the generated code, so long as it is semantically the same, isn't backwards incompatible. That said, can you use $L instead of $S here?

On Sun, Jan 21, 2018 at 5:32 PM Chad Retz notifications@github.com wrote:

What would be expected when the following is run?

MethodSpec.builder().addComment("Test: $S", "foo\nbar");

Unfortunately this outputs something like:

// Test: "foo\n" "bar"

A bit disappointed and surprising that string literals are always wrapped at newline chars no matter what. Can this change at all? I know that a backwards incompatible break probably won't happen, so another placeholder type?

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/square/javapoet/issues/604, or mute the thread https://github.com/notifications/unsubscribe-auth/AAEEEcB4vRbHysWufyrGuK5q_wm415yRks5tM7rpgaJpZM4Rl_5k .

cretz commented 6 years ago

@JakeWharton - No, $L wraps on embedded newline too. I need "normal-string-literal". I hacked this up in Kotlin to solve my temporary needs:

fun doubleQuotedString(string: String?) = CodeBlock.of("\$S", string).let {
    // https://github.com/square/javapoet/issues/604 :-(
    var str = it.toString()
    while (true) {
        val endQuoteIndex = str.indexOf("\"\n")
        if (endQuoteIndex == -1) break
        str = str.substring(0, endQuoteIndex) + str.substring(str.indexOf('+', endQuoteIndex) + 3)
    }
    str
}
jdyjjj commented 2 years ago

I want to try to sovle this bug