Skip to content

Commit

Permalink
Allow YAML JsonPatchMatcher to match document-level sequences (#4680)
Browse files Browse the repository at this point in the history
  • Loading branch information
knutwannheden authored Nov 18, 2024
1 parent 0cf8d79 commit f2b9232
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -175,18 +175,17 @@ protected boolean shouldVisitNextChild(RuleNode node, Object currentResult) {
public Object visitJsonPath(JsonPathParser.JsonPathContext ctx) {
MATCH:
if (ctx.ROOT() != null || ctx.start.getType() == JsonPathLexer.LBRACK) {
Tree first = cursorPath.get(0);
if (first instanceof Yaml.Document) {
scope = ((Yaml.Document) first).getBlock();
break MATCH;
}
for (Tree tree : cursorPath) {
if (tree instanceof Yaml.Mapping) {
scope = tree;
break MATCH;
}
}
for (Tree t : cursorPath) {
if (t instanceof Yaml.Document && ((Yaml.Document) t).getBlock() instanceof Yaml.Mapping) {
scope = ((Yaml.Document) t).getBlock();
break MATCH;
}
}
scope = null;
}
return super.visitJsonPath(ctx);
Expand All @@ -213,7 +212,7 @@ private JsonPathParser.ExpressionContext getExpressionContext(ParserRuleContext
if (previous.indexOf(current) - 1 < 0 || "$".equals(previous.get(previous.indexOf(current) - 1).getText())) {
List<Object> results = new ArrayList<>();
for (Tree path : cursorPath) {
JsonPathMatcher.JsonPathYamlVisitor v = new JsonPathMatcher.JsonPathYamlVisitor(cursorPath, path, null, false);
JsonPathYamlVisitor v = new JsonPathYamlVisitor(cursorPath, path, null, false);
for (int i = 1; i < ctx.getChildCount(); i++) {
result = v.visit(ctx.getChild(i));
if (result != null) {
Expand All @@ -224,7 +223,7 @@ private JsonPathParser.ExpressionContext getExpressionContext(ParserRuleContext
return results;
// Otherwise, the recursive descent is scoped to the previous match. `$.foo..['find-in-foo']`.
} else {
JsonPathMatcher.JsonPathYamlVisitor v = new JsonPathMatcher.JsonPathYamlVisitor(cursorPath, scope, null, true);
JsonPathYamlVisitor v = new JsonPathYamlVisitor(cursorPath, scope, null, true);
for (int i = 1; i < ctx.getChildCount(); i++) {
result = v.visit(ctx.getChild(i));
if (result != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,36 @@ void allElements() {
);
}

@Test
void documentLevelSequenceWildcard() {
assertMatched(
"$[*].id",
List.of(
"""
- id: 0
- id: 1
- id: 2
"""
),
List.of("id: 0", "id: 1", "id: 2")
);
}

@Test
void documentLevelSequenceSingle() {
assertMatched(
"$[1].id",
List.of(
"""
- id: 0
- id: 1
- id: 2
"""
),
List.of("id: 1")
);
}

@Test
void bracketOperatorByNames() {
assertMatched(
Expand Down

0 comments on commit f2b9232

Please sign in to comment.