Skip to content

Commit

Permalink
Replace PartProvider with JavaTemplate
Browse files Browse the repository at this point in the history
  • Loading branch information
timtebeek committed Dec 9, 2023
1 parent 76fe8e9 commit e383281
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaParser;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.PartProvider;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.J;

Expand All @@ -32,8 +33,6 @@
*/
public class AnyStringToNullable extends Recipe {
private static final MethodMatcher ANY_STRING = new MethodMatcher("org.mockito.Mockito anyString()");
private static final String MOCKITO_CLASS_PATH = "mockito-core-3.12";
private static J.MethodInvocation nullableStringMethodTemplate = null;

@Override
public String getDisplayName() {
Expand All @@ -53,31 +52,20 @@ public Duration getEstimatedEffortPerOccurrence() {
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new UsesMethod<>(ANY_STRING), new JavaIsoVisitor<ExecutionContext>() {

@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation mi = super.visitMethodInvocation(method, ctx);

if (ANY_STRING.matches(mi)) {
maybeAddImport("org.mockito.ArgumentMatchers", "nullable", false);
maybeRemoveImport("org.mockito.Mockito.anyString");
return getNullableMethodTemplate().withPrefix(mi.getPrefix());
return JavaTemplate.builder("nullable(String.class)")
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "mockito-core-3.12"))
.staticImports("org.mockito.ArgumentMatchers.nullable")
.build()
.apply(getCursor(), mi.getCoordinates().replace());
}
return mi;
}
});
}

private static J.MethodInvocation getNullableMethodTemplate() {
if (nullableStringMethodTemplate == null) {
nullableStringMethodTemplate = PartProvider.buildPart("import static org.mockito.ArgumentMatchers" +
".nullable;\n" +
"public class A {\n" +
" void method() {\n" +
" Object x = nullable(String.class);\n" +
" }\n" +
"}", J.MethodInvocation.class, MOCKITO_CLASS_PATH);
}
return nullableStringMethodTemplate;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import static org.openrewrite.java.Assertions.java;

class AnyStringToNullableTest implements RewriteTest {

@Override
public void defaults(RecipeSpec spec) {
spec
Expand Down

0 comments on commit e383281

Please sign in to comment.