2323import org .openrewrite .java .JavaVisitor ;
2424import org .openrewrite .java .tree .Comment ;
2525import org .openrewrite .java .tree .J ;
26+ import org .openrewrite .java .tree .Space ;
2627import org .openrewrite .java .tree .Statement ;
2728
2829import java .time .Duration ;
29- import java .util .ArrayList ;
3030import java .util .Arrays ;
3131import java .util .List ;
32+ import java .util .concurrent .atomic .AtomicReference ;
3233
3334public class UnwrapElseAfterReturn extends Recipe {
3435
@@ -54,7 +55,7 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {
5455 @ Override
5556 public J .Block visitBlock (J .Block block , ExecutionContext ctx ) {
5657 J .Block b = visitAndCast (block , ctx , super ::visitBlock );
57- List < Comment > endComments = new ArrayList <>();
58+ AtomicReference < Space > endWhitespace = new AtomicReference <>(null );
5859 J .Block alteredBlock = b .withStatements (ListUtils .flatMap (b .getStatements (), statement -> {
5960 if (statement instanceof J .If ) {
6061 J .If ifStatement = (J .If ) statement ;
@@ -63,7 +64,7 @@ public J.Block visitBlock(J.Block block, ExecutionContext ctx) {
6364 Statement elsePart = ifStatement .getElsePart ().getBody ();
6465 if (elsePart instanceof J .Block ) {
6566 J .Block elseBlock = (J .Block ) elsePart ;
66- endComments . addAll (elseBlock .getEnd (). getComments ());
67+ endWhitespace . set (elseBlock .getEnd ());
6768 return ListUtils .concat (newIf , ListUtils .mapFirst (elseBlock .getStatements (), elseStmt -> {
6869 // Combine comments from the else block itself and the first statement
6970 List <Comment > elseComments = elseBlock .getPrefix ().getComments ();
@@ -81,9 +82,9 @@ public J.Block visitBlock(J.Block block, ExecutionContext ctx) {
8182 return statement ;
8283 }));
8384
84- if (! endComments . isEmpty () ) {
85- List <Comment > mergedComments = ListUtils .concatAll (endComments , b .getEnd ().getComments ());
86- alteredBlock = alteredBlock .withEnd (b .getEnd ().withComments (mergedComments ));
85+ if (endWhitespace . get () != null ) {
86+ List <Comment > mergedComments = ListUtils .concatAll (endWhitespace . get (). getComments () , b .getEnd ().getComments ());
87+ alteredBlock = alteredBlock .withEnd (b .getEnd ().withComments (mergedComments ). withWhitespace ( endWhitespace . get (). getWhitespace ()) );
8788 }
8889
8990 return maybeAutoFormat (b , alteredBlock , ctx );
0 commit comments