Singleton

Apache 2.0

Used 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:

---
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.

org.openrewrite.Singleton
mod run . --recipe=org.openrewrite.Singleton

Install it once from Recipe actions, then run it on every repository under the current directory. New to the Moderne CLI? Set it up.