Skip to content
Open
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 @@ -93,10 +93,17 @@ private List<Statement> flatten(J.If tailIf, Statement tailElse, AtomicReference
J.Block elseBlock = (J.Block) tailElse;
endWhitespace.set(elseBlock.getEnd());
return ListUtils.concat(ifWithoutElse, ListUtils.mapFirst(elseBlock.getStatements(), elseStmt -> {
List<Comment> elsePartComments = tailIf.getElsePart().getPrefix().getComments();
List<Comment> elseComments = elseBlock.getPrefix().getComments();
List<Comment> stmtComments = elseStmt.getPrefix().getComments();
if (!elseComments.isEmpty() || !stmtComments.isEmpty()) {
return elseStmt.withComments(ListUtils.concatAll(elseComments, stmtComments));
if (!elsePartComments.isEmpty() || !elseComments.isEmpty() || !stmtComments.isEmpty()) {
return elseStmt.withPrefix(elseStmt.getPrefix()
.withWhitespace(elsePartComments.isEmpty() ?
elseStmt.getPrefix().getWhitespace() :
tailIf.getElsePart().getPrefix().getWhitespace())
.withComments(ListUtils.concatAll(
elsePartComments,
ListUtils.concatAll(elseComments, stmtComments))));
}
String whitespace = tailIf.getElsePart().getPrefix().getWhitespace();
return elseStmt.withPrefix(elseStmt.getPrefix().withWhitespace(whitespace));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,64 @@ int foo(boolean condition) {
);
}

@Test
void preserveCommentBeforeElseKeyword() {
rewriteRun(
//language=java
java(
"""
class MultilineElseTest {
int foo(boolean condition) {
if (condition) {
return 1;
}
// Handle false condition
else {
return 2;
}
}
}
""",
"""
class MultilineElseTest {
int foo(boolean condition) {
if (condition) {
return 1;
}
// Handle false condition
return 2;
}
}
"""
),
//language=java
java(
"""
class InlineElseTest {
int foo(boolean condition) {
if (condition) {
return 1;
}
// Handle false condition
else { return 2; }
}
}
""",
"""
class InlineElseTest {
int foo(boolean condition) {
if (condition) {
return 1;
}
// Handle false condition
return 2;
}
}
"""
)
);
}

@Test
void complexElseBlock() {
rewriteRun(
Expand Down
Loading