Skip to content
Open
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 @@ -22,6 +22,7 @@
import org.openrewrite.internal.ListUtils;
import org.openrewrite.internal.NameCaseConvention;
import org.openrewrite.internal.StringUtils;
import org.openrewrite.yaml.internal.BlockScalarUtils;
import org.openrewrite.yaml.tree.Yaml;

import java.util.Iterator;
Expand Down Expand Up @@ -110,10 +111,14 @@ public Yaml.Mapping.Entry visitMappingEntry(Yaml.Mapping.Entry entry, ExecutionC
private Yaml.@Nullable Block updateValue(Yaml.Block value) {
if (value instanceof Yaml.Scalar) {
Yaml.Scalar scalar = (Yaml.Scalar) value;
Yaml.Scalar newScalar = scalar.withValue(Boolean.TRUE.equals(regex) ?
scalar.getValue().replaceAll(Objects.requireNonNull(oldValue), newValue) :
newValue);
return scalar.getValue().equals(newScalar.getValue()) ? null : newScalar;
String body = BlockScalarUtils.getBody(scalar);
String updatedBody = Boolean.TRUE.equals(regex) ?
body.replaceAll(Objects.requireNonNull(oldValue), newValue) :
newValue;
if (body.equals(updatedBody)) {
return null;
}
return BlockScalarUtils.withBody(scalar, updatedBody);
}
if (value instanceof Yaml.Sequence) {
Yaml.Sequence sequence = (Yaml.Sequence) value;
Expand Down
30 changes: 20 additions & 10 deletions rewrite-yaml/src/main/java/org/openrewrite/yaml/ChangeValue.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.jspecify.annotations.Nullable;
import org.openrewrite.*;
import org.openrewrite.marker.Markers;
import org.openrewrite.yaml.internal.BlockScalarUtils;
import org.openrewrite.yaml.tree.Yaml;

import static org.openrewrite.Tree.randomId;
Expand Down Expand Up @@ -66,26 +67,35 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {
@Override
public Yaml.Mapping.Entry visitMappingEntry(Yaml.Mapping.Entry entry, ExecutionContext ctx) {
Yaml.Mapping.Entry e = super.visitMappingEntry(entry, ctx);
if (matcher.matches(getCursor()) && (!(e.getValue() instanceof Yaml.Scalar) || !((Yaml.Scalar) e.getValue()).getValue().equals(value))) {
Yaml.Anchor anchor = (e.getValue() instanceof Yaml.Scalar) ? ((Yaml.Scalar) e.getValue()).getAnchor() : null;
Yaml.Tag tag = (e.getValue() instanceof Yaml.Scalar) ? ((Yaml.Scalar) e.getValue()).getTag() : null;
String prefix = e.getValue() instanceof Yaml.Sequence ? ((Yaml.Sequence) e.getValue()).getOpeningBracketPrefix() : e.getValue().getPrefix();
e = e.withValue(
new Yaml.Scalar(randomId(), prefix, Markers.EMPTY,
Yaml.Scalar.Style.PLAIN, anchor, tag, value)
);
if (matcher.matches(getCursor()) && (!(e.getValue() instanceof Yaml.Scalar) || !BlockScalarUtils.getBody((Yaml.Scalar) e.getValue()).equals(value))) {
if (e.getValue() instanceof Yaml.Scalar && isBlockStyle((Yaml.Scalar) e.getValue())) {
e = e.withValue(BlockScalarUtils.withBody((Yaml.Scalar) e.getValue(), value));
} else {
Yaml.Anchor anchor = (e.getValue() instanceof Yaml.Scalar) ? ((Yaml.Scalar) e.getValue()).getAnchor() : null;
Yaml.Tag tag = (e.getValue() instanceof Yaml.Scalar) ? ((Yaml.Scalar) e.getValue()).getTag() : null;
String prefix = e.getValue() instanceof Yaml.Sequence ? ((Yaml.Sequence) e.getValue()).getOpeningBracketPrefix() : e.getValue().getPrefix();
e = e.withValue(
new Yaml.Scalar(randomId(), prefix, Markers.EMPTY,
Yaml.Scalar.Style.PLAIN, anchor, tag, value)
);
}
}
return e;
}

@Override
public Yaml.Scalar visitScalar(Yaml.Scalar scalar, ExecutionContext ctx) {
Yaml.Scalar s = super.visitScalar(scalar, ctx);
if (matcher.matches(getCursor())) {
s = s.withValue(value);
if (matcher.matches(getCursor()) && !BlockScalarUtils.getBody(s).equals(value)) {
s = BlockScalarUtils.withBody(s, value);
}
return s;
}

private boolean isBlockStyle(Yaml.Scalar s) {
return s.getStyle() == Yaml.Scalar.Style.FOLDED ||
s.getStyle() == Yaml.Scalar.Style.LITERAL;
}
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,11 @@ public Yaml.Mapping visitMapping(Yaml.Mapping mapping, ExecutionContext ctx) {
entry = entry.withPrefix(firstDeletedPrefix);
} else if (previousWasDeleted && !entries.isEmpty() && !containsNewline(entry.getPrefix())) {
entry = entry.withPrefix("\n" + entry.getPrefix());
} else if (previousWasDeleted && !entries.isEmpty()
&& endsWithBlockScalar(entries.get(entries.size() - 1))
&& containsNewline(entry.getPrefix())) {
// Block-scalar predecessor already owns the boundary newline; strip the duplicate.
entry = entry.withPrefix(stripLeadingLineBreak(entry.getPrefix()));
}
entries.add(entry);
previousWasDeleted = false;
Expand Down Expand Up @@ -257,6 +262,32 @@ private static boolean containsOnlyWhitespace(@Nullable String str) {
return true;
}

private static String stripLeadingLineBreak(String s) {
if (s.startsWith("\r\n")) {
return s.substring(2);
}
if (s.startsWith("\n") || s.startsWith("\r")) {
return s.substring(1);
}
// Line break not at the start — strip the first one found.
int idx = -1;
int idxN = s.indexOf('\n');
int idxR = s.indexOf('\r');
if (idxN >= 0 && (idxR < 0 || idxN < idxR)) {
idx = idxN;
} else if (idxR >= 0) {
idx = idxR;
}
if (idx < 0) {
return s;
}
int after = idx + 1;
if (s.charAt(idx) == '\r' && after < s.length() && s.charAt(after) == '\n') {
after++;
}
return s.substring(0, idx) + s.substring(after);
}

private static boolean containsNewline(@Nullable String str) {
return str != null && str.indexOf('\n') >= 0;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
/*
* Copyright 2026 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.internal;

import org.openrewrite.internal.StringUtils;
import org.openrewrite.yaml.tree.Yaml;

/**
* Internal helpers for safely mutating FOLDED ({@code >}, {@code >-}, {@code >+}) and
* LITERAL ({@code |}, {@code |-}, {@code |+}) block scalars: the {@link Yaml.Scalar#value}
* field carries the block envelope (chomp indicator, indented body, trailing whitespace
* bounding the next sibling), so a naïve Lombok-generated {@code withValue} replacement
* corrupts the surrounding structure.
*
* <p><b>TODO:</b> promote these onto {@link Yaml.Scalar} as instance {@code getBody} /
* {@code withBody} methods once enough downstream CLI bundles ship a {@code rewrite-yaml}
* including them — promoting now would {@code NoSuchMethodError} customer recipes that
* adopted the new API but load against an older bundled {@code Yaml.Scalar}.
*/
public final class BlockScalarUtils {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not super comfortable with Utils classes. Can you search for where else we would put such convience classes often?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's already a StringUtils in the same package. In the ideal, these would have just been put directly into Yaml.Scalar and not had a utility class at all, but given that changes the available method list on a core tree type, it would mean that newer recipes using those methods but running on an older CLI would more than likely end up throwing NoSuchMethodError, unless I've misunderstood the whole parent-loading thing.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These should probably just be methods on Yaml.Scalar itself


private BlockScalarUtils() {
}

/**
* Returns the body content of {@code scalar}, stripped of any style-specific envelope.
* For PLAIN and quoted styles this returns {@link Yaml.Scalar#value} verbatim. For block
* styles the body is dedented to column zero with interior line breaks normalized to
* {@code \n} (so callers can compare or regex against it irrespective of the file's
* CRLF/LF convention).
*/
public static String getBody(Yaml.Scalar scalar) {
if (!isBlockStyle(scalar)) {
return scalar.getValue();
}
String value = scalar.getValue();
int headerEnd = value.indexOf('\n');
if (headerEnd < 0) {
return "";
}
int bodyEnd = value.length();
while (bodyEnd > headerEnd + 1 && Character.isWhitespace(value.charAt(bodyEnd - 1))) {
bodyEnd--;
}
if (bodyEnd <= headerEnd + 1) {
return "";
}
String bodyRegion = value.substring(headerEnd + 1, bodyEnd);
int indent = 0;
while (indent < bodyRegion.length() && bodyRegion.charAt(indent) == ' ') {
indent++;
}
String indentStr = bodyRegion.substring(0, indent);
String[] lines = bodyRegion.split("\r\n|\r|\n", -1);
StringBuilder out = new StringBuilder(bodyRegion.length());
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
if (indent > 0 && line.startsWith(indentStr)) {
line = line.substring(indent);
}
if (i > 0) {
out.append('\n');
}
out.append(line);
}
return out.toString();
}

/** {@link #withBody(Yaml.Scalar, String, int)} with a 2-space empty-body indent fallback. */
public static Yaml.Scalar withBody(Yaml.Scalar scalar, String newBody) {
return withBody(scalar, newBody, 2);
}

/**
* Returns a copy of {@code scalar} with its body replaced by {@code newBody}. For PLAIN
* and quoted styles this just sets {@link Yaml.Scalar#value} (via the Lombok-generated
* {@code withValue}); for block styles the chomp indicator, header newline, body indent,
* and trailing whitespace are preserved, and each line of {@code newBody} is emitted in
* the existing value's line-ending convention. {@code defaultIndentSpaces} is used as the
* body indent width when the existing block scalar has an empty body — pass an
* {@code IndentsStyle#getIndentSize()} to honor the document's configured indent.
*/
public static Yaml.Scalar withBody(Yaml.Scalar scalar, String newBody, int defaultIndentSpaces) {
if (!isBlockStyle(scalar)) {
return scalar.withValue(newBody);
}
String value = scalar.getValue();
int headerEnd = value.indexOf('\n');
String header = headerEnd < 0 ? value : value.substring(0, headerEnd + 1);
String newLine = (headerEnd > 0 && value.charAt(headerEnd - 1) == '\r') ? "\r\n" : "\n";
int bodyEnd = value.length();
while (bodyEnd > 0 && Character.isWhitespace(value.charAt(bodyEnd - 1))) {
bodyEnd--;
}
String indent;
if (headerEnd >= 0 && headerEnd + 1 < bodyEnd) {
int indentEnd = headerEnd + 1;
while (indentEnd < bodyEnd && value.charAt(indentEnd) == ' ') {
indentEnd++;
}
indent = value.substring(headerEnd + 1, indentEnd);
if (indent.isEmpty()) {
indent = StringUtils.repeat(" ", defaultIndentSpaces);
}
} else {
indent = StringUtils.repeat(" ", defaultIndentSpaces);
}
String trailing = value.substring(bodyEnd);
String[] lines = newBody.split("\r\n|\r|\n", -1);
StringBuilder body = new StringBuilder();
for (int i = 0; i < lines.length; i++) {
if (i > 0) {
body.append(newLine);
}
if (!lines[i].isEmpty()) {
body.append(indent).append(lines[i]);
}
}
return scalar.withValue(header + body + trailing);
}

private static boolean isBlockStyle(Yaml.Scalar scalar) {
return scalar.getStyle() == Yaml.Scalar.Style.FOLDED ||
scalar.getStyle() == Yaml.Scalar.Style.LITERAL;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.openrewrite.SourceFile;
import org.openrewrite.Tree;
import org.openrewrite.trait.Reference;
import org.openrewrite.yaml.internal.BlockScalarUtils;
import org.openrewrite.yaml.tree.Yaml;

public abstract class YamlReference implements Reference {
Expand All @@ -40,7 +41,7 @@ public boolean supportsRename() {
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));
return BlockScalarUtils.withBody((Yaml.Scalar) tree, renamer.rename(this));
}
throw new IllegalArgumentException("cursor.getValue() must be an Yaml.Scalar but is: " + tree.getClass());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.openrewrite.trait.SimpleTraitMatcher;
import org.openrewrite.trait.Trait;
import org.openrewrite.yaml.JsonPathMatcher;
import org.openrewrite.yaml.internal.BlockScalarUtils;
import org.openrewrite.yaml.tree.Yaml;

@AllArgsConstructor
Expand Down Expand Up @@ -52,7 +53,7 @@ public Yaml.Scalar getValueAsScalar() {
}

public YamlValue withValue(String newValue) {
Yaml.Scalar value = getValueAsScalar().withValue(newValue);
Yaml.Scalar value = BlockScalarUtils.withBody(getValueAsScalar(), newValue);
cursor = new Cursor(cursor.getParent(), getTree().withValue(value));
return this;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,11 @@ class Scalar implements Block, YamlKey {
@Nullable
Tag tag;

/**
Comment thread
steve-aom-elliott marked this conversation as resolved.
* For FOLDED/LITERAL scalars this includes the chomp indicator, header newline,
* indented body, and trailing whitespace bounding the next sibling — so the
* Lombok-generated {@code withValue} cannot safely rewrite a block scalar's body.
*/
String value;

public enum Style {
Expand Down
Loading
Loading