Skip to content

Commit d9459d0

Browse files
authored
Fix AddKeyValue logging parser errors for trailing dot in keyPath (#7327)
* Fix AddKeyValue logging parser errors for trailing dot in keyPath (#6207) Normalize trailing dot in JsonPathMatcher constructor so that `$.` is treated as `$`, preventing ANTLR from printing a parse error to stderr. * Add @issue annotation to trailing dot test
1 parent aae20a5 commit d9459d0

3 files changed

Lines changed: 27 additions & 2 deletions

File tree

rewrite-json/src/main/java/org/openrewrite/json/AddKeyValue.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ public class AddKeyValue extends Recipe {
3939

4040
@Option(displayName = "Key path",
4141
description = "A JsonPath expression to locate the *parent* JSON entry.",
42-
example = "'$.subjects.*' or '$.' or '$.x[1].y.*' etc.")
42+
example = "'$.subjects.*' or '$' or '$.x[1].y.*' etc.")
4343
String keyPath;
4444

4545
@Option(displayName = "Key",

rewrite-json/src/main/java/org/openrewrite/json/JsonPathMatcher.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,9 @@ public class JsonPathMatcher {
5252
private JsonPathParser.@Nullable JsonPathContext parsed;
5353

5454
public JsonPathMatcher(String jsonPath) {
55-
this.jsonPath = jsonPath;
55+
this.jsonPath = jsonPath.endsWith(".") && jsonPath.length() > 1
56+
? jsonPath.substring(0, jsonPath.length() - 1)
57+
: jsonPath;
5658
}
5759

5860
public <T> Optional<T> find(Cursor cursor) {

rewrite-json/src/test/java/org/openrewrite/json/AddKeyValueTest.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import org.junit.jupiter.api.Test;
1919
import org.openrewrite.DocumentExample;
20+
import org.openrewrite.Issue;
2021
import org.openrewrite.test.RewriteTest;
2122

2223
import static org.openrewrite.json.Assertions.json;
@@ -105,6 +106,28 @@ void shouldAppendToNestedObjectInArray() {
105106
);
106107
}
107108

109+
@Issue("https://github.com/openrewrite/rewrite/issues/6207")
110+
@Test
111+
void shouldAppendSimpleValueWithTrailingDot() {
112+
rewriteRun(
113+
spec -> spec.recipe(new AddKeyValue("$.", "surname", "\"Doe\"", false)),
114+
//language=json
115+
json(
116+
"""
117+
{
118+
"name": "John"
119+
}
120+
""",
121+
"""
122+
{
123+
"name": "John",
124+
"surname": "Doe"
125+
}
126+
"""
127+
)
128+
);
129+
}
130+
108131
@Test
109132
void shouldNotAppendIfExists() {
110133
rewriteRun(

0 commit comments

Comments
 (0)