Skip to content

Commit b65f9c0

Browse files
Fix anchor on MappingStart in sequence entry losing prefix (#6732)
When a YAML anchor appeared on a MappingStart event inside a sequence (e.g. `- &b\n k2: v2`), the dash prefix was incorrectly truncated from the mapping's format string. This caused the SequenceBuilder to create an entry with isDash=false, producing `- k: v &b\n k2: v2` instead of preserving the original `- k: v\n- &b\n k2: v2`. The fix removes the dash-index truncation of `fmt` in the MappingStart anchor handling. The `fmt` is kept as-is so the SequenceBuilder can properly split it and preserve the dash indicator.
1 parent 1c396f6 commit b65f9c0

3 files changed

Lines changed: 24 additions & 7 deletions

File tree

rewrite-javascript/rewrite/test/yaml/parser.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -485,6 +485,17 @@ describe('Flow mappings without colons (OmitColon marker)', () => {
485485
});
486486
});
487487

488+
describe('Anchors on sequence entries', () => {
489+
490+
test('anchor on mapping in sequence entry', async () => {
491+
const yaml = `- k: v
492+
- &b
493+
k2: v2`;
494+
const result = await parseAndPrint(yaml);
495+
expect(result).toBe(yaml);
496+
});
497+
});
498+
488499
describe('Single-brace template syntax', () => {
489500

490501
test('quoted single-brace templates roundtrip', async () => {

rewrite-yaml/src/main/java/org/openrewrite/yaml/YamlParser.java

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -246,14 +246,7 @@ private Yaml.Documents parseFromInput(Path sourceFile, EncodingDetectingInputStr
246246
if (mappingStartEvent.getAnchor() != null) {
247247
anchor = buildYamlAnchor(reader, lastEnd, fmt, mappingStartEvent.getAnchor(), event.getEndMark().getIndex(), false);
248248
anchors.put(mappingStartEvent.getAnchor(), anchor);
249-
250-
// dashPrefixIndex could be 0 (if anchoring a sequence item) or greater than 0 (if anchoring entire list)
251-
int dashPrefixIndex = commentAwareIndexOf('-', fmt);
252249
lastEnd = lastEnd + mappingStartEvent.getAnchor().length() + fmt.length() + 1;
253-
254-
if (dashPrefixIndex > 0) {
255-
fmt = fmt.substring(0, dashPrefixIndex);
256-
}
257250
}
258251

259252
String fullPrefix = reader.readStringFromBuffer(lastEnd, event.getEndMark().getIndex() - 1);

rewrite-yaml/src/test/java/org/openrewrite/yaml/YamlParserTest.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -761,6 +761,19 @@ void singleBraceTemplateSyntaxUnquoted() {
761761
);
762762
}
763763

764+
@Test
765+
void anchorOnMappingInSequenceEntry() {
766+
rewriteRun(
767+
yaml(
768+
"""
769+
- k: v
770+
- &b
771+
k2: v2
772+
"""
773+
)
774+
);
775+
}
776+
764777
@Test
765778
void literalScalarTrailingNewlineInValue() {
766779
// Literal (|) and folded (>) scalars should keep trailing newlines in their value

0 commit comments

Comments
 (0)