From a928dc2238e0463b6ce91f21b2c5bb518f90558e Mon Sep 17 00:00:00 2001 From: Knut Wannheden Date: Wed, 6 Dec 2023 23:45:32 +0100 Subject: [PATCH] `PreconditionBellwether` must call `isAcceptable()` (#3780) When a precondition visitor extends an `XyzIsoVisitor` class (like `JavaIsoVisitor`) and there overrides the `visit()` method, then this will result in a `ClassCastException` when the visitor is given a source file which is not of that type. --- .../openrewrite/config/DeclarativeRecipe.java | 5 +++++ .../java/search/HasJavaVersionTest.java | 21 +++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/rewrite-core/src/main/java/org/openrewrite/config/DeclarativeRecipe.java b/rewrite-core/src/main/java/org/openrewrite/config/DeclarativeRecipe.java index bc57960c7b2..9fadb27b2a6 100644 --- a/rewrite-core/src/main/java/org/openrewrite/config/DeclarativeRecipe.java +++ b/rewrite-core/src/main/java/org/openrewrite/config/DeclarativeRecipe.java @@ -147,6 +147,11 @@ public String getDescription() { @Override public TreeVisitor getVisitor() { return new TreeVisitor() { + @Override + public boolean isAcceptable(SourceFile sourceFile, ExecutionContext ctx) { + return precondition.isAcceptable(sourceFile, ctx); + } + @Override public @Nullable Tree visit(@Nullable Tree tree, ExecutionContext ctx) { Tree t = precondition.visit(tree, ctx); diff --git a/rewrite-java-test/src/test/java/org/openrewrite/java/search/HasJavaVersionTest.java b/rewrite-java-test/src/test/java/org/openrewrite/java/search/HasJavaVersionTest.java index 5641f33b61b..86b98ac5bbe 100644 --- a/rewrite-java-test/src/test/java/org/openrewrite/java/search/HasJavaVersionTest.java +++ b/rewrite-java-test/src/test/java/org/openrewrite/java/search/HasJavaVersionTest.java @@ -15,12 +15,14 @@ */ package org.openrewrite.java.search; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.openrewrite.test.RewriteTest; import static org.openrewrite.java.Assertions.java; import static org.openrewrite.java.Assertions.version; +import static org.openrewrite.test.SourceSpecs.text; class HasJavaVersionTest implements RewriteTest { @@ -61,4 +63,23 @@ class Test { ) ); } + + @Test + void declarativePrecondition() { + rewriteRun( + spec -> spec.recipeFromYaml(""" + --- + type: specs.openrewrite.org/v1beta/recipe + name: org.openrewrite.PreconditionTest + preconditions: + - org.openrewrite.java.search.HasJavaVersion: + version: 11 + recipeList: + - org.openrewrite.text.ChangeText: + toText: 2 + """, "org.openrewrite.PreconditionTest"), + text("1") + ); + } + }