Skip to content

Commit

Permalink
#357 read escaped keys correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
amihaiemil committed Jun 13, 2020
1 parent df5bc39 commit c4f4d4d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 12 deletions.
35 changes: 23 additions & 12 deletions src/main/java/com/amihaiemil/eoyaml/ReadYamlMapping.java
Original file line number Diff line number Diff line change
Expand Up @@ -179,23 +179,34 @@ public Comment comment() {
* The YamlNode value associated with a String (scalar) key.
* @param key String key.
* @return YamlNode.
* @checkstyle ReturnCount (50 lines)
*/
private YamlNode valueOfStringKey(final String key) {
YamlNode value = null;
for (final YamlLine line : this.significant) {
final String trimmed = line.trimmed();
if(trimmed.endsWith(key + ":")
|| trimmed.matches("^" + key + "\\:[ ]*\\>$")
|| trimmed.matches("^" + key + "\\:[ ]*\\|$")
) {
value = this.significant.toYamlNode(line);
} else if(trimmed.startsWith(key + ":")
&& trimmed.length() > 1
) {
value = new ReadPlainScalar(this.all, line);
final String[] keys = new String[] {
key,
"\"" + key + "\"",
"'" + key + "'",
};
for(final String tryKey : keys) {
for (final YamlLine line : this.significant) {
final String trimmed = line.trimmed();
if(trimmed.endsWith(tryKey + ":")
|| trimmed.matches("^" + tryKey + "\\:[ ]*\\>$")
|| trimmed.matches("^" + tryKey + "\\:[ ]*\\|$")
) {
value = this.significant.toYamlNode(line);
} else if(trimmed.startsWith(tryKey + ":")
&& trimmed.length() > 1
) {
value = new ReadPlainScalar(this.all, line);
}
if(value != null) {
return value;
}
}
}
return value;
return null;
}

/**
Expand Down
15 changes: 15 additions & 0 deletions src/test/java/com/amihaiemil/eoyaml/ReadYamlMappingTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -1062,4 +1062,19 @@ public void returnsNullOnMisreadYamlSequence_MappingWithSequenceKey() {

MatcherAssert.assertThat(map.yamlSequence(key), Matchers.nullValue());
}

/**
* ReadYamlMapping returns the correct value
* when the key is wrapped in quotes.
*/
@Test
public void returnsValueOfStringKeyWithQuotes() {
final List<YamlLine> lines = new ArrayList<>();
lines.add(new RtYamlLine("\"a-key\": someValue", 0));
final YamlMapping map = new ReadYamlMapping(new AllYamlLines(lines));
MatcherAssert.assertThat(
map.string("a-key"),
Matchers.equalTo("someValue")
);
}
}

0 comments on commit c4f4d4d

Please sign in to comment.