Fix YamlConfiguration dumping null values and empty tree nodes

This commit is contained in:
Christian Koop 2022-06-26 01:36:54 +02:00
parent 885cc9a87e
commit 02ab8d4bb2
No known key found for this signature in database
GPG Key ID: 89A8181384E010A3
2 changed files with 44 additions and 0 deletions

View File

@ -209,6 +209,8 @@ public class YamlConfiguration implements IConfiguration, HeaderCommentable, Nod
String headerCommentLines = generateHeaderCommentLines();
writer.write(headerCommentLines);
cleanValuesMap(this.values);
if (this.values.size() > 0) {
if (headerCommentLines.length() > 0) {
writer.write(this.yamlDumperOptions.getLineBreak().getString());
@ -343,4 +345,23 @@ public class YamlConfiguration implements IConfiguration, HeaderCommentable, Nod
++currentKeyIndex;
}
}
/**
* This takes a map and removes all keys that have a value of null.<br>
* Additionally, if the value is a {@link Map}, it will be recursively cleaned too.<br>
* {@link Map}s that are or get empty, will be removed (recursively).<br>
*/
protected void cleanValuesMap(Map<?, ?> map) {
for (Object key : map.keySet().toArray()) {
Object value = map.get(key);
if (value instanceof Map) {
cleanValuesMap((Map<?, ?>) value);
}
if (value == null || (value instanceof Map && ((Map<?, ?>) value).isEmpty())) {
map.remove(key);
}
}
}
}

View File

@ -139,6 +139,19 @@ class YamlConfigurationTest {
assertEquals(expectedOutYaml, cfg.toYamlString());
}
@Test
void testYamlWriterWithNullValue() throws IOException {
final YamlConfiguration cfg = new YamlConfiguration();
final StringWriter stringWriter = new StringWriter(1);
cfg.set("null-value", null);
cfg.set("nested.null-value", null);
cfg.save(stringWriter);
assertEquals("", stringWriter.toString());
assertEquals("", cfg.toYamlString());
}
@Test
void testYamlWriterWithNoData() throws IOException {
final YamlConfiguration cfg = new YamlConfiguration();
@ -239,6 +252,16 @@ class YamlConfigurationTest {
assertEquals("value", cfg.get("primitives.map.key"));
}
@Test
void testSetterWithNullValue() {
final YamlConfiguration cfg = new YamlConfiguration();
assertNull(cfg.set("foo.bar.null", "not-null-string"));
assertEquals("not-null-string", cfg.set("foo.bar.null", null));
assertNull(cfg.get("foo.bar.null"));
}
@Test
void testGetNonExistingNestedKey() {
final YamlConfiguration cfg = new YamlConfiguration();