Skip to content

Commit

Permalink
Merge branch 'main' into json-recipes
Browse files Browse the repository at this point in the history
  • Loading branch information
timtebeek authored Jul 30, 2024
2 parents e9b7e66 + 52c87ad commit 6a772a3
Show file tree
Hide file tree
Showing 50 changed files with 1,864 additions and 287 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/receive-pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ jobs:
- org.openrewrite.recipes.RecipeTestingBestPracticesSubset
- org.openrewrite.recipes.RecipeNullabilityBestPracticesSubset
#- org.openrewrite.java.OrderImports
#- org.openrewrite.java.format.EmptyNewlineAtEndOfFile
- org.openrewrite.java.format.EmptyNewlineAtEndOfFile
- org.openrewrite.staticanalysis.InlineVariable
- org.openrewrite.staticanalysis.MissingOverrideAnnotation
- org.openrewrite.staticanalysis.UseDiamondOperator
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,28 +150,30 @@ public Recipe activateRecipes(Iterable<String> activeRecipes) {
}
}
if (!recipesNotFound.isEmpty()) {
@SuppressWarnings("deprecation")
List<String> suggestions = recipesNotFound.stream()
.map(r -> recipesByName.keySet().stream()
.min(comparingInt(a -> StringUtils.getLevenshteinDistance(a, r)))
.orElse(r))
.collect(toList());
String message = String.format("Recipes not found: %s\nDid you mean: %s",
String message = String.format("Recipe(s) not found: %s\nDid you mean: %s",
String.join(", ", recipesNotFound),
String.join(", ", suggestions));
throw new RecipeException(message);
}
if (activatedRecipes.isEmpty()) {
return Recipe.noop();
}
if (activatedRecipes.size() == 1) {
return activatedRecipes.get(0);
}
return new CompositeRecipe(activatedRecipes);
}

public Recipe activateRecipes(String... activeRecipes) {
return activateRecipes(Arrays.asList(activeRecipes));
}

//TODO: Nothing uses this and in most cases it would be a bad idea anyway, should consider removing
public Recipe activateAll() {
return new CompositeRecipe(listRecipes());
}

/**
* @return A list of validations of style names that could be activated.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ public InMemoryLargeSourceSet(List<SourceFile> ls) {
}

protected InMemoryLargeSourceSet(@Nullable InMemoryLargeSourceSet initialState,
@Nullable Map<SourceFile, List<Recipe>> deletions,
List<SourceFile> ls) {
@Nullable Map<SourceFile, List<Recipe>> deletions,
List<SourceFile> ls) {
this.initialState = initialState;
this.ls = ls;
this.deletions = deletions;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
import java.util.function.BiFunction;
import java.util.function.UnaryOperator;

import static java.util.Collections.unmodifiableList;
import static java.util.Collections.unmodifiableSet;
import static java.util.Objects.requireNonNull;
import static org.openrewrite.Recipe.PANIC;

Expand Down Expand Up @@ -105,23 +105,23 @@ public LSS scanSources(LSS sourceSet) {
}

public LSS generateSources(LSS sourceSet) {
List<SourceFile> generatedInThisCycle = allRecipeStack.reduce(sourceSet, recipe, ctx, (acc, recipeStack) -> {
Set<SourceFile> generatedInThisCycle = allRecipeStack.reduce(sourceSet, recipe, ctx, (acc, recipeStack) -> {
Recipe recipe = recipeStack.peek();
if (recipe instanceof ScanningRecipe) {
//noinspection unchecked
ScanningRecipe<Object> scanningRecipe = (ScanningRecipe<Object>) recipe;
List<SourceFile> generated = new ArrayList<>(scanningRecipe.generate(scanningRecipe.getAccumulator(rootCursor, ctx), unmodifiableList(acc), ctx));
List<SourceFile> generated = new ArrayList<>(scanningRecipe.generate(scanningRecipe.getAccumulator(rootCursor, ctx), unmodifiableSet(acc), ctx));
generated.replaceAll(source -> addRecipesThatMadeChanges(recipeStack, source));
acc.addAll(generated);
if (!generated.isEmpty()) {
madeChangesInThisCycle.add(recipe);
}
}
return acc;
}, new ArrayList<>());
}, new TreeSet<>(Comparator.comparing(SourceFile::getSourcePath)));

// noinspection unchecked
return (LSS) sourceSet.generate(generatedInThisCycle);
return (LSS) sourceSet.generate(new ArrayList<>(generatedInThisCycle));
}

public LSS editSources(LSS sourceSet) {
Expand Down Expand Up @@ -238,7 +238,7 @@ private void recordSourceFileResult(@Nullable String beforePath, @Nullable Strin
}

private @Nullable SourceFile handleError(Recipe recipe, SourceFile sourceFile, @Nullable SourceFile after,
Throwable t) {
Throwable t) {
ctx.getOnError().accept(t);

if (t instanceof RecipeRunException) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,16 @@ public static Validated<ExactVersion> build(String pattern) {
}
String versionOnly;
int hyphenIndex = pattern.indexOf('-');
if(hyphenIndex == -1) {
if (hyphenIndex == -1) {
versionOnly = pattern;
} else {
versionOnly = pattern.substring(0, hyphenIndex);
}
if(versionOnly.startsWith("latest") ||
versionOnly.contains("x") ||
versionOnly.contains("^") ||
versionOnly.contains("~") ||
versionOnly.contains(" ")) {
if (versionOnly.startsWith("latest") ||
versionOnly.contains("x") ||
versionOnly.contains("^") ||
versionOnly.contains("~") ||
versionOnly.contains(" ")) {
return Validated.invalid("exactVersion", pattern, "not an exact version number");
}
return Validated.valid("exactVersion", new ExactVersion(pattern));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* Copyright 2024 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.semver;

import org.openrewrite.Validated;
import org.openrewrite.internal.StringUtils;
import org.openrewrite.internal.lang.Nullable;

public class ExactVersionWithPattern extends LatestRelease {
private final String version;

public ExactVersionWithPattern(String version, String metadataPattern) {
super(metadataPattern);
this.version = version;
}

@Override
public boolean isValid(@Nullable String currentVersion, String version) {
return super.isValid(currentVersion, version) &&
super.compare(currentVersion, version, this.version) == 0;
}

public static Validated<ExactVersionWithPattern> build(String toVersion, @Nullable String metadataPattern) {
if (StringUtils.isBlank(metadataPattern)) {
return Validated.invalid("exactVersionWithPattern", metadataPattern, "metadataPattern is null or empty");
}
if (ExactVersion.build(toVersion).isInvalid()) {
return Validated.invalid("exactVersionWithPattern", toVersion, "not an exact version number");
}
return Validated.valid("exactVersionWithPattern", new ExactVersionWithPattern(toVersion, metadataPattern));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ public static Validated<VersionComparator> validate(String toVersion, @Nullable
.or(TildeRange.build(toVersion, metadataPattern))
.or(CaretRange.build(toVersion, metadataPattern))
.or(SetRange.build(toVersion, metadataPattern))
.or(ExactVersionWithPattern.build(toVersion, metadataPattern))
.or(ExactVersion.build(toVersion))
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public TreeVisitor<?, ExecutionContext> getVisitor(AtomicBoolean created) {
@Override
public SourceFile visit(@Nullable Tree tree, ExecutionContext ctx) {
SourceFile sourceFile = (SourceFile) requireNonNull(tree);
if ((created.get() || Boolean.TRUE.equals(overwriteExisting)) && path.equals(sourceFile.getSourcePath())) {
if (Boolean.TRUE.equals(overwriteExisting) && path.equals(sourceFile.getSourcePath())) {
if (sourceFile instanceof PlainText) {
return ((PlainText) sourceFile).withText(fileContents);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,7 @@ void canCallImperativeRecipeWithoutArgsFromDeclarative() {
type: specs.openrewrite.org/v1beta/recipe
name: test.recipe
displayName: Test Recipe
description: Test Recipe.
recipeList:
- org.openrewrite.NoArgRecipe
""",
Expand All @@ -295,6 +296,7 @@ void canCallImperativeRecipeWithUnnecessaryArgsFromDeclarative() {
type: specs.openrewrite.org/v1beta/recipe
name: test.recipe
displayName: Test Recipe
description: Test Recipe.
recipeList:
- org.openrewrite.NoArgRecipe:
foo: bar
Expand All @@ -311,6 +313,7 @@ void canCallRecipeWithNoExplicitConstructor() {
type: specs.openrewrite.org/v1beta/recipe
name: test.recipe
displayName: Test Recipe
description: Test Recipe.
recipeList:
- org.openrewrite.DefaultConstructorRecipe
""",
Expand All @@ -326,18 +329,21 @@ void declarativeRecipeChain() {
type: specs.openrewrite.org/v1beta/recipe
name: test.recipe.a
displayName: Test Recipe
description: Test Recipe.
recipeList:
- test.recipe.b
---
type: specs.openrewrite.org/v1beta/recipe
name: test.recipe.b
displayName: Test Recipe
description: Test Recipe.
recipeList:
- test.recipe.c
---
type: specs.openrewrite.org/v1beta/recipe
name: test.recipe.c
displayName: Test Recipe
description: Test Recipe.
recipeList:
- org.openrewrite.NoArgRecipe
""",
Expand All @@ -354,6 +360,7 @@ void declarativeRecipeChainAcrossFiles() {
type: specs.openrewrite.org/v1beta/recipe
name: test.recipe.c
displayName: Test Recipe
description: Test Recipe.
recipeList:
- org.openrewrite.NoArgRecipe
""".getBytes()),
Expand All @@ -363,6 +370,7 @@ void declarativeRecipeChainAcrossFiles() {
type: specs.openrewrite.org/v1beta/recipe
name: test.recipe.b
displayName: Test Recipe
description: Test Recipe.
recipeList:
- test.recipe.c
""".getBytes()),
Expand All @@ -372,6 +380,7 @@ void declarativeRecipeChainAcrossFiles() {
type: specs.openrewrite.org/v1beta/recipe
name: test.recipe.a
displayName: Test Recipe
description: Test Recipe.
recipeList:
- test.recipe.b
""".getBytes()),
Expand All @@ -391,7 +400,7 @@ void declarativeRecipeChainFromResources() {
void declarativeRecipeChainFromResourcesIncludesImperativeRecipesInDescriptors() {
rewriteRun(spec -> spec.recipeFromResources("test.declarative.sample.a")
.afterRecipe(recipeRun -> assertThat(recipeRun.getChangeset().getAllResults().get(0)
.getRecipeDescriptorsThatMadeChanges().get(0).getRecipeList().get(0).getRecipeList().get(0)
.getRecipeDescriptorsThatMadeChanges().get(0).getRecipeList().get(0)
.getDisplayName()).isEqualTo("Change text")),
text("Hi", "after"));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ void yamlPrecondition() {
---
type: specs.openrewrite.org/v1beta/recipe
name: org.openrewrite.PreconditionTest
description: Test.
preconditions:
- org.openrewrite.text.Find:
find: 1
Expand All @@ -180,6 +181,7 @@ void yamlPreconditionWithScanningRecipe() {
---
type: specs.openrewrite.org/v1beta/recipe
name: org.openrewrite.PreconditionTest
description: Test.
preconditions:
- org.openrewrite.text.Find:
find: 1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,26 +31,24 @@ class SourceFileResultsTest implements RewriteTest {
void hierarchical() {
rewriteRun(
spec -> spec
.recipe(
new ByteArrayInputStream(
.recipeFromYaml(
//language=yml
"""
type: specs.openrewrite.org/v1beta/recipe
name: test.ChangeTextToHello
displayName: Change text to hello
description: Hello world.
recipeList:
- org.openrewrite.text.ChangeText:
toText: Hello!
""".getBytes()
),
- org.openrewrite.text.ChangeText:
toText: Hello!
""",
"test.ChangeTextToHello"
).dataTable(SourcesFileResults.Row.class, rows -> {
assertThat(rows).hasSize(2);
assertThat(rows).hasSize(1);
assertThat(rows.stream().map(SourcesFileResults.Row::getParentRecipe))
.containsExactly("test.ChangeTextToHello", "");
.containsExactly("test.ChangeTextToHello");
assertThat(rows.stream().map(SourcesFileResults.Row::getRecipe))
.containsExactly("org.openrewrite.text.ChangeText", "test.ChangeTextToHello");
.containsExactly("org.openrewrite.text.ChangeText");
}),
text(
"Hi",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,10 @@
*/
package org.openrewrite.text;

import lombok.EqualsAndHashCode;
import lombok.Value;
import org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.Recipe;
import org.openrewrite.test.RewriteTest;

import java.util.Arrays;
import java.util.List;

import static org.openrewrite.test.SourceSpecs.text;

class FindAndReplaceTest implements RewriteTest {
Expand Down Expand Up @@ -57,7 +51,7 @@ void removeWhenNullOrEmpty() {
""",
"""
Foo
Quz
"""
)
Expand Down Expand Up @@ -127,33 +121,14 @@ void dollarSignsTolerated() {
);
}

@Value
@EqualsAndHashCode(callSuper = false)
static class MultiFindAndReplace extends Recipe {

@Override
public String getDisplayName() {
return "Replaces \"one\" with \"two\" then \"three\" then \"four\"";
}

@Override
public String getDescription() {
return "Replaces \"one\" with \"two\" then \"three\" then \"four\".";
}

@Override
public List<Recipe> getRecipeList() {
return Arrays.asList(
new FindAndReplace("one", "two", null, null, null, null, null, null),
new FindAndReplace("two", "three", null, null, null, null, null, null),
new FindAndReplace("three", "four", null, null, null, null, null, null));
}
}

@Test
void successiveReplacement() {
rewriteRun(
spec -> spec.recipe(new MultiFindAndReplace()),
spec -> spec.recipes(
new FindAndReplace("one", "two", null, null, null, null, null, null),
new FindAndReplace("two", "three", null, null, null, null, null, null),
new FindAndReplace("three", "four", null, null, null, null, null, null)
),
text(
"""
one
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@
type: specs.openrewrite.org/v1beta/recipe
name: test.declarative.sample.a
displayName: Test Recipe
description: Test Recipe.
recipeList:
- test.declarative.sample.b
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
type: specs.openrewrite.org/v1beta/recipe
name: test.declarative.sample.b
displayName: Test Recipe
description: Test Recipe.
recipeList:
- org.openrewrite.text.ChangeText:
toText: after
Loading

0 comments on commit 6a772a3

Please sign in to comment.