-
Notifications
You must be signed in to change notification settings - Fork 3
Superclass modifying recipes #3
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
Merged
timtebeek
merged 27 commits into
openrewrite:main
from
Fossur:superclass-modifying-recipes
Apr 28, 2025
Merged
Changes from 21 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
7bb9db8
Add WIP
Fossur 73e9efc
Add licences
Fossur a950992
Clean up recipe naming, Update inherited recipes to visitor style inh…
Fossur dd8f3ac
Add usages to yaml
Fossur d946fc0
Fix tests to not use full runtime classpath
Fossur c85975e
Fix examples and descriptions
Fossur 40eb375
Apply suggestions from code review
timtebeek 255b8c7
Apply formatter on tests
timtebeek a46e244
Apply formatter on tests
timtebeek b30d0ab
Restore package declarations
timtebeek eeb4d31
Fix extended visitors to inline
Fossur 0a790c1
Merge branch 'superclass-modifying-recipes' of https://github.com/Fos…
Fossur a46101e
Remove method stub creator
Fossur 4de524e
Update tests
Fossur 9e21ec8
Merge branch 'main' into superclass-modifying-recipes
timtebeek 6f2b944
Apply suggestions from code review
timtebeek 92ae561
Merge branch 'main' into superclass-modifying-recipes
timtebeek 08fb545
Polish `RemoveUnnecessarySuperCalls`
timtebeek b4fa74e
Polish `RemoveSuperTypeVisitor`
timtebeek 294e6ad
Place the documentation examples first
timtebeek b139441
Remove `RemoveSuperTypeByPackage` as it's likely to make unchecked ch…
timtebeek fb67197
No need to handle interfaces just yet
timtebeek 8f8e060
Trim down `RemoveUnnecessaryOverride`
timtebeek 9ae951b
Use `RemoveAnnotationVisitor` to not change formatting
timtebeek 128758b
Comment out `ee.taltech.example.AbstractJpaDAO` reference for now
timtebeek dac7cbf
Polish `ChangeSuperType`
timtebeek 86502ca
Update examples.yml
timtebeek File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
164 changes: 164 additions & 0 deletions
164
src/main/java/org/openrewrite/java/dropwizard/method/ChangeSuperType.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| /* | ||
| * Copyright 2025 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.dropwizard.method; | ||
|
|
||
|
|
||
| import lombok.EqualsAndHashCode; | ||
| import lombok.Value; | ||
| import org.openrewrite.ExecutionContext; | ||
| import org.openrewrite.Option; | ||
| 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.service.ImportService; | ||
| import org.openrewrite.java.tree.Expression; | ||
| import org.openrewrite.java.tree.J; | ||
| import org.openrewrite.java.tree.JavaType; | ||
| import org.openrewrite.java.tree.TypeTree; | ||
|
|
||
| import static java.lang.Boolean.TRUE; | ||
| import static org.openrewrite.java.tree.TypeUtils.asFullyQualified; | ||
| import static org.openrewrite.java.tree.TypeUtils.isOfClassType; | ||
|
|
||
| @Value | ||
| @EqualsAndHashCode(callSuper = false) | ||
| public class ChangeSuperType extends Recipe { | ||
|
|
||
| @Option(displayName = "Target class", | ||
| description = "The fully qualified name of the class whose superclass should be changed.", | ||
| example = "com.myorg.MyClass") | ||
| String targetClass; | ||
|
|
||
| @Option(displayName = "New superclass", | ||
| description = "The fully qualified name of the new superclass to extend or interface to implement.", | ||
| example = "com.myorg.NewSuperclass") | ||
| String newSuperclass; | ||
|
|
||
| @Option(displayName = "Keep type parameters", | ||
| description = "Whether to keep existing type parameters on the target class declaration.", | ||
| required = false) | ||
| Boolean keepTypeParameters; | ||
|
|
||
| @Option(displayName = "Convert to interface", | ||
| description = "If the new supertype is an interface, setting this to true converts 'extends' to 'implements'.", | ||
| required = false) | ||
| Boolean convertToInterface; | ||
|
|
||
| @Option(displayName = "Remove unnecessary overrides", | ||
| description = "Remove method Override annotations that override methods from the *old* superclass but are no longer necessary with the new superclass.", | ||
| required = false) | ||
| Boolean removeUnnecessaryOverrides; | ||
|
|
||
| @Override | ||
| public String getDisplayName() { | ||
| return "Change superclass"; | ||
| } | ||
|
|
||
| @Override | ||
| public String getDescription() { | ||
| return "Changes the superclass of a specified class to a new superclass."; | ||
| } | ||
|
|
||
| @Override | ||
| public TreeVisitor<?, ExecutionContext> getVisitor() { | ||
| return new JavaIsoVisitor<ExecutionContext>() { | ||
| @Override | ||
| public J.ClassDeclaration visitClassDeclaration( | ||
| J.ClassDeclaration classDecl, ExecutionContext ctx) { | ||
| J.ClassDeclaration cd = super.visitClassDeclaration(classDecl, ctx); | ||
|
|
||
| if (cd.getExtends() == null || !isOfClassType(cd.getExtends().getType(), targetClass)) { | ||
| return cd; | ||
| } | ||
|
|
||
| String typeParams = getTypeParams(cd.getExtends()); | ||
|
|
||
| maybeAddImport(newSuperclass); | ||
| maybeRemoveImport(targetClass); | ||
|
|
||
| JavaTemplate extendsTemplate = | ||
| JavaTemplate.builder("#{}" + typeParams) | ||
| .javaParser(JavaParser.fromJavaVersion().classpath(JavaParser.runtimeClasspath())) | ||
| .imports(newSuperclass) | ||
| .contextSensitive() | ||
| .build(); | ||
|
|
||
| JavaType.FullyQualified newSuperType; | ||
|
|
||
| if (TRUE.equals(convertToInterface)) { | ||
| cd = | ||
| extendsTemplate.apply( | ||
| updateCursor(cd), cd.getCoordinates().addImplementsClause(), newSuperclass); | ||
| cd = cd.withExtends(null); | ||
| TypeTree lastInterface = cd.getImplements().get(cd.getImplements().size() - 1); | ||
| newSuperType = asFullyQualified(lastInterface.getType()); | ||
| } else { | ||
| cd = | ||
| extendsTemplate.apply( | ||
| updateCursor(cd), cd.getCoordinates().replaceExtendsClause(), newSuperclass); | ||
| newSuperType = asFullyQualified(cd.getExtends().getType()); | ||
| } | ||
|
|
||
| // If changing to a class that was not compiled initially (eg. from a new library) | ||
| if (newSuperType == null) { | ||
| newSuperType = asFullyQualified(JavaType.buildType(newSuperclass)); | ||
| } | ||
|
|
||
| cd = cd.withType(((JavaType.Class) cd.getType()).withSupertype(newSuperType)); | ||
|
|
||
| doAfterVisit(new UpdateMethodTypesVisitor(cd.getType())); | ||
|
|
||
| if (TRUE.equals(removeUnnecessaryOverrides)) { | ||
| doAfterVisit(new RemoveUnnecessaryOverride.RemoveUnnecessaryOverrideVisitor()); | ||
| } | ||
|
|
||
| doAfterVisit(new RemoveUnnecessarySuperCalls.RemoveUnnecessarySuperCallsVisitor()); | ||
| doAfterVisit(service(ImportService.class).shortenFullyQualifiedTypeReferencesIn(cd)); | ||
|
|
||
| return cd; | ||
| } | ||
|
|
||
| private String getTypeParams(TypeTree extendsType) { | ||
| StringBuilder typeParams = new StringBuilder(); | ||
|
|
||
| if (TRUE.equals(keepTypeParameters) && extendsType instanceof J.ParameterizedType) { | ||
| J.ParameterizedType parameterizedType = (J.ParameterizedType) extendsType; | ||
|
|
||
| boolean hasParameters = false; | ||
| typeParams.append('<'); | ||
|
|
||
| for (Expression typeParameter : parameterizedType.getTypeParameters()) { | ||
| if (hasParameters) { | ||
| typeParams.append(", "); | ||
| } | ||
| typeParams.append(typeParameter.toString()); | ||
| hasParameters = true; | ||
| } | ||
|
|
||
| if (hasParameters) { | ||
| typeParams.append('>'); | ||
| } else { | ||
| typeParams.setLength(0); | ||
| } | ||
| } | ||
|
|
||
| return typeParams.toString(); | ||
| } | ||
| }; | ||
| } | ||
| } |
79 changes: 79 additions & 0 deletions
79
src/main/java/org/openrewrite/java/dropwizard/method/RemoveSuperTypeByType.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| /* | ||
| * Copyright 2025 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.dropwizard.method; | ||
|
|
||
| import lombok.EqualsAndHashCode; | ||
| import lombok.Value; | ||
| import org.jspecify.annotations.Nullable; | ||
| import org.openrewrite.*; | ||
| import org.openrewrite.internal.ListUtils; | ||
| import org.openrewrite.java.JavaIsoVisitor; | ||
| import org.openrewrite.java.search.UsesType; | ||
| import org.openrewrite.java.tree.J; | ||
| import org.openrewrite.java.tree.JavaType; | ||
|
|
||
| import static org.openrewrite.java.tree.TypeUtils.isOfClassType; | ||
|
|
||
| @Value | ||
| @EqualsAndHashCode(callSuper = false) | ||
| public class RemoveSuperTypeByType extends Recipe { | ||
|
|
||
| @Option(displayName = "Fully qualified name of the superclass to remove", | ||
timtebeek marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| description = "Supertypes that match this name are to be removed", | ||
| example = "io.dropwizard.Configuration") | ||
| String typeToRemove; | ||
|
|
||
| @Override | ||
| public String getDisplayName() { | ||
| return "Remove supertype by fully qualified name matches"; | ||
| } | ||
|
|
||
| @Override | ||
| public String getDescription() { | ||
| return "Removes a specified type from class extends or implements clauses."; | ||
| } | ||
|
|
||
| @Override | ||
| public TreeVisitor<?, ExecutionContext> getVisitor() { | ||
| return Preconditions.check( | ||
| new UsesType<>(typeToRemove, false), | ||
| new JavaIsoVisitor<ExecutionContext>() { | ||
| @Override | ||
| public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) { | ||
| J.ClassDeclaration cd = super.visitClassDeclaration(classDecl, ctx); | ||
|
|
||
| if (cd.getExtends() != null && shouldRemoveType(cd.getExtends().getType())) { | ||
| cd = cd.withExtends(null); | ||
| } | ||
| if (cd.getImplements() != null) { | ||
| cd = cd.withImplements(ListUtils.filter(cd.getImplements(), impl -> !shouldRemoveType(impl.getType()))); | ||
| } | ||
| if (cd != classDecl) { | ||
| JavaType.ShallowClass type = (JavaType.ShallowClass) JavaType.buildType("java.lang.Object"); | ||
| doAfterVisit(new UpdateMethodTypesVisitor(type)); | ||
| doAfterVisit(new RemoveUnnecessarySuperCalls.RemoveUnnecessarySuperCallsVisitor()); | ||
| } | ||
|
|
||
| return cd; | ||
| } | ||
|
|
||
| private boolean shouldRemoveType(@Nullable JavaType type) { | ||
| return isOfClassType(type, typeToRemove); | ||
| } | ||
| } | ||
| ); | ||
| } | ||
| } | ||
97 changes: 97 additions & 0 deletions
97
src/main/java/org/openrewrite/java/dropwizard/method/RemoveUnnecessaryOverride.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| /* | ||
| * Copyright 2025 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.dropwizard.method; | ||
|
|
||
| import lombok.EqualsAndHashCode; | ||
| import lombok.Value; | ||
timtebeek marked this conversation as resolved.
Show resolved
Hide resolved
timtebeek marked this conversation as resolved.
Show resolved
Hide resolved
timtebeek marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| import org.jspecify.annotations.Nullable; | ||
| import org.openrewrite.*; | ||
| import org.openrewrite.java.AnnotationMatcher; | ||
| import org.openrewrite.java.JavaIsoVisitor; | ||
| import org.openrewrite.java.service.AnnotationService; | ||
| import org.openrewrite.java.tree.J; | ||
| import org.openrewrite.java.tree.TypeUtils; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
|
|
||
| @Value | ||
| @EqualsAndHashCode(callSuper = false) | ||
| public class RemoveUnnecessaryOverride extends Recipe { | ||
timtebeek marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| @Option( | ||
| displayName = "Ignore methods in anonymous classes", | ||
| description = "When enabled, ignore @Override annotations on methods in anonymous classes.", | ||
| required = false) | ||
| @Nullable | ||
| Boolean ignoreAnonymousClassMethods; | ||
|
|
||
| @Override | ||
| public String getDisplayName() { | ||
| return "Remove unnecessary `@Override` annotations"; | ||
| } | ||
|
|
||
| @Override | ||
| public String getDescription() { | ||
| return "Removes `@Override` annotations from methods that don't actually override or implement any method. " + | ||
| "This helps maintain clean code by removing incorrect annotations that could be misleading."; | ||
| } | ||
|
|
||
| @Override | ||
| public TreeVisitor<?, ExecutionContext> getVisitor() { | ||
| return new RemoveUnnecessaryOverrideVisitor(ignoreAnonymousClassMethods); | ||
| } | ||
|
|
||
| public static class RemoveUnnecessaryOverrideVisitor extends JavaIsoVisitor<ExecutionContext> { | ||
| private final AnnotationMatcher OVERRIDE_ANNOTATION = | ||
| new AnnotationMatcher("@java.lang.Override"); | ||
| private final Boolean ignoreAnonymousClassMethods; | ||
|
|
||
| public RemoveUnnecessaryOverrideVisitor(Boolean ignoreAnonymousClassMethods) { | ||
| this.ignoreAnonymousClassMethods = ignoreAnonymousClassMethods; | ||
| } | ||
|
|
||
| public RemoveUnnecessaryOverrideVisitor() { | ||
| this(false); | ||
| } | ||
|
|
||
| private Cursor getCursorToParentScope(Cursor cursor) { | ||
| return cursor.dropParentUntil( | ||
| is -> is instanceof J.NewClass || is instanceof J.ClassDeclaration); | ||
| } | ||
|
|
||
| @Override | ||
| public J.MethodDeclaration visitMethodDeclaration( | ||
| J.MethodDeclaration method, ExecutionContext ctx) { | ||
| J.MethodDeclaration m = super.visitMethodDeclaration(method, ctx); | ||
|
|
||
| if (!m.isConstructor() && | ||
| service(AnnotationService.class).matches(getCursor(), OVERRIDE_ANNOTATION) && | ||
| !TypeUtils.isOverride(m.getMethodType()) && | ||
| !(Boolean.TRUE.equals(ignoreAnonymousClassMethods) && | ||
| getCursorToParentScope(getCursor()).getValue() instanceof J.NewClass)) { | ||
|
|
||
| // Find and remove the @Override annotation | ||
| List<J.Annotation> annotations = new ArrayList<>(m.getLeadingAnnotations()); | ||
| annotations.removeIf(OVERRIDE_ANNOTATION::matches); | ||
|
|
||
| return maybeAutoFormat(method, m.withLeadingAnnotations(annotations), ctx); | ||
| } | ||
|
|
||
| return m; | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.