Skip to content

Commit

Permalink
Add logic to quote yaml scalar value (#644)
Browse files Browse the repository at this point in the history
Co-authored-by: Tyler Van Gorder <[email protected]>
  • Loading branch information
tkvangorder and tkvangorder authored Dec 4, 2024
1 parent 0716305 commit a6c6033
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
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: "*"
""")
);
}
}

0 comments on commit a6c6033

Please sign in to comment.