diff --git a/rewrite-yaml/src/main/java/org/openrewrite/yaml/ChangePropertyKey.java b/rewrite-yaml/src/main/java/org/openrewrite/yaml/ChangePropertyKey.java index e06cda1432a..4fd7ab31254 100755 --- a/rewrite-yaml/src/main/java/org/openrewrite/yaml/ChangePropertyKey.java +++ b/rewrite-yaml/src/main/java/org/openrewrite/yaml/ChangePropertyKey.java @@ -350,7 +350,8 @@ public Yaml.Mapping visitMapping(Yaml.Mapping mapping, P p) { } if (entries.size() == 1) { - entries = ListUtils.map(entries, e -> e.withPrefix("")); + String firstEntryPrefix = m.getEntries().get(0).getPrefix(); + entries = ListUtils.map(entries, e -> e.withPrefix(firstEntryPrefix)); } if (changed) { diff --git a/rewrite-yaml/src/test/java/org/openrewrite/yaml/ChangePropertyKeyTest.java b/rewrite-yaml/src/test/java/org/openrewrite/yaml/ChangePropertyKeyTest.java index dc3f005589e..9708f414bb2 100644 --- a/rewrite-yaml/src/test/java/org/openrewrite/yaml/ChangePropertyKeyTest.java +++ b/rewrite-yaml/src/test/java/org/openrewrite/yaml/ChangePropertyKeyTest.java @@ -51,6 +51,53 @@ void singleEntry() { ); } + @Issue("https://github.com/openrewrite/rewrite/issues/2608") + @Test + void moveSubpropertyOut() { + rewriteRun( + spec -> spec.recipe(new ChangePropertyKey("foo.bar", "bar", null, null, null)), + yaml( + """ + foo: + bar: + prop: val + other: other-val + """, + """ + foo: + other: other-val + bar: + prop: val + """ + ) + ); + } + + @Issue("https://github.com/openrewrite/rewrite/issues/2608") + @Test + void multiDocument() { + rewriteRun( + spec -> spec.recipe(new ChangePropertyKey("foo.bar", "bar", null, null, null)), + yaml( + """ + a: b + --- + foo: + bar: + prop: val + other: other-val + """, + """ + a: b + --- + other: other-val + bar: + prop: val + """ + ) + ); + } + @Issue("https://github.com/openrewrite/rewrite/issues/1873") @Test void shorterNewKeyWithIndentedConfig() {