Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add initial support for java references for yaml #4698

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import static org.openrewrite.java.Assertions.java;
import static org.openrewrite.properties.Assertions.properties;
import static org.openrewrite.xml.Assertions.xml;
import static org.openrewrite.yaml.Assertions.yaml;

@SuppressWarnings("ConstantConditions")
class ChangePackageTest implements RewriteTest {
Expand Down Expand Up @@ -1724,7 +1725,25 @@ void changePackageInSpringXml() {
"""
)
);
}

@Test
void changePackageInYaml() {
rewriteRun(
spec -> spec.recipe(new ChangePackage("java.lang", "java.cool", true)),
yaml(
"""
root:
a: java.lang.String
b: java.lang.test.String
c: String
""", """
root:
a: java.cool.String
b: java.cool.test.String
c: String
""", spec -> spec.path("application.yaml")
));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import static org.openrewrite.java.Assertions.java;
import static org.openrewrite.properties.Assertions.properties;
import static org.openrewrite.xml.Assertions.xml;
import static org.openrewrite.yaml.Assertions.yaml;

@SuppressWarnings("ConstantConditions")
class ChangeTypeTest implements RewriteTest {
Expand Down Expand Up @@ -2079,4 +2080,25 @@ void changeTypeInPropertiesFile() {
""", spec -> spec.path("application.properties"))
);
}

@Test
void changeTypeInYaml() {
rewriteRun(
spec -> spec.recipe(new ChangeType("java.lang.String", "java.lang.Integer", true)),
yaml(
"""
root:
a: java.lang.String
b: java.lang.StringBuilder
c: java.lang.test.String
d: String
""", """
root:
a: java.lang.Integer
b: java.lang.StringBuilder
c: java.lang.test.String
d: String
""", spec -> spec.path("application.yaml")
));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -119,5 +119,4 @@ public boolean matchesReference(Reference reference) {
public Reference.Renamer createRenamer(String newName) {
return reference -> newName;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/*
* 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.yaml.trait;

import lombok.Value;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;
import org.openrewrite.*;
import org.openrewrite.trait.Reference;
import org.openrewrite.trait.SimpleTraitMatcher;
import org.openrewrite.yaml.tree.Yaml;

import java.util.HashSet;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Pattern;

@Incubating(since = "8.40.3")
@Value
public class YamlReference implements Reference {
Cursor cursor;
Kind kind;

@Override
public Kind getKind() {
return kind;
}

@Override
public String getValue() {
if (getTree() instanceof Yaml.Scalar) {
return ((Yaml.Scalar) getTree()).getValue();
}
throw new IllegalArgumentException("getTree() must be an Yaml.Document: " + getTree().getClass());
}

@Override
public boolean supportsRename() {
return true;
}

/**
* {@inheritDoc}
*/
@Override
public Tree rename(Renamer renamer, Cursor cursor, ExecutionContext ctx) {
Tree tree = cursor.getValue();
if (tree instanceof Yaml.Scalar) {
return ((Yaml.Scalar) tree).withValue(renamer.rename(this));
}
throw new IllegalArgumentException("cursor.getValue() must be an Yaml.Scalar but is: " + tree.getClass());
}

@SuppressWarnings("unused")
public static class SpringApplicationYamlReferenceProvider implements Reference.Provider {
private static final Predicate<String> applicationPropertiesMatcher = Pattern.compile("^application(-\\w+)?\\.(yaml|yml)$").asPredicate();

@Override
public boolean isAcceptable(SourceFile sourceFile) {
return sourceFile instanceof Yaml.Documents && applicationPropertiesMatcher.test(sourceFile.getSourcePath().getFileName().toString());
}

@Override
public @NonNull Set<Reference> getReferences(SourceFile sourceFile) {
Set<Reference> references = new HashSet<>();
new Matcher().asVisitor(reference -> {
references.add(reference);
return reference.getTree();
}).visit(sourceFile, 0);
return references;
}

private static class Matcher extends SimpleTraitMatcher<YamlReference> {
private static final Pattern javaFullyQualifiedTypePattern = Pattern.compile("\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*\\.\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*(?:\\.\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*)*");

@Override
protected @Nullable YamlReference test(Cursor cursor) {
Object value = cursor.getValue();
if (value instanceof Yaml.Scalar && javaFullyQualifiedTypePattern.matcher(((Yaml.Scalar) value).getValue()).matches()) {
return new YamlReference(cursor, determineKind(((Yaml.Scalar) value).getValue()));
}
return null;
}

private Kind determineKind(String value) {
return Character.isUpperCase(value.charAt(value.lastIndexOf('.') + 1)) ? Kind.TYPE : Kind.PACKAGE;
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* 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.
*/
@NullMarked
@NonNullFields
package org.openrewrite.yaml.trait;

import org.jspecify.annotations.NullMarked;
import org.openrewrite.internal.lang.NonNullFields;
28 changes: 27 additions & 1 deletion rewrite-yaml/src/main/java/org/openrewrite/yaml/tree/Yaml.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,15 @@

import lombok.*;
import lombok.experimental.FieldDefaults;
import lombok.experimental.NonFinal;
import org.jspecify.annotations.Nullable;
import org.openrewrite.*;
import org.openrewrite.marker.Markers;
import org.openrewrite.yaml.YamlVisitor;
import org.openrewrite.yaml.internal.YamlPrinter;

import java.beans.Transient;
import java.lang.ref.SoftReference;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
Expand Down Expand Up @@ -60,8 +63,10 @@ default <P> boolean isAcceptable(TreeVisitor<?, P> v, P p) {

@Value
@EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true)
@RequiredArgsConstructor
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@With
class Documents implements Yaml, SourceFile {
class Documents implements Yaml, SourceFileWithReferences {
@EqualsAndHashCode.Include
UUID id;

Expand Down Expand Up @@ -125,6 +130,27 @@ public Documents withPrefix(String prefix) {
public <P> TreeVisitor<?, PrintOutputCapture<P>> printer(Cursor cursor) {
return new YamlPrinter<>();
}

@Nullable
@NonFinal
transient SoftReference<References> references;

@Transient
@Override
public References getReferences() {
References cache;
if (this.references == null) {
cache = References.build(this);
this.references = new SoftReference<>(cache);
} else {
cache = this.references.get();
if (cache == null || cache.getSourceFile() != this) {
cache = References.build(this);
this.references = new SoftReference<>(cache);
}
}
return cache;
}
}

@Value
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
org.openrewrite.yaml.trait.YamlReference$SpringApplicationYamlReferenceProvider
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
* 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.yaml.trait;

import org.intellij.lang.annotations.Language;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.openrewrite.test.RewriteTest;
import org.openrewrite.trait.Reference;

import static org.assertj.core.api.Assertions.assertThat;
import static org.openrewrite.yaml.Assertions.yaml;

class YamlReferenceTest implements RewriteTest {
@Language("yml")
private static final String YAML = """
root:
a: java.lang.String
b: java.lang
c: String
recipelist:
- org.openrewrite.java.DoSomething:
option: 'org.foo.Bar'
""";


@ParameterizedTest
@CsvSource({
"application.yaml",
"application.yml",
"application-test.yaml",
"application-test.yml",
"/foo/bar/application-test.yaml",
"/foo/bar/application-test.yml",
})
void findJavaReferencesInYamlProperties(String filename) {
rewriteRun(
yaml(
YAML,
spec -> spec.path(filename).afterRecipe(doc -> {
assertThat(doc.getReferences().getReferences()).satisfiesExactlyInAnyOrder(
ref -> {
assertThat(ref.getKind()).isEqualTo(Reference.Kind.TYPE);
assertThat(ref.getValue()).isEqualTo("java.lang.String");
},
ref -> {
assertThat(ref.getKind()).isEqualTo(Reference.Kind.PACKAGE);
assertThat(ref.getValue()).isEqualTo("java.lang");
},
ref -> {
assertThat(ref.getKind()).isEqualTo(Reference.Kind.TYPE);
assertThat(ref.getValue()).isEqualTo("org.openrewrite.java.DoSomething");
},
ref -> {
assertThat(ref.getKind()).isEqualTo(Reference.Kind.TYPE);
assertThat(ref.getValue()).isEqualTo("org.foo.Bar");
});
}))
);
}

@ParameterizedTest
@CsvSource({
"application-.yaml",
"application-.yml",
"application.test.yaml",
"application.test.yml",
"other-application.yaml",
"other-application.yml",
"other.yaml",
"other.yml",
"/foo/bar/other.yaml",
"/foo/bar/other.yml"
})
void noReferencesInMismatchedFilenames(String filename) {
rewriteRun(
yaml(
YAML,
spec -> spec.path(filename).afterRecipe(doc -> assertThat(doc.getReferences().getReferences()).isEmpty())
)
);
}
}