Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recipe to convert explicit getters to the Lombok annotation #623

Merged
merged 20 commits into from
Dec 13, 2024
Merged
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
97 changes: 97 additions & 0 deletions src/main/java/org/openrewrite/java/migrate/lombok/LombokUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
* Copyright 2024 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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;
timo-a marked this conversation as resolved.
Show resolved Hide resolved

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;
}

}
109 changes: 109 additions & 0 deletions src/main/java/org/openrewrite/java/migrate/lombok/UseLombokGetter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* Copyright 2024 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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<String> getTags() {
return Collections.singleton("lombok");
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new JavaIsoVisitor<ExecutionContext>() {
@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<ExecutionContext> {

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;
}
}
}
Loading