Skip to content

Instantly share code, notes, and snippets.

@Bit-Flipper
Created April 11, 2024 11:05
Show Gist options
  • Save Bit-Flipper/3b18c93758d2ccc2e89cdece05a4bfd3 to your computer and use it in GitHub Desktop.
Save Bit-Flipper/3b18c93758d2ccc2e89cdece05a4bfd3 to your computer and use it in GitHub Desktop.
OpenRewrite recipe to demonstrate testing cycle errors
package dev.bitflippers;
import com.google.common.annotations.Beta;
import lombok.EqualsAndHashCode;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.AnnotationMatcher;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaParser;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.tree.J;
import java.util.Comparator;
@EqualsAndHashCode(callSuper = true)
public class AddDummyAnnotation extends Recipe {
@Override
public String getDisplayName() {
return "Test annotation addition recipe";
}
@Override
public String getDescription() {
return "Dummy recipe to show how the OpenRewrite recipe testing framework works with cycles.";
}
private static final AnnotationMatcher BETA_ANNOTATION_MATCHER = new AnnotationMatcher(Beta.class.getTypeName());
@Beta
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new JavaIsoVisitor<>() {
@Override
public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext executionContext) {
multiVariable = super.visitVariableDeclarations(multiVariable, executionContext);
// Uncomment to resolve cycle errors
// if (shouldAddAnnotation(multiVariable)) {
// return multiVariable;
// }
return addDummyBetaAnnotation(multiVariable);
}
private boolean shouldAddAnnotation(J.VariableDeclarations multiVariable) {
return multiVariable.getLeadingAnnotations().stream()
.anyMatch(BETA_ANNOTATION_MATCHER::matches);
}
private J.VariableDeclarations addDummyBetaAnnotation(J.VariableDeclarations multiVariable) {
maybeAddImport(Beta.class.getTypeName());
return JavaTemplate.builder("@Beta")
.javaParser(JavaParser.fromJavaVersion().classpath("guava"))
.imports(Beta.class.getTypeName())
.build()
.apply(getCursor(), multiVariable.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::toString)));
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment