From 29c5a0a1028f48310c7cf9d6977226d929edd8f3 Mon Sep 17 00:00:00 2001 From: Daniel-I-Am Date: Fri, 16 Oct 2020 17:04:54 +0200 Subject: [PATCH] Allow regex in keys --- ChaosBot/Configuration.cs | 36 ++++++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/ChaosBot/Configuration.cs b/ChaosBot/Configuration.cs index 7f6037d..2246f2e 100644 --- a/ChaosBot/Configuration.cs +++ b/ChaosBot/Configuration.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Text.RegularExpressions; using ChaosBot.Repositories; using Microsoft.Extensions.Configuration; @@ -37,7 +38,7 @@ namespace ChaosBot public Configuration() { _appSettingsWrapper = Program.AppSettingsHandler; - + if (_appSettingsWrapper == null) throw new NullReferenceException("Program.AppSettingsHandler is unset"); } @@ -50,16 +51,18 @@ namespace ChaosBot */ public T GetValue(string key, T defaultValue, ulong? guildId = null) { - if (!ConfigurationFlags.ContainsKey(key)) + bool keyExists = TryGetKeyFromRegexMatch(key, out string realKey); + + if (!keyExists) throw new ArgumentException($"Configuration does not contain key '{key}'"); - if (!(ConfigurationFlags[key] == typeof(T))) - throw new ArgumentException($"Configuration flag '{key}<{ConfigurationFlags[key]}>' does not have type '{typeof(T)}'"); + if (!(ConfigurationFlags[realKey] == typeof(T))) + throw new ArgumentException($"Configuration flag '{realKey}<{ConfigurationFlags[realKey]}>' does not have type '{typeof(T)}'"); if (guildId.HasValue) - return ConfigurationRepository.GetValue(key, guildId.Value, defaultValue); + return ConfigurationRepository.GetValue(realKey, guildId.Value, defaultValue); - return _appSettingsWrapper.GetValue(key, defaultValue); + return _appSettingsWrapper.GetValue(realKey, defaultValue); } public T GetValue(string key) @@ -80,5 +83,26 @@ namespace ChaosBot { return ConfigurationFlags.ToImmutableDictionary(); } + + private bool TryGetKeyFromRegexMatch(string key, out string realKey) + { + if (ConfigurationFlags.ContainsKey(key)) + { + realKey = key; + return true; + } + + foreach (string configurationFlagsKey in ConfigurationFlags.Keys) + { + if (new Regex(configurationFlagsKey).IsMatch(key)) + { + realKey = key; + return true; + } + } + + realKey = null; + return false; + } } }