Singleton
org.openrewrite.Singletonorg.openrewrite:rewrite-coreUsed as a precondition to ensure that a recipe attempts to make changes only once. Accidentally including multiple copies/instances of the same large composite recipes is a common mistake. If those recipes are marked with this precondition the performance penalty is limited. This recipe does nothing useful run on its own.
## Usage in YAML recipes
Add org.openrewrite.Singleton as a precondition:
``yaml
---
type: specs.openrewrite.org/v1beta/recipe
name: com.example.Append
displayName: My recipe
preconditions:
- org.openrewrite.Singleton
recipeList:
- org.openrewrite.text.AppendToTextFile:
relativeFileName: report.txt
content: 'Recipe executed'
## Usage in Java recipes
Wrap visitors with Singleton.singleton(this, visitor) to ensure only the first *equivalent* recipe instance makes changes:
java
@Override
public TreeVisitor<?, ExecutionContext> getVisitor(Accumulator acc) {
return singleton(this, new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
// Your transformation logic
return tree;
}
});
}
@Override
public Collection<SourceFile> generate(Accumulator acc, ExecutionContext ctx) {
if (!isSingleton(this, ctx)) {
return Collections.emptyList();
}
// Generate new sources
return results;
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor(Accumulator acc) {
return singleton(this, new TreeVisitor<Tree, ExecutionContext>() {
// Visitor logic
});
}
**Note:** Singleton status is determined by the recipe's equals() and hashCode() methods. If equivalent instances of a recipe are not considered singletons, ensure your recipe class correctly implements these methods. The easiest way is to use Lombok's @Value annotation on your recipe class, which automatically generates correct equals() and hashCode()` implementations based on all fields.
Usage
This recipe has no required configuration options. You’ll need the Moderne CLI configured before running the command below.
mod run . --recipe org.openrewrite.SingletonIf the recipe isn’t available locally, install it with:
mod config recipes jar install org.openrewrite:rewrite-core:8.88.0Data tables
Structured output this recipe can produce.
- Source files that had resultsSource files that were modified by the recipe run.
org.openrewrite.table.SourcesFileResults - Source files that had search resultsSearch results that were found during the recipe run.
org.openrewrite.table.SearchResults - Source files that errored on a recipeThe details of all errors produced by a recipe run.
org.openrewrite.table.SourcesFileErrors - Recipe performanceStatistics used in analyzing the performance of recipes.
org.openrewrite.table.RecipeRunStats