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 logic to quote yaml scalar value #644

Merged
merged 1 commit into from
Dec 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import org.openrewrite.properties.tree.Properties;
import org.openrewrite.yaml.tree.Yaml;

import java.util.regex.Pattern;

@EqualsAndHashCode(callSuper = false)
@Value
public class ChangeSpringPropertyValue extends Recipe {
Expand Down Expand Up @@ -68,7 +70,7 @@ public String getDescription() {
Boolean relaxedBinding;

@Override
public Validated validate() {
public Validated<Object> validate() {
return super.validate().and(
Validated.test("oldValue", "is required if `regex` is enabled", oldValue,
value -> !(Boolean.TRUE.equals(regex) && StringUtils.isNullOrEmpty(value))));
Expand All @@ -77,7 +79,8 @@ public Validated validate() {
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
Recipe changeProperties = new org.openrewrite.properties.ChangePropertyValue(propertyKey, newValue, oldValue, regex, relaxedBinding);
Recipe changeYaml = new org.openrewrite.yaml.ChangePropertyValue(propertyKey, newValue, oldValue, regex, relaxedBinding, null);
String yamlValue = quoteValue(newValue) ? "\"" + newValue + "\"" : newValue;
Recipe changeYaml = new org.openrewrite.yaml.ChangePropertyValue(propertyKey, yamlValue, oldValue, regex, relaxedBinding, null);
return new TreeVisitor<Tree, ExecutionContext>() {
@Override
public @Nullable Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
Expand All @@ -90,4 +93,9 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {
}
};
}

private static final Pattern scalarNeedsAQuote = Pattern.compile("[^a-zA-Z\\d\\s]*");
private boolean quoteValue(String value) {
return scalarNeedsAQuote.matcher(value).matches();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,27 @@ void regex() {
yaml("server.port: 53", "server.port: 8053")
);
}

@Test
void yamlValueQuoted() {
rewriteRun(
spec -> spec.recipe(new ChangeSpringPropertyValue("management.endpoints.web.exposure.include", "*", null, null, null)),
properties("management.endpoints.web.exposure.include=info,health", "management.endpoints.web.exposure.include=*"),
yaml(
"""
management:
endpoints:
web:
exposure:
include: info,health
""",
"""
management:
endpoints:
web:
exposure:
include: "*"
""")
);
}
}
Loading