Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
@Value
public class InlineMethodCalls extends Recipe {
private static final Pattern TEMPLATE_IDENTIFIER = Pattern.compile("#\\{(\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*):any\\(.*?\\)}");
private static final Pattern BARE_METHOD_CALL = Pattern.compile("^\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*\\(");

@Option(displayName = "Method pattern",
description = "A method pattern that is used to find matching method invocations.",
Expand Down Expand Up @@ -199,6 +200,11 @@ private String createTemplateString(MethodCall original, JavaType.Method methodT
((J.MethodInvocation) original).getSelect() == null &&
replacement.startsWith("this.")) {
templateString = replacement.substring(5);
} else if (original instanceof J.MethodInvocation &&
((J.MethodInvocation) original).getSelect() != null &&
BARE_METHOD_CALL.matcher(replacement).find()) {
// Original had a select but replacement is a bare method call; preserve the select
templateString = "#{this:any()}." + replacement;
} else {
templateString = replacement.replaceAll("\\bthis\\b", "#{this:any()}");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,53 @@ void foo(Builder builder) {
);
}

@Test
void preserveSelectWhenReplacementIsBareMethodCall() {
//language=java
rewriteRun(
spec -> spec.recipe(new InlineMethodCalls(
"Lib getTotalHits()",
"getTotalHitsCount()",
null,
null,
null)),
java(
"""
class Lib {
@Deprecated
public int getTotalHits() {
return getTotalHitsCount();
}

public int getTotalHitsCount() {
return 0;
}

static int usage(Lib lib) {
return lib.getTotalHits();
}
}
""",
"""
class Lib {
@Deprecated
public int getTotalHits() {
return getTotalHitsCount();
}

public int getTotalHitsCount() {
return 0;
}

static int usage(Lib lib) {
return lib.getTotalHitsCount();
}
}
"""
)
);
}

@Test
void sameArgumentUsedTwice() {
//language=java
Expand Down
Loading