Add uber convenience function 'loadConfig'

This commit is contained in:
Mike Bierlee 2022-09-25 19:38:37 +03:00
parent e62fe7c9ae
commit daf4c9029b
2 changed files with 27 additions and 4 deletions

View file

@ -12,9 +12,12 @@
module mirage.config;
import std.exception : enforce;
import std.string : split, startsWith, endsWith, join, lastIndexOf, strip;
import std.string : split, startsWith, endsWith, join, lastIndexOf, strip, toLower;
import std.conv : to, ConvException;
import std.file : readText;
import std.path : extension;
import mirage.json : loadJsonConfig;
/**
* Used by the ConfigDictionary when something goes wrong when reading configuration.
@ -370,6 +373,16 @@ abstract class ConfigFactory {
ConfigDictionary parseConfig(string contents);
}
ConfigDictionary loadConfig(const string configPath) {
auto extension = configPath.extension.toLower;
if (extension == ".json") {
return loadJsonConfig(configPath);
}
throw new ConfigCreationException(
"File extension '" ~ extension ~ "' is not recognized as a supported config file format. Please use a specific function to load it, such as 'loadJsonConfig()'");
}
version (unittest) {
import std.exception : assertThrown;
import std.math.operations : isClose;
@ -603,4 +616,14 @@ version (unittest) {
assert(config.get(" que. pasa hombre ") == "not much");
}
@("Load configurations using the loadConfig convenience function")
unittest {
auto jsonConfig = loadConfig("testfiles/groot.json");
assert(jsonConfig.get("name") == "Groot");
assert(jsonConfig.get("traits[1]") == "tree");
assert(jsonConfig.get("age") == "8728");
assert(jsonConfig.get("taxNumber") == null);
}
}

View file

@ -103,7 +103,7 @@ class JsonConfigFactory : ConfigFactory {
* json = Text contents of the config to be parsed.
* Returns: The parsed configuration.
*/
ConfigDictionary parseJsonConfig(string json) {
ConfigDictionary parseJsonConfig(const string json) {
return new JsonConfigFactory().parseConfig(json);
}
@ -114,7 +114,7 @@ ConfigDictionary parseJsonConfig(string json) {
* contents = JSONValue config to be parsed.
* Returns: The parsed configuration.
*/
ConfigDictionary parseJsonConfig(JSONValue json) {
ConfigDictionary parseJsonConfig(const JSONValue json) {
return new JsonConfigFactory().parseJson(json);
}
@ -125,7 +125,7 @@ ConfigDictionary parseJsonConfig(JSONValue json) {
* filePath = Path to the JSON configuration file.
* Returns: The loaded configuration.
*/
ConfigDictionary loadJsonConfig(string filePath) {
ConfigDictionary loadJsonConfig(const string filePath) {
return new JsonConfigFactory().loadFile(filePath);
}