Add file loading

This commit is contained in:
Mike Bierlee 2022-09-24 18:51:32 +03:00
parent a1a99d1dee
commit 20a7c0471b
2 changed files with 19 additions and 7 deletions

View file

@ -12,6 +12,7 @@ module mirage.config;
import std.exception : enforce;
import std.string : split, startsWith, endsWith, join, lastIndexOf;
import std.conv : to, ConvException;
import std.file : readText;
class ConfigReadException : Exception {
this(string msg, string file = __FILE__, size_t line = __LINE__) {
@ -265,8 +266,12 @@ class ConfigDictionary {
}
}
interface ConfigFactory {
ConfigDictionary loadFile(string path);
abstract class ConfigFactory {
ConfigDictionary loadFile(string path) {
auto json = readText(path);
return parseConfig(json);
}
ConfigDictionary parseConfig(string contents);
}

View file

@ -15,11 +15,7 @@ import std.conv : to;
import mirage.config : ConfigFactory, ConfigDictionary, ConfigNode, ValueNode, ObjectNode, ArrayNode, ConfigCreationException;
class JsonConfigFactory : ConfigFactory {
ConfigDictionary loadFile(string path) {
throw new Exception("not yet implemented");
}
ConfigDictionary parseConfig(string contents) {
override ConfigDictionary parseConfig(string contents) {
return parseJson(parseJSON(contents));
}
@ -130,4 +126,15 @@ version (unittest) {
assert(config.get("age") == "8728");
assert(config.get("taxNumber") == null);
}
@("Load JSON file")
unittest {
auto loader = new JsonConfigFactory();
auto config = loader.loadFile("testfiles/groot.json");
assert(config.get("name") == "Groot");
assert(config.get("traits[1]") == "tree");
assert(config.get("age") == "8728");
assert(config.get("taxNumber") == null);
}
}