Skip to content

Commit

Permalink
Speed up scanning phase if the value has already been found
Browse files Browse the repository at this point in the history
  • Loading branch information
sambsnyd committed Feb 13, 2024
1 parent 14f9b7d commit e121981
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
12 changes: 11 additions & 1 deletion rewrite-yaml/src/main/java/org/openrewrite/yaml/CopyValue.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -92,6 +93,15 @@ public Accumulator getInitialValue(ExecutionContext ctx) {
public TreeVisitor<?, ExecutionContext> getScanner(Accumulator acc) {
TreeVisitor<?, ExecutionContext> visitor = new YamlIsoVisitor<ExecutionContext>() {
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);
Expand Down
20 changes: 20 additions & 0 deletions rewrite-yaml/src/test/java/org/openrewrite/yaml/CopyValueTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down

0 comments on commit e121981

Please sign in to comment.