diff --git a/rewrite-yaml/src/main/java/org/openrewrite/yaml/JsonPathMatcher.java b/rewrite-yaml/src/main/java/org/openrewrite/yaml/JsonPathMatcher.java index a7088ad0b94..99d2c049fb0 100644 --- a/rewrite-yaml/src/main/java/org/openrewrite/yaml/JsonPathMatcher.java +++ b/rewrite-yaml/src/main/java/org/openrewrite/yaml/JsonPathMatcher.java @@ -94,12 +94,35 @@ public boolean matches(Cursor cursor) { private static List resolvedAncestors(Cursor cursor) { ArrayDeque deque = new ArrayDeque<>(); + Map resolved = new IdentityHashMap<>(); for (Iterator it = cursor.getPath(Tree.class::isInstance); it.hasNext(); ) { Tree tree = (Tree) it.next(); - tree = tree instanceof Yaml ? new ReplaceAliasWithAnchorValueVisitor().visitNonNull(tree, 0) : tree; + if (tree instanceof Yaml.Document) { + tree = new ReplaceAliasWithAnchorValueVisitor() { + @Override + public @Nullable Yaml visit(@Nullable Tree tree, Integer p) { + Yaml updated = super.visit(tree, p); + if (tree != null && updated != tree) { + resolved.put(tree, updated); + } + return updated; + } + }.visitNonNull(tree, 0); + deque.addFirst(tree); + break; + } deque.addFirst(tree); } - return new ArrayList<>(deque); + ArrayList list = new ArrayList<>(deque); + if (!resolved.isEmpty()) { + for (int i = 0; i < list.size(); i++) { + Tree tree = list.get(i); + if (resolved.containsKey(tree)) { + list.set(i, resolved.get(tree)); + } + } + } + return list; } private JsonPathParser jsonPath() {