diff --git a/rewrite-yaml/src/main/java/org/openrewrite/yaml/CopyValue.java b/rewrite-yaml/src/main/java/org/openrewrite/yaml/CopyValue.java index 3d1caf72117..77d5e923458 100644 --- a/rewrite-yaml/src/main/java/org/openrewrite/yaml/CopyValue.java +++ b/rewrite-yaml/src/main/java/org/openrewrite/yaml/CopyValue.java @@ -72,7 +72,8 @@ public String getInstanceNameSuffix() { public String getDescription() { return "Copies a YAML value from one key to another. " + "The existing key/value pair remains unaffected by this change. " + - "If either the source key path does not exist, no value will be copied."; + "Attempts to merge the copied value into the new key if it already exists. " + + "Attempts to create the new key if it does not exist."; } @Data @@ -92,6 +93,15 @@ public Accumulator getInitialValue(ExecutionContext ctx) { public TreeVisitor getScanner(Accumulator acc) { TreeVisitor visitor = new YamlIsoVisitor() { final JsonPathMatcher oldPathMatcher = new JsonPathMatcher(oldKeyPath); + + @Override + public Yaml.Documents visitDocuments(Yaml.Documents documents, ExecutionContext executionContext) { + if(acc.snippet == null) { + return super.visitDocuments(documents, executionContext); + } + return documents; + } + @Override public Yaml.Mapping.Entry visitMappingEntry(Yaml.Mapping.Entry entry, ExecutionContext ctx) { Yaml.Mapping.Entry source = super.visitMappingEntry(entry, ctx); diff --git a/rewrite-yaml/src/test/java/org/openrewrite/yaml/CopyValueTest.java b/rewrite-yaml/src/test/java/org/openrewrite/yaml/CopyValueTest.java index dca3fdd178d..6e527d51784 100644 --- a/rewrite-yaml/src/test/java/org/openrewrite/yaml/CopyValueTest.java +++ b/rewrite-yaml/src/test/java/org/openrewrite/yaml/CopyValueTest.java @@ -32,6 +32,26 @@ public void defaults(RecipeSpec spec) { spec.executionContext(ctx); } + @Test + void changeCurrentFileWhenNull() { + rewriteRun( + spec -> spec.recipe( + new CopyValue("$.source", null, "$.destination", null) + ), + yaml( + """ + source: value + destination: original + """, + """ + source: value + destination: value + """, + spec -> spec.path("a.yml") + ) + ); + } + @Test void changeOnlyMatchingFile() { rewriteRun(