1919import org .openrewrite .Preconditions ;
2020import org .openrewrite .Recipe ;
2121import org .openrewrite .TreeVisitor ;
22+ import org .openrewrite .internal .ListUtils ;
2223import org .openrewrite .internal .lang .Nullable ;
2324import org .openrewrite .java .ChangeMethodTargetToStatic ;
2425import org .openrewrite .java .JavaIsoVisitor ;
2930import java .util .Arrays ;
3031import java .util .List ;
3132
33+ import static java .util .Collections .emptyList ;
34+
3235public class AssertToAssertions extends Recipe {
3336
3437 @ Override
@@ -82,8 +85,8 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
8285 "org.junit.jupiter.api.Assertions" , null , null , true )
8386 .getVisitor ());
8487
85- List <Expression > args = m .getArguments ();
86- Expression firstArg = args .get (0 );
88+ List <JRightPadded < Expression >> args = m .getPadding (). getArguments (). getPadding (). getElements ();
89+ Expression firstArg = args .get (0 ). getElement () ;
8790 // Suppress arg-switching for Assertions.assertEquals(String, String)
8891 if (args .size () == 2 ) {
8992 if ("assertSame" .equals (m .getSimpleName ()) ||
@@ -97,17 +100,29 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
97100 if (TypeUtils .isString (firstArg .getType ())) {
98101 // Move the first arg to be the last argument
99102
100- List <Expression > newArgs = new ArrayList <>(args .size ());
101- for (int i = 1 ; i < args .size (); i ++) {
102- if (i == 1 ) {
103- newArgs .add (args .get (i ).withPrefix (firstArg .getPrefix ()));
104- } else {
105- newArgs .add (args .get (i ));
106- }
107- }
108- newArgs .add (firstArg .withPrefix (args .get (args .size () - 1 ).getPrefix ()));
109-
110- m = m .withArguments (newArgs );
103+ List <JRightPadded <Expression >> newArgs = new ArrayList <>(args );
104+ JRightPadded <Expression > first = newArgs .remove (0 );
105+ JRightPadded <Expression > lastArg = args .get (args .size () - 1 );
106+ boolean lastArgComments = !lastArg .getAfter ().getComments ().isEmpty ();
107+
108+ newArgs = ListUtils .mapFirst (newArgs , e -> e .withElement (e .getElement ().withPrefix (first .getElement ().getPrefix ())));
109+ newArgs = ListUtils .mapLast (newArgs , e -> e .withAfter (Space .EMPTY ));
110+ newArgs .add (first
111+ .withElement (first .getElement ()
112+ .withPrefix (lastArgComments ?
113+ lastArg .getAfter ().withComments (ListUtils .mapLast (
114+ lastArg .getAfter ().getComments (),
115+ c -> c .withSuffix (lastArg .getElement ().getPrefix ().getWhitespace ()))
116+ ) :
117+ lastArg .getElement ().getPrefix ()
118+ )
119+ )
120+ .withAfter (lastArgComments ? Space .build (lastArg .getAfter ().getLastWhitespace (), emptyList ()) : lastArg .getAfter ())
121+ );
122+
123+ m = m .getPadding ().withArguments (
124+ m .getPadding ().getArguments ().getPadding ().withElements (newArgs )
125+ );
111126 }
112127
113128 return m ;
0 commit comments