Skip to content

Commit

Permalink
Fix CRLF in the stringTemplate (#411)
Browse files Browse the repository at this point in the history
  • Loading branch information
kunli2 authored Nov 15, 2023
1 parent 9d0a205 commit 1c21420
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2955,9 +2955,19 @@ public J visitStringTemplateExpression(KtStringTemplateExpression expression, Ex
);
}

String valueSource = expression.getText();
StringBuilder valueSb = new StringBuilder();
Arrays.stream(entries).forEach(x -> valueSb.append(x.getText()));
Arrays.stream(entries).forEach(entry -> valueSb.append(maybeAdjustCRLF(entry))
);

PsiElement openQuote = expression.getFirstChild();
PsiElement closingQuota = expression.getLastChild();
if (openQuote == null || closingQuota == null ||
openQuote.getNode().getElementType() != KtTokens.OPEN_QUOTE ||
closingQuota.getNode().getElementType() != KtTokens.CLOSING_QUOTE) {
throw new UnsupportedOperationException("This should never happen");
}

String valueSource = openQuote.getText() + valueSb + closingQuota.getText();

return new J.Literal(
randomId(),
Expand Down Expand Up @@ -3866,7 +3876,8 @@ private Space toSpace(@Nullable PsiElement element) {
// replace `\n` to CRLF back if it's CRLF in the source
private String maybeAdjustCRLF(PsiElement element) {
String text = element.getText();
if (!isSpace(element.getNode())) {
boolean isStringTemplateEntry = element instanceof KtLiteralStringTemplateEntry;
if (!isSpace(element.getNode()) && !isStringTemplateEntry) {
return text;
}

Expand Down
14 changes: 14 additions & 0 deletions src/test/java/org/openrewrite/kotlin/tree/CRLFTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package org.openrewrite.kotlin.tree;

import org.junit.jupiter.api.Test;
import org.openrewrite.Issue;
import org.openrewrite.test.RewriteTest;

import static org.openrewrite.kotlin.Assertions.kotlin;
Expand Down Expand Up @@ -82,4 +83,17 @@ void crlfInBlockComment() {
)
);
}

@Issue("https://github.com/openrewrite/rewrite-kotlin/issues/402")
@Test
void crlfInMultilineString() {
rewriteRun(
kotlin(
"val s = \"\"\"\r\n" +
"l1\r\n" +
"l2\n" +
"\"\"\""
)
);
}
}

0 comments on commit 1c21420

Please sign in to comment.