-
Notifications
You must be signed in to change notification settings - Fork 90
Add FluentSetterRecipe #646
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
Open
e5LA
wants to merge
9
commits into
openrewrite:main
Choose a base branch
from
e5LA:fluent-setter-recipe
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+945
−0
Open
Changes from 2 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
2d3d034
feat: add FluentSetterRecipe
e5LA 1bd3684
Merge branch 'main' into fluent-setter-recipe
e5LA d8673d1
refactor: fix formatting
e5LA e3d9951
Merge branch 'fluent-setter-recipe' of github.com:e5LA/rewrite-static…
e5LA d7375e4
Merge branch 'main' into fluent-setter-recipe
timtebeek 363366c
refactor: renaming class, removing Recipe suffix
e5LA 7a31b53
Merge branch 'main' into fluent-setter-recipe
timtebeek 829139a
Apply final class safety check when no method pattern specified
e5LA ace4dc9
Merge branch 'main' into fluent-setter-recipe
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
224 changes: 224 additions & 0 deletions
224
src/main/java/org/openrewrite/staticanalysis/FluentSetterRecipe.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,224 @@ | ||
| /* | ||
| * Copyright 2025 the original author or authors. | ||
| * <p> | ||
| * Licensed under the Moderne Source Available License (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://docs.moderne.io/licensing/moderne-source-available-license | ||
| * <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.staticanalysis; | ||
|
|
||
| import lombok.EqualsAndHashCode; | ||
| import lombok.Value; | ||
| import org.jspecify.annotations.Nullable; | ||
| import org.openrewrite.ExecutionContext; | ||
| import org.openrewrite.Option; | ||
| import org.openrewrite.Recipe; | ||
| import org.openrewrite.internal.ListUtils; | ||
| import org.openrewrite.java.JavaIsoVisitor; | ||
| import org.openrewrite.java.tree.J; | ||
| import org.openrewrite.java.tree.JavaType; | ||
| import org.openrewrite.java.tree.Space; | ||
| import org.openrewrite.java.tree.Statement; | ||
| import org.openrewrite.marker.Markers; | ||
|
|
||
| import java.util.List; | ||
| import java.util.concurrent.atomic.AtomicBoolean; | ||
| import java.util.regex.Pattern; | ||
|
|
||
| import static java.util.Collections.emptyList; | ||
| import static org.openrewrite.Tree.randomId; | ||
|
|
||
| @EqualsAndHashCode(callSuper = false) | ||
| @Value | ||
| public class FluentSetterRecipe extends Recipe { | ||
|
|
||
| @Option(displayName = "Include all void methods", description = | ||
| "Whether to convert all void methods to return `this`, not just setters. " | ||
| + "When false, only methods matching setter patterns will be converted.", required = false) | ||
| @Nullable | ||
| Boolean includeAllVoidMethods; | ||
|
|
||
| @Option(displayName = "Method name pattern", description = | ||
| "A regular expression pattern to match method names. " | ||
| + "Only methods matching this pattern will be converted. " | ||
| + "Defaults to setter pattern when includeAllVoidMethods is false.", example = "set.*", required = false) | ||
| @Nullable | ||
| String methodNamePattern; | ||
|
|
||
| @Option(displayName = "Exclude method patterns", description = | ||
| "A regular expression pattern for method names to exclude from conversion. " | ||
| + "Methods matching this pattern will not be converted.", example = "main|run", required = false) | ||
| @Nullable | ||
| String excludeMethodPattern; | ||
|
|
||
| @Override | ||
| public String getDisplayName() { | ||
| return "Convert setters to return `this` for fluent interfaces"; | ||
| } | ||
|
|
||
| @Override | ||
| public String getDescription() { | ||
| return "Converts void setter methods (and optionally other void methods) to return `this` " | ||
| + "to enable method chaining and fluent interfaces."; | ||
e5LA marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| @Override | ||
| public JavaIsoVisitor<ExecutionContext> getVisitor() { | ||
| return new JavaIsoVisitor<ExecutionContext>() { | ||
|
|
||
| @Override | ||
| public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, | ||
| ExecutionContext ctx) { | ||
| method = super.visitMethodDeclaration(method, ctx); | ||
| if (!shouldConvertMethod(method)) { | ||
| return method; | ||
| } | ||
|
|
||
| J.ClassDeclaration containingClass = getCursor().firstEnclosing(J.ClassDeclaration.class); | ||
| if (containingClass == null || containingClass.getType() == null) { | ||
| return method; | ||
| } | ||
|
|
||
| JavaType.FullyQualified classType = containingClass.getType(); | ||
| String className = classType.getClassName(); | ||
| if (className.contains(".")) { | ||
| className = className.substring(className.lastIndexOf('.') + 1); | ||
| } | ||
|
|
||
| Space returnTypeSpace = method.getReturnTypeExpression() == null ? Space.EMPTY | ||
| : method.getReturnTypeExpression().getPrefix(); | ||
| Markers returnTypeMarkers = method.getReturnTypeExpression() == null ? Markers.EMPTY | ||
| : method.getReturnTypeExpression().getMarkers(); | ||
e5LA marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| J.Identifier returnTypeIdentifier = new J.Identifier( | ||
| randomId(), | ||
| returnTypeSpace, | ||
| returnTypeMarkers, | ||
| emptyList(), | ||
| className, | ||
| classType, | ||
| null | ||
| ); | ||
|
|
||
| J.MethodDeclaration updatedMethod = method | ||
| .withReturnTypeExpression(returnTypeIdentifier); | ||
|
|
||
| if (updatedMethod.getBody() != null) { | ||
| Space indentation; | ||
| List<Statement> statements = updatedMethod.getBody().getStatements(); | ||
| if (!statements.isEmpty()) { | ||
| indentation = statements.get(statements.size() - 1).getPrefix(); | ||
| } else { | ||
| indentation = updatedMethod.getBody().getPrefix(); | ||
| } | ||
|
|
||
| J.Return returnThis = new J.Return( | ||
| randomId(), | ||
| Space.format("\n" + indentation.getIndent()), | ||
| Markers.EMPTY, | ||
| new J.Identifier( | ||
| randomId(), | ||
| Space.SINGLE_SPACE, | ||
| Markers.EMPTY, | ||
| emptyList(), | ||
| "this", | ||
| classType, | ||
| null | ||
| ) | ||
| ); | ||
|
|
||
| updatedMethod = updatedMethod.withBody( | ||
| updatedMethod.getBody().withStatements( | ||
| ListUtils.concat(updatedMethod.getBody().getStatements(), returnThis) | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| return updatedMethod; | ||
| } | ||
|
|
||
|
|
||
| private boolean shouldConvertMethod(J.MethodDeclaration method) { | ||
| if (method.getReturnTypeExpression() == null | ||
| || method.getReturnTypeExpression().getType() != JavaType.Primitive.Void) { | ||
e5LA marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| return false; | ||
| } | ||
|
|
||
| if (method.hasModifier(J.Modifier.Type.Static)) { | ||
| return false; | ||
| } | ||
|
|
||
| if (method.hasModifier(J.Modifier.Type.Abstract) || method.getBody() == null) { | ||
| return false; | ||
| } | ||
|
|
||
| if (method.isConstructor()) { | ||
| return false; | ||
| } | ||
|
|
||
| if (method.getBody() != null && hasReturnStatement(method.getBody())) { | ||
| return false; | ||
| } | ||
|
|
||
| String methodName = method.getSimpleName(); | ||
|
|
||
| if (excludeMethodPattern != null && !excludeMethodPattern.trim().isEmpty()) { | ||
| Pattern excludePattern = Pattern.compile(excludeMethodPattern); | ||
| if (excludePattern.matcher(methodName).matches()) { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| if (methodNamePattern != null && !methodNamePattern.trim().isEmpty()) { | ||
| Pattern namePattern = Pattern.compile(methodNamePattern); | ||
| return namePattern.matcher(methodName).matches(); | ||
| } | ||
|
|
||
| if (includeAllVoidMethods != null && includeAllVoidMethods) { | ||
| return true; | ||
| } | ||
|
|
||
| // Default behavior: only setter methods | ||
| return isSetterMethod(method); | ||
| } | ||
|
|
||
| private boolean isSetterMethod(J.MethodDeclaration method) { | ||
| String methodName = method.getSimpleName(); | ||
| if (!methodName.startsWith("set") || methodName.length() <= 3) { | ||
| return false; | ||
| } | ||
|
|
||
| // Must have exactly one parameter | ||
| if (method.getParameters().size() != 1) { | ||
| return false; | ||
| } | ||
|
|
||
| // The character after "set" should be uppercase (setName, not setup) | ||
| char charAfterSet = methodName.charAt(3); | ||
| return Character.isUpperCase(charAfterSet); | ||
| } | ||
|
|
||
| private boolean hasReturnStatement(J.Block body) { | ||
| AtomicBoolean hasReturn = new AtomicBoolean(false); | ||
|
|
||
| new JavaIsoVisitor<AtomicBoolean>() { | ||
| @Override | ||
| public J.Return visitReturn(J.Return returnStmt, AtomicBoolean found) { | ||
| found.set(true); | ||
| return returnStmt; | ||
| } | ||
| }.visit(body, hasReturn); | ||
|
|
||
| return hasReturn.get(); | ||
| } | ||
| }; | ||
| } | ||
| } | ||
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.