diff --git a/src/main/java/org/openrewrite/java/migrate/lombok/LombokUtils.java b/src/main/java/org/openrewrite/java/migrate/lombok/LombokUtils.java new file mode 100644 index 000000000..20c1ae081 --- /dev/null +++ b/src/main/java/org/openrewrite/java/migrate/lombok/LombokUtils.java @@ -0,0 +1,97 @@ +/* + * Copyright 2024 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openrewrite.java.migrate.lombok; + +import lombok.AccessLevel; +import org.jspecify.annotations.Nullable; +import org.openrewrite.internal.StringUtils; +import org.openrewrite.java.tree.Expression; +import org.openrewrite.java.tree.J; +import org.openrewrite.java.tree.JavaType; + +import static lombok.AccessLevel.*; +import static org.openrewrite.java.tree.J.Modifier.Type.*; + +class LombokUtils { + + static boolean isGetter(J.MethodDeclaration method) { + if (method.getMethodType() == null) { + return false; + } + // Check signature: no parameters + if (!(method.getParameters().get(0) instanceof J.Empty) || method.getReturnTypeExpression() == null) { + return false; + } + // Check body: just a return statement + if (method.getBody() == null || + method.getBody().getStatements().size() != 1 || + !(method.getBody().getStatements().get(0) instanceof J.Return)) { + return false; + } + // Check field is declared on method type + JavaType.FullyQualified declaringType = method.getMethodType().getDeclaringType(); + Expression returnExpression = ((J.Return) method.getBody().getStatements().get(0)).getExpression(); + if (returnExpression instanceof J.Identifier) { + J.Identifier identifier = (J.Identifier) returnExpression; + if (identifier.getFieldType() != null && declaringType == identifier.getFieldType().getOwner()) { + // Check return: type and matching field name + return hasMatchingTypeAndName(method, identifier.getType(), identifier.getSimpleName()); + } + } else if (returnExpression instanceof J.FieldAccess) { + J.FieldAccess fieldAccess = (J.FieldAccess) returnExpression; + Expression target = fieldAccess.getTarget(); + if (target instanceof J.Identifier && ((J.Identifier) target).getFieldType() != null && + declaringType == ((J.Identifier) target).getFieldType().getOwner()) { + // Check return: type and matching field name + return hasMatchingTypeAndName(method, fieldAccess.getType(), fieldAccess.getSimpleName()); + } + } + return false; + } + + private static boolean hasMatchingTypeAndName(J.MethodDeclaration method, @Nullable JavaType type, String simpleName) { + if (method.getType() == type) { + String deriveGetterMethodName = deriveGetterMethodName(type, simpleName); + return method.getSimpleName().equals(deriveGetterMethodName); + } + return false; + } + + private static String deriveGetterMethodName(@Nullable JavaType type, String fieldName) { + if (type == JavaType.Primitive.Boolean) { + boolean alreadyStartsWithIs = fieldName.length() >= 3 && + fieldName.substring(0, 3).matches("is[A-Z]"); + if (alreadyStartsWithIs) { + return fieldName; + } else { + return "is" + StringUtils.capitalize(fieldName); + } + } + return "get" + StringUtils.capitalize(fieldName); + } + + static AccessLevel getAccessLevel(J.MethodDeclaration modifiers) { + if (modifiers.hasModifier(Public)) { + return PUBLIC; + } else if (modifiers.hasModifier(Protected)) { + return PROTECTED; + } else if (modifiers.hasModifier(Private)) { + return PRIVATE; + } + return PACKAGE; + } + +} diff --git a/src/main/java/org/openrewrite/java/migrate/lombok/UseLombokGetter.java b/src/main/java/org/openrewrite/java/migrate/lombok/UseLombokGetter.java new file mode 100644 index 000000000..b8de2d23f --- /dev/null +++ b/src/main/java/org/openrewrite/java/migrate/lombok/UseLombokGetter.java @@ -0,0 +1,109 @@ +/* + * Copyright 2024 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openrewrite.java.migrate.lombok; + +import lombok.AccessLevel; +import lombok.EqualsAndHashCode; +import lombok.Value; +import org.jspecify.annotations.Nullable; +import org.openrewrite.ExecutionContext; +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.tree.Expression; +import org.openrewrite.java.tree.J; +import org.openrewrite.java.tree.JavaType; + +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import static java.util.Comparator.comparing; +import static lombok.AccessLevel.PUBLIC; + +@Value +@EqualsAndHashCode(callSuper = false) +public class UseLombokGetter extends Recipe { + + @Override + public String getDisplayName() { + return "Convert getter methods to annotations"; + } + + @Override + public String getDescription() { + //language=markdown + return "Convert trivial getter methods to `@Getter` annotations on their respective fields."; + } + + @Override + public Set getTags() { + return Collections.singleton("lombok"); + } + + @Override + public TreeVisitor getVisitor() { + return new JavaIsoVisitor() { + @Override + public J.@Nullable MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, ExecutionContext ctx) { + if (LombokUtils.isGetter(method)) { + Expression returnExpression = ((J.Return) method.getBody().getStatements().get(0)).getExpression(); + if (returnExpression instanceof J.Identifier && + ((J.Identifier) returnExpression).getFieldType() != null) { + doAfterVisit(new FieldAnnotator( + ((J.Identifier) returnExpression).getFieldType(), + LombokUtils.getAccessLevel(method))); + return null; + } else if (returnExpression instanceof J.FieldAccess && + ((J.FieldAccess) returnExpression).getName().getFieldType() != null) { + doAfterVisit(new FieldAnnotator( + ((J.FieldAccess) returnExpression).getName().getFieldType(), + LombokUtils.getAccessLevel(method))); + return null; + } + } + return method; + } + }; + } + + + @Value + @EqualsAndHashCode(callSuper = false) + static class FieldAnnotator extends JavaIsoVisitor { + + JavaType field; + AccessLevel accessLevel; + + @Override + public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext ctx) { + for (J.VariableDeclarations.NamedVariable variable : multiVariable.getVariables()) { + if (variable.getName().getFieldType() == field) { + maybeAddImport("lombok.Getter"); + maybeAddImport("lombok.AccessLevel"); + String suffix = accessLevel == PUBLIC ? "" : String.format("(AccessLevel.%s)", accessLevel.name()); + return JavaTemplate.builder("@Getter" + suffix) + .imports("lombok.Getter", "lombok.AccessLevel") + .javaParser(JavaParser.fromJavaVersion().classpath("lombok")) + .build().apply(getCursor(), multiVariable.getCoordinates().addAnnotation(comparing(J.Annotation::getSimpleName))); + } + } + return multiVariable; + } + } +} diff --git a/src/test/java/org/openrewrite/java/migrate/lombok/UseLombokGetterTest.java b/src/test/java/org/openrewrite/java/migrate/lombok/UseLombokGetterTest.java new file mode 100644 index 000000000..ec62019a5 --- /dev/null +++ b/src/test/java/org/openrewrite/java/migrate/lombok/UseLombokGetterTest.java @@ -0,0 +1,531 @@ +/* + * Copyright 2024 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openrewrite.java.migrate.lombok; + +import org.junit.jupiter.api.Test; +import org.openrewrite.DocumentExample; +import org.openrewrite.test.RecipeSpec; +import org.openrewrite.test.RewriteTest; + +import static org.openrewrite.java.Assertions.java; + +class UseLombokGetterTest implements RewriteTest { + + @Override + public void defaults(RecipeSpec spec) { + spec.recipe(new UseLombokGetter()); + } + + @DocumentExample + @Test + void replaceGetter() { + rewriteRun(// language=java + java( + """ + class A { + + int foo = 9; + + public int getFoo() { + return foo; + } + } + """, + """ + import lombok.Getter; + + class A { + + @Getter + int foo = 9; + } + """ + ) + ); + } + + @Test + void replaceGetterWithFieldAccess() { + rewriteRun(// language=java + java( + """ + class A { + + int foo = 9; + + public int getFoo() { + return this.foo; + } + } + """, + """ + import lombok.Getter; + + class A { + + @Getter + int foo = 9; + } + """ + ) + ); + } + + @Test + void replaceGetterWithMultiVariable() { + // Technically this adds a new public getter not there previously, but we'll tolerate it + rewriteRun(// language=java + java( + """ + class A { + + int foo = 9, bar = 10; + + public int getFoo() { + return foo; + } + } + """, + """ + import lombok.Getter; + + class A { + + @Getter + int foo = 9, bar = 10; + } + """ + ) + ); + } + + @Test + void replacePackageGetter() { + rewriteRun(// language=java + java( + """ + class A { + + int foo = 9; + + int getFoo() { + return foo; + } + } + """, + """ + import lombok.AccessLevel; + import lombok.Getter; + + class A { + + @Getter(AccessLevel.PACKAGE) + int foo = 9; + } + """ + ) + ); + } + + @Test + void replaceProtectedGetter() { + rewriteRun(// language=java + java( + """ + class A { + + int foo = 9; + + protected int getFoo() { + return foo; + } + } + """, + """ + import lombok.AccessLevel; + import lombok.Getter; + + class A { + + @Getter(AccessLevel.PROTECTED) + int foo = 9; + } + """ + ) + ); + } + + @Test + void replacePrivateGetter() { + rewriteRun(// language=java + java( + """ + class A { + + int foo = 9; + + private int getFoo() { + return foo; + } + } + """, + """ + import lombok.AccessLevel; + import lombok.Getter; + + class A { + + @Getter(AccessLevel.PRIVATE) + int foo = 9; + } + """ + ) + ); + } + + @Test + void replaceJustTheMatchingGetter() { + rewriteRun(// language=java + java( + """ + class A { + + int foo = 9; + + int ba; + + public A() { + ba = 1; + } + + public int getFoo() { + return foo; + } + + public int getMoo() {//method name wrong + return ba; + } + } + """, + """ + import lombok.Getter; + + class A { + + @Getter + int foo = 9; + + int ba; + + public A() { + ba = 1; + } + + public int getMoo() {//method name wrong + return ba; + } + } + """ + ) + ); + } + + @Test + void noChangeWhenMethodNameDoesntMatch() { + rewriteRun(// language=java + java( + """ + class A { + + int foo = 9; + + public A() { + } + + int getfoo() {//method name wrong + return foo; + } + } + """ + ) + ); + } + + @Test + void noChangeWhenReturnTypeDoesntMatch() { + rewriteRun(// language=java + java( + """ + class A { + + int foo = 9; + + public A() { + } + + long getFoo() { //return type wrong + return foo; + } + } + """ + ) + ); + } + + @Test + void noChangeWhenFieldIsNotReturned() { + rewriteRun(// language=java + java( + """ + class A { + + int foo = 9; + int ba = 10; + + public A() { + } + + int getFoo() { + return 5;//does not return variable + } + } + """ + ) + ); + } + + @Test + void noChangeWhenDifferentFieldIsReturned() { + rewriteRun(// language=java + java( + """ + class A { + + int foo = 9; + int ba = 10; + + public A() { + } + + int getFoo() { + return ba;//returns wrong variable + } + } + """ + ) + ); + } + + @Test + void noChangeWhenSideEffects1() { + rewriteRun(// language=java + java( + """ + class A { + + int foo = 9; + int ba = 10; + + public A() { + } + + int getfoo() { + foo++;//does extra stuff + return foo; + } + } + """ + ) + ); + } + + @Test + void noChangeWhenSideEffects2() { + rewriteRun(// language=java + java( + """ + class A { + + int foo = 9; + int ba = 10; + + public A() { + } + + int getFoo() { + ba++;//does unrelated extra stuff + return foo; + } + } + """ + ) + ); + } + + @Test + void replacePrimitiveBoolean() { + rewriteRun(// language=java + java( + """ + class A { + + boolean foo = true; + + public boolean isFoo() { + return foo; + } + } + """, + """ + import lombok.Getter; + + class A { + + @Getter + boolean foo = true; + } + """ + ) + ); + } + + @Test + void replacePrimitiveBooleanStartingWithIs() { + rewriteRun(// language=java + java( + """ + class A { + + boolean isFoo = true; + + public boolean isFoo() { + return isFoo; + } + } + """, + """ + import lombok.Getter; + + class A { + + @Getter + boolean isFoo = true; + } + """ + ) + ); + } + + @Test + void noChangeWhenPrimitiveBooleanUsesGet() { + rewriteRun(// language=java + java( + """ + class A { + + boolean foo = true; + + boolean getFoo() { + return foo; + } + } + """ + ) + ); + } + + @Test + void replaceBoolean() { + rewriteRun(// language=java + java( + """ + class A { + + Boolean foo = true; + + public Boolean getFoo() { + return foo; + } + } + """, + """ + import lombok.Getter; + + class A { + + @Getter + Boolean foo = true; + } + """ + ) + ); + } + + @Test + void noChangeWhenBooleanUsesIs() { + rewriteRun(// language=java + java( + """ + class A { + + Boolean foo = true; + + Boolean isFoo() { + return foo; + } + } + """ + ) + ); + } + + @Test + void noChangeWhenBooleanUsesIs2() { + rewriteRun(// language=java + java( + """ + class A { + + Boolean isfoo = true; + + Boolean isFoo() { + return isfoo; + } + } + """ + ) + ); + } + + @Test + void noChangeNestedClassGetter() { + rewriteRun(// language=java + java( + """ + class Outer { + int foo = 9; + + class Inner { + public int getFoo() { + return foo; + } + } + } + """ + ) + ); + } +}