Skip to content

Commit

Permalink
Merge branch 'main' into fix-remove-unused-imports
Browse files Browse the repository at this point in the history
  • Loading branch information
timtebeek authored Sep 24, 2024
2 parents 6a11dc0 + d2c825c commit 43a8266
Show file tree
Hide file tree
Showing 185 changed files with 4,175 additions and 2,360 deletions.
8 changes: 2 additions & 6 deletions .github/workflows/receive-pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,9 @@ jobs:
displayName: Recipe nullability best practices
description: Use OpenRewrite internal nullability annotations; drop JetBrains annotations; use `package-info.java` instead.
recipeList:
- org.openrewrite.java.ChangeType:
oldFullyQualifiedTypeName: org.jetbrains.annotations.Nullable
newFullyQualifiedTypeName: org.openrewrite.internal.lang.Nullable
- org.openrewrite.java.ChangeType:
oldFullyQualifiedTypeName: jakarta.annotation.Nullable
newFullyQualifiedTypeName: org.openrewrite.internal.lang.Nullable
- org.openrewrite.staticanalysis.NullableOnMethodReturnType
- org.openrewrite.java.RemoveAnnotation:
annotationPattern: '@org.jetbrains.annotations.NotNull'
- org.openrewrite.java.RemoveAnnotation:
annotationPattern: '@jakarta.annotation.Nonnull'
- org.openrewrite.java.jspecify.MigrateToJspecify
4 changes: 2 additions & 2 deletions gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionSha256Sum=5b9c5eb3f9fc2c94abaea57d90bd78747ca117ddbbf96c859d3741181a12bf2a
distributionSha256Sum=31c55713e40233a8303827ceb42ca48a47267a0ad4bab9177123121e71524c26
4 changes: 2 additions & 2 deletions rewrite-core/src/main/java/org/openrewrite/Cursor.java
Original file line number Diff line number Diff line change
Expand Up @@ -187,8 +187,8 @@ public String toString() {
.map(t -> t instanceof Tree ?
t.getClass().getSimpleName() :
t.toString())
.collect(Collectors.joining("->"))
+ "}";
.collect(Collectors.joining("->")) +
"}";
}

public Cursor dropParentUntil(Predicate<Object> valuePredicate) {
Expand Down
10 changes: 5 additions & 5 deletions rewrite-core/src/main/java/org/openrewrite/PathUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,8 @@ private static boolean matchesGlob(String pattern, String path) {
if (!StringUtils.matchesGlob(pathTokens[pathIdxEnd], pattTokens[pattIdxEnd])) {
return false;
}
if (pattIdxEnd == (pattTokens.length - 1)
&& (isFileSeparator(pattern.charAt(pattern.length() - 1)) ^ isFileSeparator(path.charAt(path.length() - 1)))) {
if (pattIdxEnd == (pattTokens.length - 1) &&
(isFileSeparator(pattern.charAt(pattern.length() - 1)) ^ isFileSeparator(path.charAt(path.length() - 1)))) {
return false;
}
pattIdxEnd--;
Expand Down Expand Up @@ -293,8 +293,8 @@ private static boolean isFileSeparator(char ch) {

@SuppressWarnings("SameParameterValue")
private static boolean isFileSeparator(boolean strict, char ch) {
return strict
? ch == File.separatorChar
: ch == UNIX_SEPARATOR || ch == WINDOWS_SEPARATOR;
return strict ?
ch == File.separatorChar :
ch == UNIX_SEPARATOR || ch == WINDOWS_SEPARATOR;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ public final List<Recipe> getRecipeList() {
getName() + " declares the ScanningRecipe " + precondition.getName() + " as a precondition." +
"ScanningRecipe cannot be used as Preconditions.");
}
andPreconditions.add(precondition::getVisitor);
andPreconditions.add(() -> orVisitors(precondition));
}
PreconditionBellwether bellwether = new PreconditionBellwether(Preconditions.and(andPreconditions.toArray(new Supplier[]{})));
List<Recipe> recipeListWithBellwether = new ArrayList<>(recipeList.size() + 1);
Expand All @@ -279,6 +279,19 @@ public final List<Recipe> getRecipeList() {
return recipeListWithBellwether;
}

private static TreeVisitor<?, ExecutionContext> orVisitors(Recipe recipe) {
if (recipe.getRecipeList().isEmpty()) {
return recipe.getVisitor();
}
List<TreeVisitor<?, ExecutionContext>> conditions = new ArrayList<>();
conditions.add(recipe.getVisitor());
for (Recipe r : recipe.getRecipeList()) {
conditions.add(orVisitors(r));
}
//noinspection unchecked
return Preconditions.or(conditions.toArray(new TreeVisitor[0]));
}

private static boolean isScanningRecipe(Recipe recipe) {
if (recipe instanceof ScanningRecipe) {
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -466,8 +466,8 @@ private static boolean matchesGlob(String pattern, String str, boolean caseSensi
if (ch == '*') {
break;
}
if (ch != '?'
&& different(caseSensitive, ch, str.charAt(strIdxStart))) {
if (ch != '?' &&
different(caseSensitive, ch, str.charAt(strIdxStart))) {
return false; // Character mismatch
}
patIdxStart++;
Expand Down Expand Up @@ -554,9 +554,9 @@ private static boolean allStars(String chars, int start, int end) {
}

private static boolean different(boolean caseSensitive, char ch, char other) {
return caseSensitive
? ch != other
: Character.toUpperCase(ch) != Character.toUpperCase(other);
return caseSensitive ?
ch != other :
Character.toUpperCase(ch) != Character.toUpperCase(other);
}

public static String indent(String text) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ public Response send(Request request) {
String methodValue = method.toString();
if (entity.length > 0) {
String contentType = request.getRequestHeaders().get("Content-Type");
MediaType mediaType = contentType != null
? MediaType.get(contentType + "; charset=utf-8")
: MEDIA_TYPE_APPLICATION_JSON;
MediaType mediaType = contentType != null ?
MediaType.get(contentType + "; charset=utf-8") :
MEDIA_TYPE_APPLICATION_JSON;
RequestBody body = RequestBody.create(entity, mediaType);
requestBuilder.method(methodValue, body);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,9 +195,9 @@ public GitProvenance(UUID id,
if (environment instanceof JenkinsBuildEnvironment) {
JenkinsBuildEnvironment jenkinsBuildEnvironment = (JenkinsBuildEnvironment) environment;
try (Repository repository = new RepositoryBuilder().findGitDir(projectDir.toFile()).build()) {
String branch = jenkinsBuildEnvironment.getLocalBranch() != null
? jenkinsBuildEnvironment.getLocalBranch()
: localBranchName(repository, jenkinsBuildEnvironment.getBranch());
String branch = jenkinsBuildEnvironment.getLocalBranch() != null ?
jenkinsBuildEnvironment.getLocalBranch() :
localBranchName(repository, jenkinsBuildEnvironment.getBranch());
return fromGitConfig(repository, branch, getChangeset(repository), gitRemoteParser);
} catch (IllegalArgumentException | GitAPIException e) {
// Silently ignore if the project directory is not a git repository
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ public static BitbucketBuildEnvironment build(UnaryOperator<String> environment)

@Override
public GitProvenance buildGitProvenance() throws IncompleteGitConfigException {
if (StringUtils.isBlank(httpOrigin)
|| StringUtils.isBlank(branch)
|| StringUtils.isBlank(sha)) {
if (StringUtils.isBlank(httpOrigin) ||
StringUtils.isBlank(branch) ||
StringUtils.isBlank(sha)) {
throw new IncompleteGitConfigException();
} else {
return new GitProvenance(UUID.randomUUID(), httpOrigin, branch, sha,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ public interface BuildEnvironment extends Marker {
if (environment.apply("GITLAB_CI") != null) {
return GitlabBuildEnvironment.build(environment);
}
if (environment.apply("CI") != null && environment.apply("GITHUB_ACTION") != null
&& environment.apply("GITHUB_RUN_ID") != null) {
if (environment.apply("CI") != null && environment.apply("GITHUB_ACTION") != null &&
environment.apply("GITHUB_RUN_ID") != null) {
return GithubActionsBuildEnvironment.build(environment);
}
if (environment.apply("DRONE") != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ public static CustomBuildEnvironment build(UnaryOperator<String> environment) {

@Override
public GitProvenance buildGitProvenance() throws IncompleteGitConfigException {
if (StringUtils.isBlank(cloneURL)
|| StringUtils.isBlank(ref)
|| StringUtils.isBlank(sha)) {
if (StringUtils.isBlank(cloneURL) ||
StringUtils.isBlank(ref) ||
StringUtils.isBlank(sha)) {
throw new IncompleteGitConfigException();
} else {
return new GitProvenance(UUID.randomUUID(), cloneURL, ref, sha,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,9 @@ public static DroneBuildEnvironment build(UnaryOperator<String> environment) {

@Override
public GitProvenance buildGitProvenance() throws IncompleteGitConfigException {
if (StringUtils.isBlank(remoteURL)
|| (StringUtils.isBlank(branch) && StringUtils.isBlank(tag))
|| StringUtils.isBlank(commitSha)) {
if (StringUtils.isBlank(remoteURL) ||
(StringUtils.isBlank(branch) && StringUtils.isBlank(tag)) ||
StringUtils.isBlank(commitSha)) {
throw new IncompleteGitConfigException();
}
return new GitProvenance(UUID.randomUUID(), remoteURL,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,16 +67,16 @@ public GitProvenance buildGitProvenance() throws IncompleteGitConfigException {
} else {
gitRef = gitRef.replaceFirst("refs/heads/", "");
}
if (StringUtils.isBlank(ghRef)
|| StringUtils.isBlank(host)
|| StringUtils.isBlank(repository)
|| StringUtils.isBlank(sha)) {
if (StringUtils.isBlank(ghRef) ||
StringUtils.isBlank(host) ||
StringUtils.isBlank(repository) ||
StringUtils.isBlank(sha)) {
throw new IncompleteGitConfigException(
String.format("Invalid GitHub environment with host: %s, branch: %s, " +
"repository: %s, sha: %s", host, ghRef, repository, sha));
}

return new GitProvenance(UUID.randomUUID(), host + "/" + getRepository()
+ ".git", gitRef, getSha(), null, null, emptyList());
return new GitProvenance(UUID.randomUUID(), host + "/" + getRepository() +
".git", gitRef, getSha(), null, null, emptyList());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ public static GitlabBuildEnvironment build(UnaryOperator<String> environment) {

@Override
public GitProvenance buildGitProvenance() throws IncompleteGitConfigException {
if (StringUtils.isBlank(ciRepositoryUrl)
|| StringUtils.isBlank(ciCommitRefName)
|| StringUtils.isBlank(ciCommitSha)) {
if (StringUtils.isBlank(ciRepositoryUrl) ||
StringUtils.isBlank(ciCommitRefName) ||
StringUtils.isBlank(ciCommitSha)) {
throw new IncompleteGitConfigException();
}
return new GitProvenance(UUID.randomUUID(), ciRepositoryUrl, ciCommitRefName, ciCommitSha,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,9 @@ public static Validated<DependencyMatcher> build(String pattern) {
}

public boolean matches(@Nullable String groupId, String artifactId, String version) {
return StringUtils.matchesGlob(groupId, groupPattern)
&& StringUtils.matchesGlob(artifactId, artifactPattern)
&& (versionComparator == null || versionComparator.isValid(null, version));
return StringUtils.matchesGlob(groupId, groupPattern) &&
StringUtils.matchesGlob(artifactId, artifactPattern) &&
(versionComparator == null || versionComparator.isValid(null, version));
}

public boolean matches(@Nullable String groupId, String artifactId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,15 @@
*/
package org.openrewrite.semver;

import lombok.Getter;
import org.jspecify.annotations.Nullable;
import org.openrewrite.Validated;

/**
* Version selector for matching exact version: either explicitly prefixed with "=",
* or implicit default when no other version selectors match.
*/
@Getter
public class ExactVersion extends LatestRelease {
String version;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,14 @@ static int countVersionParts(String version) {
public int compare(@Nullable String currentVersion, String v1, String v2) {
if (v1.equalsIgnoreCase(v2)) {
return 0;
}
if (v1.equalsIgnoreCase("RELEASE")) {
return v2.equalsIgnoreCase("LATEST") ? -1 : 1;
}
if (v1.equalsIgnoreCase("LATEST")) {
} else if (v1.equalsIgnoreCase("LATEST")) {
return 1;
} else if (v2.equalsIgnoreCase("LATEST")) {
return -1;
} else if (v1.equalsIgnoreCase("RELEASE")) {
return 1;
} else if (v2.equalsIgnoreCase("RELEASE")) {
return -1;
}

String nv1 = normalizeVersion(v1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@ public class Semver {
private Semver() {
}

public static boolean isVersion(String version) {
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public static boolean isVersion(@Nullable String version) {
if (version == null) {
return false;
}
return LatestRelease.RELEASE_PATTERN.matcher(version).matches();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,12 @@ public class AppendToTextFile extends ScanningRecipe<AtomicBoolean> {
@Nullable Boolean appendNewline;

@Option(displayName = "Existing file strategy",
description = "Determines behavior if a file exists at this location prior to Rewrite execution.\n\n"
+ "- `Continue`: append new content to existing file contents. If existing file is not plaintext, recipe does nothing.\n"
+ "- `Replace`: remove existing content from file.\n"
+ "- `Leave`: *(default)* do nothing. Existing file is fully preserved.\n\n"
+ "Note: this only affects the first interaction with the specified file per Rewrite execution.\n"
+ "Subsequent instances of this recipe in the same Rewrite execution will always append.",
description = "Determines behavior if a file exists at this location prior to Rewrite execution.\n\n" +
"- `Continue`: append new content to existing file contents. If existing file is not plaintext, recipe does nothing.\n" +
"- `Replace`: remove existing content from file.\n" +
"- `Leave`: *(default)* do nothing. Existing file is fully preserved.\n\n" +
"Note: this only affects the first interaction with the specified file per Rewrite execution.\n" +
"Subsequent instances of this recipe in the same Rewrite execution will always append.",
valid = {"Continue", "Replace", "Leave"},
required = false)
@Nullable Strategy existingFileStrategy;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,65 @@ void yamlPrecondition() {
);
}

@Test
void yamlDeclarativeRecipeAsPrecondition() {
rewriteRun(
spec -> spec.recipeFromYaml(
"""
type: specs.openrewrite.org/v1beta/recipe
name: org.openrewrite.PreconditionTest
description: Test.
preconditions:
- org.openrewrite.DeclarativePrecondition
recipeList:
- org.openrewrite.text.ChangeText:
toText: 3
---
type: specs.openrewrite.org/v1beta/recipe
name: org.openrewrite.DeclarativePrecondition
recipeList:
- org.openrewrite.text.Find:
find: 1
""",
"org.openrewrite.PreconditionTest"
),
text("1", "3"),
text("2")
);
}

@Test
void orPreconditions() {
// As documented https://docs.openrewrite.org/reference/yaml-format-reference#creating-or-preconditions-instead-of-and
rewriteRun(
spec -> spec.recipeFromYaml(
"""
type: specs.openrewrite.org/v1beta/recipe
name: org.sample.DoSomething
description: Test.
preconditions:
- org.sample.FindAnyJson
recipeList:
- org.openrewrite.text.ChangeText:
toText: 2
---
type: specs.openrewrite.org/v1beta/recipe
name: org.sample.FindAnyJson
recipeList:
- org.openrewrite.FindSourceFiles:
filePattern: "**/my.json"
- org.openrewrite.FindSourceFiles:
filePattern: "**/your.json"
- org.openrewrite.FindSourceFiles:
filePattern: "**/our.json"
""",
"org.sample.DoSomething"
),
text("1", "2", spec -> spec.path("a/my.json")),
text("a", spec -> spec.path("a/not-my.json"))
);
}

@Test
void yamlPreconditionWithScanningRecipe() {
rewriteRun(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

import static com.fasterxml.jackson.core.JsonParser.Feature.IGNORE_UNDEFINED;
import static com.fasterxml.jackson.core.JsonParser.Feature.INCLUDE_SOURCE_IN_LOCATION;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,12 @@ void preReleases() {
@Test
void releaseOrLatestKeyword_beatsEverything() {
assertThat(latestRelease.compare(null, "RELEASE", "1.2.3")).isPositive();
assertThat(latestRelease.compare(null, "1.2.3", "RELEASE")).isNegative();
assertThat(latestRelease.compare(null, "RELEASE", "999.999.999")).isPositive();
assertThat(latestRelease.compare(null, "RELEASE", "RELEASE")).isZero();

assertThat(latestRelease.compare(null, "LATEST", "1.2.3")).isPositive();
assertThat(latestRelease.compare(null, "1.2.3", "LATEST")).isNegative();
assertThat(latestRelease.compare(null, "LATEST", "999.999.999")).isPositive();
assertThat(latestRelease.compare(null, "LATEST", "LATEST")).isZero();

Expand Down
Loading

0 comments on commit 43a8266

Please sign in to comment.