Skip to content

Commit

Permalink
Allow FindLiterals to match text blocks
Browse files Browse the repository at this point in the history
For `FindLiterals` it makes more sense to match the regex against the literal's value, as that will then have the quotes stripped.

Also for other literals it makes sense to match the pattern against the value, so that e.g. a pattern `1000` also matches an integer literal like `1_000`.
  • Loading branch information
knutwannheden committed Feb 25, 2025
1 parent 777d6e1 commit 6cc119a
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class FindLiteralsTest implements RewriteTest {

@DocumentExample
@Test
void findLiterals() {
void string() {
rewriteRun(
spec -> spec.recipe(new FindLiterals("Hello.*")),
java(
Expand All @@ -42,4 +42,48 @@ class Test {
)
);
}

@Test
void textBlock() {
rewriteRun(
spec -> spec.recipe(new FindLiterals("(?s)Hello.*")),
java(
"""
class Test {
String s = \"""
Hello Jonathan
\""";
}
""",
"""
class Test {
String s = /*~~>*/\"""
Hello Jonathan
\""";
}
"""
)
);
}

@Test
void number() {
rewriteRun(
spec -> spec.recipe(new FindLiterals("1000")),
java(
"""
class Test {
int i1 = 1000;
int i2 = 1_000;
}
""",
"""
class Test {
int i1 = /*~~>*/1000;
int i2 = /*~~>*/1_000;
}
"""
)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,10 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {
@Override
public J.Literal visitLiteral(J.Literal literal, ExecutionContext ctx) {
if (literal.getValueSource() != null) {
if (literal.getType() == JavaType.Primitive.String) {
if (!literal.getValueSource().isEmpty() && compiledPattern.matcher(literal.getValueSource().substring(1, literal.getValueSource().length() - 1)).matches()) {
return SearchResult.found(literal);
}
if (literal.getValue() != null && compiledPattern.matcher(literal.getValue().toString()).matches()) {
return SearchResult.found(literal);
}
if (compiledPattern.matcher(literal.getValueSource()).matches()) {
if (literal.getType() != JavaType.Primitive.String && compiledPattern.matcher(literal.getValueSource()).matches()) {
return SearchResult.found(literal);
}
}
Expand Down

0 comments on commit 6cc119a

Please sign in to comment.